repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/ui/network_page.rs
nmrs-gui/src/ui/network_page.rs
use glib::clone; use gtk::prelude::*; use gtk::{Align, Box, Button, Image, Label, Orientation}; use nmrs::models::NetworkInfo; use nmrs::NetworkManager; use std::cell::RefCell; use std::rc::Rc; type OnSuccessCallback = Rc<RefCell<Option<Rc<dyn Fn()>>>>; pub struct NetworkPage { root: gtk::Box, title: gtk::Label, status: gtk::Label, strength: gtk::Label, bars: gtk::Label, bssid: gtk::Label, freq: gtk::Label, channel: gtk::Label, mode: gtk::Label, rate: gtk::Label, security: gtk::Label, current_ssid: Rc<RefCell<String>>, on_success: OnSuccessCallback, } impl NetworkPage { pub fn new(stack: &gtk::Stack) -> Self { let root = Box::new(Orientation::Vertical, 12); root.add_css_class("network-page"); let back = Button::with_label("← Back"); back.add_css_class("back-button"); back.set_halign(Align::Start); back.set_cursor_from_name(Some("pointer")); back.connect_clicked(clone![ #[weak] stack, move |_| { stack.set_visible_child_name("networks"); } ]); root.append(&back); let header = Box::new(Orientation::Horizontal, 6); let icon = Image::from_icon_name("network-wireless-signal-excellent-symbolic"); icon.set_pixel_size(24); let title = Label::new(None); title.add_css_class("network-title"); let spacer = Box::new(Orientation::Horizontal, 0); spacer.set_hexpand(true); let forget_btn = Button::with_label("Forget"); forget_btn.add_css_class("forget-button"); forget_btn.set_halign(Align::End); forget_btn.set_valign(Align::Center); forget_btn.set_cursor_from_name(Some("pointer")); let current_ssid = Rc::new(RefCell::new(String::new())); let on_success_callback: OnSuccessCallback = Rc::new(RefCell::new(None)); { let stack_clone = stack.clone(); let current_ssid_clone = current_ssid.clone(); let on_success_clone = on_success_callback.clone(); forget_btn.connect_clicked(move |_| { let stack = stack_clone.clone(); let ssid = current_ssid_clone.borrow().clone(); let on_success = on_success_clone.clone(); glib::MainContext::default().spawn_local(async move { if let Ok(nm) = NetworkManager::new().await { if nm.forget(&ssid).await.is_ok() { stack.set_visible_child_name("networks"); if let Some(callback) = on_success.borrow().as_ref() { callback(); } } } }); }); } header.append(&icon); header.append(&title); header.append(&spacer); header.append(&forget_btn); root.append(&header); let basic_box = Box::new(Orientation::Vertical, 6); basic_box.add_css_class("basic-section"); let basic_header = Label::new(Some("Basic")); basic_header.add_css_class("section-header"); basic_box.append(&basic_header); let status = Label::new(None); let strength = Label::new(None); let bars = Label::new(None); Self::add_row(&basic_box, "Connection Status", &status); Self::add_row(&basic_box, "Signal Strength", &strength); Self::add_row(&basic_box, "Bars", &bars); root.append(&basic_box); let advanced_box = Box::new(Orientation::Vertical, 8); advanced_box.add_css_class("advanced-section"); let advanced_header = Label::new(Some("Advanced")); advanced_header.add_css_class("section-header"); advanced_box.append(&advanced_header); let bssid = Label::new(None); let freq = Label::new(None); let channel = Label::new(None); let mode = Label::new(None); let rate = Label::new(None); let security = Label::new(None); Self::add_row(&advanced_box, "BSSID", &bssid); Self::add_row(&advanced_box, "Frequency", &freq); Self::add_row(&advanced_box, "Channel", &channel); Self::add_row(&advanced_box, "Mode", &mode); Self::add_row(&advanced_box, "Speed", &rate); Self::add_row(&advanced_box, "Security", &security); root.append(&advanced_box); Self { root, title, status, strength, bars, bssid, freq, channel, mode, rate, security, current_ssid, on_success: on_success_callback, } } pub fn set_on_success(&self, callback: Rc<dyn Fn()>) { *self.on_success.borrow_mut() = Some(callback); } fn add_row(parent: &gtk::Box, key_text: &str, val_widget: &gtk::Label) { let row = Box::new(Orientation::Vertical, 3); row.set_halign(Align::Start); let key = Label::new(Some(key_text)); key.add_css_class("info-label"); key.set_halign(Align::Start); val_widget.add_css_class("info-value"); val_widget.set_halign(Align::Start); row.append(&key); row.append(val_widget); parent.append(&row); } pub fn update(&self, info: &NetworkInfo) { self.current_ssid.replace(info.ssid.clone()); self.title.set_text(&info.ssid); self.status.set_text(&info.status); self.strength.set_text(&format!("{}%", info.strength)); self.bars.set_text(&info.bars); self.bssid.set_text(&info.bssid); self.freq.set_text( &info .freq .map(|f| format!("{:.1} GHz", f as f32 / 1000.0)) .unwrap_or_else(|| "-".into()), ); self.channel.set_text( &info .channel .map(|c| c.to_string()) .unwrap_or_else(|| "-".into()), ); self.mode.set_text(&info.mode); self.rate.set_text( &info .rate_mbps .map(|r| format!("{r:.2} Mbps")) .unwrap_or_else(|| "-".into()), ); self.security.set_text(&info.security); } pub fn widget(&self) -> &gtk::Box { &self.root } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/objects/theme.rs
nmrs-gui/src/objects/theme.rs
use gtk::glib; use gtk::subclass::prelude::ObjectSubclassIsExt; mod imp { use super::*; use crate::objects::theme::glib::subclass::prelude::ObjectImpl; use crate::objects::theme::glib::subclass::prelude::ObjectSubclass; use std::cell::RefCell; #[derive(Default)] pub struct Theme { pub label: RefCell<String>, } #[glib::object_subclass] impl ObjectSubclass for Theme { const NAME: &'static str = "ThemeObject"; type Type = super::Theme; } impl ObjectImpl for Theme {} } glib::wrapper! { pub struct Theme(ObjectSubclass<imp::Theme>); } impl Theme { pub fn new(label: &str) -> Self { let obj: Self = glib::Object::new(); obj.imp().label.replace(label.to_string()); obj } pub fn label(&self) -> String { self.imp().label.borrow().clone() } }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/src/objects/mod.rs
nmrs-gui/src/objects/mod.rs
pub mod theme;
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/tests/style_test.rs
nmrs-gui/tests/style_test.rs
#[test] fn style_css_loads() { if std::env::var("CI").is_ok() { return; } gtk::init().unwrap(); nmrs_gui::style::load_css(); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
cachebag/nmrs
https://github.com/cachebag/nmrs/blob/411987cb7691206b7135594ef65d3f37bc1e7958/nmrs-gui/tests/smoke_test.rs
nmrs-gui/tests/smoke_test.rs
#[test] fn app_initializes_without_panic() { // Skip when no display (e.g. in CI) if std::env::var("CI").is_ok() { return; } gtk::init().unwrap(); let result = std::panic::catch_unwind(|| { nmrs_gui::run().ok(); }); assert!(result.is_ok(), "UI startup panicked"); }
rust
MIT
411987cb7691206b7135594ef65d3f37bc1e7958
2026-01-04T20:24:43.919455Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/server/src/handlers.rs
server/src/handlers.rs
use axum::{ extract::{Multipart, Path, State}, http::StatusCode, response::IntoResponse, Json, }; use serde::{Deserialize, Serialize}; use tracing::debug; use crate::{ utils::{extract_file_content, read_file}, AppState, }; #[derive(Deserialize)] pub struct InputPrompt { user_query: String, doc_name: String, } #[derive(Serialize)] pub struct DocInfo { name: String, } pub async fn doc_names(State(state): State<AppState>) -> impl IntoResponse { match state.processor.vec_store.list_collections().await { Ok(collection_names) => { let result: Vec<DocInfo> = collection_names .iter() .map(|name| DocInfo { name: name.to_string(), }) .collect(); Json(result).into_response() } Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), } } pub async fn file_handler(Path(file_name): Path<String>) -> impl IntoResponse { match extract_file_content(file_name.as_str()) { Ok(data) => data.into_response(), Err(_) => { return (StatusCode::NOT_FOUND, "File not found or cannot be read.").into_response() } } } pub async fn upload_file(State(state): State<AppState>, multipart: Multipart) -> impl IntoResponse { let file_names = match read_file(multipart).await { Ok(file_names) => file_names, Err(e) => { debug!("unable to read the file: {}", e); vec![] } }; if file_names.len() == 0 { return (StatusCode::BAD_REQUEST, "no pdf files were uploaded").into_response(); } let mut processed_files = vec![]; for file_name in file_names.iter() { match state.processor.process_file(file_name.as_str()).await { Ok(()) => processed_files.push(file_name), Err(e) => { eprintln!("error occurred:: {}", e.to_string()); } }; } if processed_files.len() == file_names.len() { (StatusCode::OK, "files uploaded successfully").into_response() } else { ( StatusCode::INTERNAL_SERVER_ERROR, "one or more uploads failed".to_string(), ) .into_response() } } pub async fn prompt_handler( State(state): State<AppState>, Json(data): Json<InputPrompt>, ) -> impl IntoResponse { let user_query = data.user_query; let doc_name = data.doc_name; let processor = state.processor; match processor .process_prompt(user_query.as_str(), doc_name.as_str()) .await { Ok(response) => (StatusCode::OK, response).into_response(), Err(e) => { eprintln!("error occurred:: {}", e.to_string()); (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response() } } }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/server/src/processor.rs
server/src/processor.rs
use tokio::task; use tracing::debug; use uuid::Uuid; use crate::{ utils::{ chunk_text, extract_file_content, get_content_embeddings, send_request, ConfigVar, ModelKind, }, vector_db::VectorStore, }; use anyhow::{anyhow, Context, Ok, Result}; pub struct Processor { pub settings: ConfigVar, pub vec_store: VectorStore, } impl Processor { pub fn new(settings: ConfigVar, vec_store: VectorStore) -> Self { Self { settings, vec_store, } } // process_file splits the text into chunks so to generate the embeddings // for proper context length and saves them to the db pub async fn process_file(&self, file_name: &str) -> Result<()> { let chunks = self.process_chunks(file_name)?; let embeddings = self.process_embeddings(chunks.to_owned()).await.unwrap(); let coll_name = file_name.split_once(".pdf").unwrap().0; self.save_embeddings(coll_name, embeddings.to_owned()) .await?; Ok(()) } // process_prompt gets the similar cosine embeddings for the user prompt // and sets the context for LLM to get the result generated as per the context pub async fn process_prompt(&self, user_query: &str, doc_name: &str) -> Result<String> { // split user query into chunks let chunk_size = self .settings .embedding_model_chunk_size .as_ref() .expect("required chunk size"); let chunks = chunk_text(&user_query, *chunk_size); let embeddings = self .process_embeddings(chunks.to_owned()) .await .context("unable to process the embeddings")?; // get all the payloads similar to prompt embedding let mut all_payloads = vec![]; if let Some(split_name) = doc_name.split_once(".pdf") { let coll_name = split_name.0; for embedding in embeddings { let payloads = self .vec_store .search_result(coll_name, embedding.1) .await .with_context(|| format!("unable to fetch the result for {}", coll_name))?; debug!("Payloads:: {:?}", payloads); all_payloads.extend(payloads); } } else { debug!("error handling fileName ..."); return Err(anyhow!("bad request - doc type is incorrect...")); } // set the LLM context let context = all_payloads.join(","); let (generate_model_url, generate_model_name) = self .settings .get_model_details(ModelKind::Generate) .context("unable to fetch the model details")?; // final prompt to the LLM let prompt = format!( "You are an expert providing factually accurate answers. Use only the information from the context to generate your answer. If the context doesn't contain relevant information say I don't know as context doesn't have much info. Context: {context} Question: {user_query} Answer(only use the context for your answer)" ); let res = send_request( generate_model_url.as_str(), generate_model_name.as_str(), prompt.as_str(), ) .await .context("send request to LLM operation failed")?; let res_json: serde_json::Value = serde_json::from_str(res.as_str()) .context("parsing response into value type failed")?; let response: String = serde_json::from_value(res_json["response"].clone()) .context("parsing string from value type failed")?; Ok(response) } // process_chunks splits the large text into chunks pub fn process_chunks(&self, file_name: &str) -> Result<Vec<String>> { let chunk_size = self .settings .embedding_model_chunk_size .as_ref() .expect("required chunk size"); let content = extract_file_content(file_name).context("failed to extract the file content")?; let chunks = chunk_text(&content, *chunk_size); Ok(chunks) } // process_embedding generates the embeddings for different chunk texts parallely pub async fn process_embeddings( &self, chunks: Vec<String>, ) -> Result<Vec<(String, Vec<f32>, String)>> { let mut tasks = vec![]; for (_i, chunk) in chunks.into_iter().enumerate() { let settings = self.settings.clone(); tasks.push(task::spawn(async move { let chunk_clone = chunk.clone(); let embedding = get_content_embeddings(settings, chunk_clone.as_str()) .await .unwrap_or_else(|e| { debug!("Error: {}", e); vec![] }); (Uuid::new_v4().to_string(), embedding.clone(), chunk_clone) })) } let results = futures::future::join_all(tasks).await; let embeddings: Vec<(String, Vec<f32>, String)> = results.into_iter().map(|res| res.unwrap()).collect(); Ok(embeddings) } // save_embeddings saves the embeddings to the vector DB pub async fn save_embeddings( &self, coll_name: &str, embeddings: Vec<(String, Vec<f32>, String)>, ) -> Result<()> { self.vec_store .store_embeddings(coll_name, embeddings) .await?; Ok(()) } }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/server/src/utils.rs
server/src/utils.rs
use std::{fs, io::Write}; use axum::{ extract::{Multipart, Request}, middleware, response::Response, }; use reqwest::Client; use serde_json::json; use config::{Config, FileFormat}; use tracing::{debug, info}; use anyhow::{anyhow, Context, Ok, Result}; pub enum ModelKind { Generate, Embedding, } // log_request is the basic logging middleware for the server pub async fn log_request(req: Request, next: middleware::Next) -> Response { info!("Incoming request: {} {}", req.method(), req.uri()); let response = next.run(req).await; info!("Response status: {}", response.status()); response } #[derive(serde_derive::Deserialize, Clone, Debug)] pub struct ConfigVar { pub embedding_model_url: Option<String>, pub embedding_model_name: Option<String>, pub generate_model_url: Option<String>, pub generate_model_name: Option<String>, pub db_url: Option<String>, pub embedding_model_chunk_size: Option<usize>, } impl ConfigVar { //get the model details from the config var based on kind enum pub fn get_model_details(&self, kind: ModelKind) -> Result<(&String, &String)> { match kind { ModelKind::Generate => { let model_url = &self .generate_model_url .as_ref() .expect("model url is expected"); let model_name = &self .generate_model_name .as_ref() .expect("model name is expected"); Ok((model_url, model_name)) } ModelKind::Embedding => { let model_url = &self .embedding_model_url .as_ref() .expect("model url is expected"); let model_name = &self .embedding_model_name .as_ref() .expect("model name is expected"); Ok((model_url, model_name)) } } } } // fetch the config variables pub fn get_settings() -> ConfigVar { let yaml_data = include_str!("../env.yaml"); let settings = Config::builder() .add_source(config::File::from_str(yaml_data, FileFormat::Yaml)) .build() .expect("setting file is expected to read the input variables"); let config: ConfigVar = settings.try_deserialize().unwrap(); config } // extract the file content pub fn extract_file_content(file_name: &str) -> Result<String> { let file_path = format!("./uploads/{}", file_name); match pdf_extract::extract_text(file_path) { std::result::Result::Ok(content) => Ok(content), Err(e) => { debug!("failed to read the file: {}", e.to_string()); Err(anyhow::Error::new(e).context("Failed to read the file")) } } } // chunk the large text based on chunk size pub fn chunk_text(text: &str, chunk_size: usize) -> Vec<String> { text.chars() .collect::<Vec<char>>() .chunks(chunk_size) .map(|chunk| chunk.iter().collect()) .collect() } // send_request helps to send the request to ollama api pub async fn send_request(url: &str, model_name: &str, prompt: &str) -> Result<String> { let client = Client::new(); let req_body = json!({ "model": model_name, "prompt": prompt, "stream": false, }); let response = client .post(url) .header("Content-Type", "application/json") .json(&req_body) .send() .await?; let text_result = response.text().await?; Ok(text_result) } // get the content embeddings from the embedding gen model pub async fn get_content_embeddings(settings: ConfigVar, content: &str) -> Result<Vec<f32>> { let (model_url, model_name) = settings.get_model_details(ModelKind::Embedding).unwrap(); let response = send_request(model_url.as_str(), model_name.as_str(), content).await?; let response_json: serde_json::Value = serde_json::from_str(response.as_str())?; let embeddings: Vec<f32> = response_json["embedding"] .as_array() .unwrap() .iter() .map(|v| v.as_f64().unwrap() as f32) .collect(); Ok(embeddings) } // Read the pdf file pub async fn read_file(mut multipart: Multipart) -> Result<Vec<String>> { let mut uploaded_files = vec![]; while let Some(mut field) = multipart.next_field().await.map_err(|e| { std::io::Error::new( std::io::ErrorKind::Other, format!("error status:: {} and text {}", e.status(), e.body_text()), ) })? { if let Some(file_name) = field.file_name().map(|name| name.to_string()) { if !is_pdf(file_name.as_str()) { return Err(anyhow!("Only Pdf files are allowed")); } let mut data = Vec::new(); while let Some(chunk) = field.chunk().await? { data.extend_from_slice(&chunk); } // Save to server let file_path = format!("./uploads/{}", file_name); save_file(&file_path, &data).context("error occurred while saving the file")?; uploaded_files.push(file_name); } } if uploaded_files.is_empty() { return Err(anyhow!("No valid PDF files were uploaded.")); } Ok(uploaded_files) } // Validate PDF File Extension fn is_pdf(file_name: &str) -> bool { std::path::Path::new(file_name) .extension() .and_then(|ext| ext.to_str()) .map(|ext| ext.eq_ignore_ascii_case("pdf")) .unwrap_or(false) } // Save File to Server fn save_file(file_path: &str, data: &[u8]) -> Result<()> { fs::create_dir_all("./uploads")?; let mut file = fs::File::create(file_path)?; file.write_all(data).context("write operation failed")?; Ok(()) }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/server/src/vector_db.rs
server/src/vector_db.rs
use std::collections::HashMap; use anyhow::{anyhow, Context, Ok, Result}; use qdrant_client::{ qdrant::{ CreateCollectionBuilder, Distance, PointId, PointStruct, SearchPoints, UpsertPointsBuilder, Value, VectorParamsBuilder, Vectors, }, Qdrant, }; use tracing::info; pub struct VectorStore { client: Qdrant, } // initialize the db client fn db_init(url: &str) -> Qdrant { let qdrant_client = match Qdrant::from_url(url).build() { std::result::Result::Ok(client) => client, Err(err) => panic!("unable to connect to DB! {}", err.to_string()), }; return qdrant_client; } // impl the vector store impl VectorStore { pub fn new(db_url: &str) -> Self { let db_client = db_init(db_url); Self { client: db_client } } // create_collection to be a private method. Collection to be created based on doc name async fn create_collection(&self, collection_name: &str) -> Result<()> { let collection_exists = self .client .collection_exists(collection_name) .await .context("collection_exists operation failed!")?; if !collection_exists { let new_collection = self .client .create_collection( CreateCollectionBuilder::new(collection_name) .vectors_config(VectorParamsBuilder::new(768, Distance::Cosine)), ) .await .context("create new collection failed")?; if new_collection.result { return Ok(()); } else { return Err(anyhow!("unable to create the new collection")); } } Err(anyhow!("collection already exists")) } // saves the vector embeddings to database pub async fn store_embeddings( &self, collection_name: &str, embeddings: Vec<(String, Vec<f32>, String)>, ) -> Result<()> { self.create_collection(collection_name).await?; let points: Vec<PointStruct> = embeddings .into_iter() .map(|(id, vec, content)| PointStruct { id: Some(PointId::from(id)), vectors: Some(Vectors::from(vec)), payload: HashMap::from([("text".to_string(), Value::from(content))]), }) .collect(); self.client .upsert_points(UpsertPointsBuilder::new(collection_name, points).wait(true)) .await .context("upsert_points operation failed")?; info!("embeddings saved successfully!"); Ok(()) } // search for the similar points along with payload // payload to be sent to LLM as context. pub async fn search_result( &self, collection_name: &str, query: Vec<f32>, ) -> Result<Vec<String>> { let search_result = self .client .search_points(SearchPoints { collection_name: collection_name.to_string(), vector: query, limit: 6, with_payload: Some(true.into()), ..Default::default() }) .await .context("unable to fetch the results")?; let payloads: Vec<String> = search_result .result .iter() .filter_map(|p| { p.payload .get("text") .and_then(|v| v.as_str().map(|s| s.to_string())) }) .collect(); Ok(payloads) } //list out the collection names pub async fn list_collections(&self) -> Result<Vec<String>> { let collections = self .client .list_collections() .await .context("list_collections operation failed")?; let collection_names: Vec<String> = collections .collections .into_iter() .map(|coll| coll.name) .collect(); Ok(collection_names) } }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/server/src/main.rs
server/src/main.rs
mod handlers; mod processor; mod utils; mod vector_db; use std::sync::Arc; use axum::{ middleware, routing::{get, post}, Router, }; use handlers::{doc_names, file_handler, prompt_handler, upload_file}; use processor::Processor; use tracing::info; use tracing_subscriber; use utils::{get_settings, log_request, ConfigVar}; use vector_db::VectorStore; #[derive(Clone)] struct AppState { processor: Arc<Processor>, } #[tokio::main] async fn main() { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .init(); // fetch the env configured variables let settings: ConfigVar = get_settings(); let db_url = settings .db_url .as_ref() .expect("db url connection string is required"); // shared app state for handlers let state = AppState { processor: Arc::new(Processor::new(settings.clone(), VectorStore::new(&db_url))), }; // the routes configuration let app = Router::new() .route("/", get(doc_names)) .route("/file/{fileName}", get(file_handler)) .route("/upload", post(upload_file)) .layer(axum::extract::DefaultBodyLimit::max(500 * 1024 * 1024)) .route("/prompt", post(prompt_handler)) .layer(middleware::from_fn(log_request)) .with_state(state.clone()); // start the app server let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); info!("Starting server at port: 3000"); axum::serve(listener, app).await.unwrap(); }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/client/src-tauri/build.rs
client/src-tauri/build.rs
fn main() { tauri_build::build() }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/client/src-tauri/src/lib.rs
client/src-tauri/src/lib.rs
use base64::decode; use regex::Regex; use reqwest::multipart::{Form, Part}; use serde::{Deserialize, Serialize}; use reqwest; use serde_json::json; // Structs for API responses and requests #[derive(Clone, Debug, Deserialize, Serialize)] struct ListItem { name: String, } fn get_backend_url() -> String { let backend_url = std::env::var("BACKEND_URL") .expect("BACKEND_URL not found"); backend_url } // HTTP API call to fetch list items #[tauri::command] async fn fetch_list_items() -> Result<Vec<ListItem>, String> { let backend_url = get_backend_url(); match reqwest::Client::new() .get(backend_url) .send() .await { Ok(response) => { response.json::<Vec<ListItem>>() .await .map_err(|e| e.to_string()) }, Err(e) => Err(e.to_string()) } } fn style_text(text: &str) -> Vec<String> { let mut styled_parts = Vec::new(); let paragraphs = text.split("\n\n"); let important_words = Regex::new(r"\b(important|error|warning|success|note)\b").unwrap(); for para in paragraphs { if para.len() > 100 { let highlighted_text = important_words.replace_all(para, "<span class='highlight'>$0</span>"); styled_parts.push(format!("<p>{}</p>", highlighted_text)); } } styled_parts } #[tauri::command] async fn fetch_content(item: ListItem) -> Result<String, String> { let backend_url = get_backend_url(); match reqwest::Client::new() .get(&format!("{}/file/{}.pdf", backend_url, item.name)) .send() .await { Ok(response) => { let content = response.text().await.unwrap(); let result_content = style_text(content.as_str()); Ok(result_content.join("<br/>")) }, Err(e) => Err(e.to_string()) } } #[tauri::command] async fn process_prompt(item: ListItem, query: String) -> Result<String, String> { let backend_url = get_backend_url(); let payload = json!({ "user_query": query, "doc_name": format!("{}.pdf",item.name) }); match reqwest::Client::new() .post(&format!("{}/prompt", backend_url)) .json(&payload) .send().await { Ok(response) => { let llm_response = response.text().await.unwrap_or_else(|e| { format!("unable to get the llm response:: {:?}", e.to_string()) }); Ok(llm_response) } Err(e) => Err(e.to_string()) } } #[tauri::command] async fn upload_file(name: String, ct: String) -> Result<String, String> { let backend_url = get_backend_url(); let decoded_data = decode(&ct).map_err(|e| format!("Base64 Decode Error: {}", e))?; let file_part = Part::bytes(decoded_data) .file_name(name.clone()) .mime_str("application/octet-stream") .map_err(|e| format!("File Part Error: {}", e))?; let form = Form::new() .part("file", file_part); let client = reqwest::Client::new(); match client.post(&format!("{}/upload", backend_url)) .multipart(form) .send() .await { Ok(response) => { if response.status().is_success() { Ok("File uploaded successfully!".to_string()) } else { Err(format!("Upload failed with status: {}", response.status())) } }, Err(e) => Err(format!("Request failed: {}", e)), } } #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .invoke_handler(tauri::generate_handler![fetch_list_items, fetch_content, process_prompt, upload_file]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Harry-027/DocuMind
https://github.com/Harry-027/DocuMind/blob/581cb154e57dbc439bcbd3c7f13b5bcff00be228/client/src-tauri/src/main.rs
client/src-tauri/src/main.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use std::env; use dotenv::dotenv; fn main() { dotenv().ok(); env::var("BACKEND_URL").expect("BACKEND_URL not found"); documind_lib::run() }
rust
MIT
581cb154e57dbc439bcbd3c7f13b5bcff00be228
2026-01-04T20:23:43.479737Z
false
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/build.rs
build.rs
fn main() { static_vcruntime::metabuild(); }
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
false
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/dinvoke/src/lib.rs
dinvoke/src/lib.rs
#[macro_use] extern crate litcrypt; use_litcrypt!(); use std::cell::UnsafeCell; use std::mem::size_of; use std::panic; use std::{collections::HashMap, ptr}; use std::ffi::CString; use bindings::Windows::Win32::System::Diagnostics::Debug::{GetThreadContext,SetThreadContext}; use bindings::Windows::Win32::System::Kernel::UNICODE_STRING; use bindings::Windows::Win32::System::Threading::PROCESS_BASIC_INFORMATION; use bindings::Windows::Win32::System::WindowsProgramming::{OBJECT_ATTRIBUTES, IO_STATUS_BLOCK}; use bindings::Windows::Win32::{Foundation::{HANDLE, HINSTANCE}, System::Threading::{GetCurrentProcess,GetCurrentThread}}; use data::{ApiSetNamespace, ApiSetNamespaceEntry, ApiSetValueEntry, DLL_PROCESS_ATTACH, EAT, EntryPoint, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, PVOID, PeMetadata, CONTEXT, NtAllocateVirtualMemoryArgs, EXCEPTION_POINTERS, NtOpenProcessArgs, CLIENT_ID, PROCESS_QUERY_LIMITED_INFORMATION, NtProtectVirtualMemoryArgs, PAGE_READONLY, NtWriteVirtualMemoryArgs, ExceptionHandleFunction, PS_ATTRIBUTE_LIST, NtCreateThreadExArgs, LptopLevelExceptionFilter}; use libc::c_void; use litcrypt::lc; use winproc::Process; use winapi::shared::ntdef::LARGE_INTEGER; use rand::Rng; static mut HARDWARE_BREAKPOINTS: bool = false; static mut HARDWARE_EXCEPTION_FUNCTION: ExceptionHandleFunction = ExceptionHandleFunction::NtOpenProcess; static mut NT_ALLOCATE_VIRTUAL_MEMORY_ARGS: NtAllocateVirtualMemoryArgs = NtAllocateVirtualMemoryArgs{handle: HANDLE {0: -1}, base_address: ptr::null_mut()}; static mut NT_OPEN_PROCESS_ARGS: NtOpenProcessArgs = NtOpenProcessArgs{handle: ptr::null_mut(), access:0, attributes: ptr::null_mut(), client_id: ptr::null_mut()}; static mut NT_PROTECT_VIRTUAL_MEMORY_ARGS: NtProtectVirtualMemoryArgs = NtProtectVirtualMemoryArgs{handle: HANDLE {0: -1}, base_address: ptr::null_mut(), size: ptr::null_mut(), protection: 0}; static mut NT_WRITE_VIRTUAL_MEMORY_ARGS: NtWriteVirtualMemoryArgs = NtWriteVirtualMemoryArgs{handle: HANDLE {0: -1}, base_address: ptr::null_mut(), buffer: ptr::null_mut(), size: 0usize}; static mut NT_CREATE_THREAD_EX_ARGS: NtCreateThreadExArgs = NtCreateThreadExArgs{thread:ptr::null_mut(), access: 0, attributes: ptr::null_mut(), process: HANDLE {0: -1}}; /// Enables or disables the use of exception handlers in /// combination with hardware breakpoints. pub fn use_hardware_breakpoints(value: bool) { unsafe { HARDWARE_BREAKPOINTS = value; } } /// It sets a hardware breakpoint on a certain memory address. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// let nt_open_process = dinvoke::get_function_address(ntdll, "NtOpenProcess"); /// let instruction_addr = dinvoke::find_syscall_address(nt_open_process); /// dinvoke::set_hardware_breakpoint(instruction_addr); /// ``` pub fn set_hardware_breakpoint(address: usize) { unsafe { let mut context = CONTEXT::default(); context.ContextFlags = 0x100000 | 0x10; // CONTEXT_DEBUG_REGISTERS let mut lp_context: *mut bindings::Windows::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::transmute(&context); GetThreadContext(GetCurrentThread(), lp_context); let context: *mut CONTEXT = std::mem::transmute(lp_context); (*context).Dr0 = address as u64; (*context).Dr6 = 0; (*context).Dr7 = ((*context).Dr7 & !(((1 << 2) - 1) << 16)) | (0 << 16); (*context).Dr7 = ((*context).Dr7 & !(((1 << 2) - 1) << 18)) | (0 << 18); (*context).Dr7 = ((*context).Dr7 & !(((1 << 1) - 1) << 0)) | (1 << 0); (*context).ContextFlags = 0x100000 | 0x10; lp_context = std::mem::transmute(context); SetThreadContext(GetCurrentThread(), lp_context ); } } /// Retrieves the memory address of a syscall instruction. /// /// It expects the memory address of the function as a parameter, and /// it will iterate over each following byte until it finds the value 0x0F05. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// let nt_open_process = dinvoke::get_function_address(ntdll, "NtOpenProcess"); /// let syscall_addr = dinvoke::find_syscall_address(nt_open_process); /// ``` pub fn find_syscall_address(address: usize) -> usize { unsafe { let stub: [u8;2] = [ 0x0F, 0x05 ]; let mut ptr:*mut u8 = address as *mut u8; for _i in 0..23 { if *(ptr.add(1)) == stub[0] && *(ptr.add(2)) == stub[1] { return ptr.add(1) as usize; } ptr = ptr.add(1); } } 0usize } /// This function acts as an Exception Handler, and should be combined with a hardware breakpoint. /// /// Whenever the HB gets triggered, this function will be executed. This is meant to be used in order /// to spoof syscalls parameters. pub unsafe extern "system" fn breakpoint_handler (exceptioninfo: *mut EXCEPTION_POINTERS) -> i32 { if (*(*(exceptioninfo)).exception_record).ExceptionCode.0 == 0x80000004 // STATUS_SINGLE_STEP { if ((*(*exceptioninfo).context_record).Dr7 & 1) == 1 { if (*(*exceptioninfo).context_record).Rip == (*(*exceptioninfo).context_record).Dr0 { (*(*exceptioninfo).context_record).Dr0 = 0; // Remove the breakpoint match HARDWARE_EXCEPTION_FUNCTION { ExceptionHandleFunction::NtAllocateVirtualMemory => { (*(*exceptioninfo).context_record).R10 = NT_ALLOCATE_VIRTUAL_MEMORY_ARGS.handle.0 as u64; (*(*exceptioninfo).context_record).Rdx = std::mem::transmute(NT_ALLOCATE_VIRTUAL_MEMORY_ARGS.base_address); }, ExceptionHandleFunction::NtProtectVirtualMemory => { (*(*exceptioninfo).context_record).R10 = NT_PROTECT_VIRTUAL_MEMORY_ARGS.handle.0 as u64; (*(*exceptioninfo).context_record).Rdx = std::mem::transmute(NT_PROTECT_VIRTUAL_MEMORY_ARGS.base_address); (*(*exceptioninfo).context_record).R8 = std::mem::transmute(NT_PROTECT_VIRTUAL_MEMORY_ARGS.size); (*(*exceptioninfo).context_record).R9 = NT_PROTECT_VIRTUAL_MEMORY_ARGS.protection as u64; }, ExceptionHandleFunction::NtOpenProcess => { (*(*exceptioninfo).context_record).R10 = std::mem::transmute(NT_OPEN_PROCESS_ARGS.handle); (*(*exceptioninfo).context_record).Rdx = NT_OPEN_PROCESS_ARGS.access as u64; (*(*exceptioninfo).context_record).R8 = std::mem::transmute(NT_OPEN_PROCESS_ARGS.attributes); (*(*exceptioninfo).context_record).R9 = std::mem::transmute(NT_OPEN_PROCESS_ARGS.client_id); }, ExceptionHandleFunction::NtWriteVirtualMemory => { (*(*exceptioninfo).context_record).R10 = NT_WRITE_VIRTUAL_MEMORY_ARGS.handle.0 as u64; (*(*exceptioninfo).context_record).Rdx = std::mem::transmute(NT_WRITE_VIRTUAL_MEMORY_ARGS.base_address); (*(*exceptioninfo).context_record).R8 = std::mem::transmute(NT_WRITE_VIRTUAL_MEMORY_ARGS.buffer); (*(*exceptioninfo).context_record).R9 = NT_WRITE_VIRTUAL_MEMORY_ARGS.size as u64; }, ExceptionHandleFunction::NtCreateThreadEx => { (*(*exceptioninfo).context_record).R10 = std::mem::transmute(NT_CREATE_THREAD_EX_ARGS.thread); (*(*exceptioninfo).context_record).Rdx = NT_CREATE_THREAD_EX_ARGS.access as u64; (*(*exceptioninfo).context_record).R8 = std::mem::transmute(NT_CREATE_THREAD_EX_ARGS.attributes); (*(*exceptioninfo).context_record).R9 = NT_CREATE_THREAD_EX_ARGS.process.0 as u64; } } } } return -1; // EXCEPTION_CONTINUE_EXECUTION } 0 // EXCEPTION_CONTINUE_SEARCH } /// Retrieves the base address of a module loaded in the current process. /// /// In case that the module can't be found in the current process, it will /// return 0. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// println!("The base address of ntdll.dll is 0x{:X}.", ntdll); /// } /// ``` pub fn get_module_base_address (module_name: &str) -> isize { let process = Process::current(); let modules = process.module_list().unwrap(); for m in modules { if m.name().unwrap().to_lowercase() == module_name.to_ascii_lowercase() { let handle = m.handle(); return handle as isize; } } 0 } /// Retrieves the address of an exported function from the specified module. /// /// This functions is analogous to GetProcAddress from Win32. The exported /// function's address is obtained by walking and parsing the EAT of the /// specified module. /// /// In case that the function's address can't be retrieved, it will return 0. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let addr = dinvoke::get_function_address(ntdll, "NtCreateThread"); /// println!("The address where NtCreateThread is located at is 0x{:X}.", addr); /// } /// ``` pub fn get_function_address(module_base_address: isize, function: &str) -> isize { unsafe { let mut function_ptr:*mut i32 = ptr::null_mut(); let pe_header = *((module_base_address + 0x3C) as *mut i32); let opt_header: isize = module_base_address + (pe_header as isize) + 0x18; let magic = *(opt_header as *mut i16); let p_export: isize; if magic == 0x010b { p_export = opt_header + 0x60; } else { p_export = opt_header + 0x70; } let export_rva = *(p_export as *mut i32); let ordinal_base = *((module_base_address + export_rva as isize + 0x10) as *mut i32); let number_of_names = *((module_base_address + export_rva as isize + 0x18) as *mut i32); let functions_rva = *((module_base_address + export_rva as isize + 0x1C) as *mut i32); let names_rva = *((module_base_address + export_rva as isize + 0x20) as *mut i32); let ordinals_rva = *((module_base_address + export_rva as isize + 0x24) as *mut i32); for x in 0..number_of_names { let address = *((module_base_address + names_rva as isize + x as isize * 4) as *mut i32); let mut function_name_ptr = (module_base_address + address as isize) as *mut u8; let mut function_name: String = "".to_string(); while *function_name_ptr as char != '\0' // null byte { function_name.push(*function_name_ptr as char); function_name_ptr = function_name_ptr.add(1); } if function_name.to_lowercase() == function.to_lowercase() { let function_ordinal = *((module_base_address + ordinals_rva as isize + x as isize * 2) as *mut i16) as i32 + ordinal_base; let function_rva = *(((module_base_address + functions_rva as isize + (4 * (function_ordinal - ordinal_base)) as isize )) as *mut i32); function_ptr = (module_base_address + function_rva as isize) as *mut i32; function_ptr = get_forward_address(function_ptr as *mut u8) as *mut i32; break; } } let mut ret: isize = 0; if function_ptr != ptr::null_mut() { ret = function_ptr as isize; } ret } } fn get_forward_address(function_ptr: *mut u8) -> isize { unsafe { let mut c = 100; let mut ptr = function_ptr.clone(); let mut forwarded_names = "".to_string(); loop { if *ptr as char != '\0' { forwarded_names.push(*ptr as char); } else { break; } ptr = ptr.add(1); c = c - 1; // Assume there wont be an exported address with len > 100 if c == 0 { return function_ptr as isize; } } let values: Vec<&str> = forwarded_names.split(".").collect(); if values.len() != 2 { return function_ptr as isize; } let mut forwarded_module_name = values[0].to_string(); let forwarded_export_name = values[1].to_string(); let api_set = get_api_mapping(); let prev_hook = panic::take_hook(); panic::set_hook(Box::new(|_| {})); let result = panic::catch_unwind(|| { format!("{}{}",&forwarded_module_name[..forwarded_module_name.len() - 2], ".dll"); }); panic::set_hook(prev_hook); if result.is_err() { return function_ptr as isize; } let lookup_key = format!("{}{}",&forwarded_module_name[..forwarded_module_name.len() - 2], ".dll"); if api_set.contains_key(&lookup_key) { forwarded_module_name = match api_set.get(&lookup_key) { Some(x) => x.to_string(), None => {forwarded_module_name} }; } else { forwarded_module_name = forwarded_module_name + ".dll"; } let mut module = get_module_base_address(&forwarded_module_name); // If the module is not already loaded, we try to load it dynamically calling LoadLibraryA if module == 0 { module = load_library_a(&forwarded_module_name); } if module != 0 { return get_function_address(module, &forwarded_export_name); } function_ptr as isize } } pub fn get_api_mapping() -> HashMap<String,String> { unsafe { let handle = GetCurrentProcess(); let process_information: *mut c_void = std::mem::transmute(&PROCESS_BASIC_INFORMATION::default()); let _ret = nt_query_information_process( handle, 0, process_information, size_of::<PROCESS_BASIC_INFORMATION>() as u32, ptr::null_mut()); let _r = close_handle(handle); let process_information_ptr: *mut PROCESS_BASIC_INFORMATION = std::mem::transmute(process_information); let api_set_map_offset:usize; if size_of::<usize>() == 4 { api_set_map_offset = 0x38; } else { api_set_map_offset = 0x68; } let mut api_set_dict: HashMap<String,String> = HashMap::new(); let api_set_namespace_ptr = *(((*process_information_ptr).PebBaseAddress as usize + api_set_map_offset) as *mut isize); let api_set_namespace_ptr: *mut ApiSetNamespace = std::mem::transmute(api_set_namespace_ptr); let namespace = *api_set_namespace_ptr; for i in 0..namespace.count { let set_entry_ptr = (api_set_namespace_ptr as usize + namespace.entry_offset as usize + (i * size_of::<ApiSetNamespaceEntry>() as i32) as usize) as *mut ApiSetNamespaceEntry; let set_entry = *set_entry_ptr; let mut api_set_entry_name_ptr = (api_set_namespace_ptr as usize + set_entry.name_offset as usize) as *mut u8; let mut api_set_entry_name: String = "".to_string(); let mut j = 0; while j < (set_entry.name_length / 2 ) { let c = *api_set_entry_name_ptr as char; if c != '\0' // Esto se podria meter en una funcion aparte { api_set_entry_name.push(c); j = j + 1; } api_set_entry_name_ptr = api_set_entry_name_ptr.add(1); } let api_set_entry_key = format!("{}{}",&api_set_entry_name[..api_set_entry_name.len()-2], ".dll"); let mut set_value_ptr: *mut ApiSetValueEntry = ptr::null_mut(); if set_entry.value_length == 1 { let value = (api_set_namespace_ptr as usize + set_entry.value_offset as usize) as *mut u8; set_value_ptr = std::mem::transmute(value); } else if set_entry.value_length > 1 { for x in 0..set_entry.value_length { let host_ptr = (api_set_entry_name_ptr as usize + set_entry.value_offset as usize + size_of::<ApiSetValueEntry>() as usize * x as usize) as *mut u8; let mut c: u8 = u8::default(); let mut host: String = "".to_string(); while c as char != '\0' { c = *host_ptr; if c as char != '\0' { host.push(c as char); } } if host != api_set_entry_name { set_value_ptr = (api_set_namespace_ptr as usize + set_entry.value_offset as usize + size_of::<ApiSetValueEntry>() as usize * x as usize) as *mut ApiSetValueEntry; } } if set_value_ptr == ptr::null_mut() { set_value_ptr = (api_set_namespace_ptr as usize + set_entry.value_offset as usize) as *mut ApiSetValueEntry; } } let set_value = *set_value_ptr; let mut api_set_value: String = "".to_string(); if set_value.value_count != 0 { let mut value_ptr = (api_set_namespace_ptr as usize + set_value.value_offset as usize) as *mut u8; let mut r = 0; while r < (set_value.value_count / 2 ) { let c = *value_ptr as char; if c != '\0' { api_set_value.push(c); r = r + 1; } value_ptr = value_ptr.add(1); } } api_set_dict.insert(api_set_entry_key, api_set_value); } api_set_dict } } /// Returns a BTreeMap<isize,String> composed of pairs (memory address, function name) /// with all the Nt exported functions on ntdll.dll. /// /// This functions will only return valid data if the parameter passed is the base address of /// ntdll.dll. This function is usefull to dynamically get a syscall id as it is shown in the /// example. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let eat = dinvoke::get_ntdll_eat(ntdll); /// let mut j = 0; /// for (a,b) in eat.iter() /// { /// if b == "NtCreateThreadEx" /// { /// println!("The syscall id for NtCreateThreadEx is {}.",j); /// break; /// } /// j = j + 1; /// } /// } /// ``` pub fn get_ntdll_eat(module_base_address: isize) -> EAT { unsafe { let mut eat:EAT = EAT::default(); let mut function_ptr:*mut i32; let pe_header = *((module_base_address + 0x3C) as *mut i32); let opt_header: isize = module_base_address + (pe_header as isize) + 0x18; let magic = *(opt_header as *mut i16); let p_export: isize; if magic == 0x010b { p_export = opt_header + 0x60; } else { p_export = opt_header + 0x70; } let export_rva = *(p_export as *mut i32); let ordinal_base = *((module_base_address + export_rva as isize + 0x10) as *mut i32); let number_of_names = *((module_base_address + export_rva as isize + 0x18) as *mut i32); let functions_rva = *((module_base_address + export_rva as isize + 0x1C) as *mut i32); let names_rva = *((module_base_address + export_rva as isize + 0x20) as *mut i32); let ordinals_rva = *((module_base_address + export_rva as isize + 0x24) as *mut i32); for x in 0..number_of_names { let address = *((module_base_address + names_rva as isize + x as isize * 4) as *mut i32); let mut function_name_ptr = (module_base_address + address as isize) as *mut u8; let mut function_name: String = "".to_string(); while *function_name_ptr as char != '\0' // null byte { function_name.push(*function_name_ptr as char); function_name_ptr = function_name_ptr.add(1); } if function_name.starts_with("Zw") { let function_ordinal = *((module_base_address + ordinals_rva as isize + x as isize * 2) as *mut i16) as i32 + ordinal_base; let function_rva = *(((module_base_address + functions_rva as isize + (4 * (function_ordinal - ordinal_base)) as isize )) as *mut i32); function_ptr = (module_base_address + function_rva as isize) as *mut i32; function_name = function_name.replace("Zw", "Nt"); eat.insert(function_ptr as isize,function_name ); } } eat } } /// Returns the syscall id that correspond to the function specified. /// /// This functions will return -1 in case that the syscall id of the specified function /// could not be retrieved. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let eat = dinvoke::get_ntdll_eat(ntdll); /// let id = dinvoke::get_syscall_id(eat, "NtCreateThreadEx"); /// /// if id != -1 /// { /// println!("The syscall id for NtCreateThreadEx is {}.",id); /// } /// } /// ``` pub fn get_syscall_id(eat: &EAT, function_name: &str) -> i32 { let mut i = 0; for (_a,b) in eat.iter() { if b == function_name { return i; } i = i + 1; } -1 } /// Given a valid syscall id, it will allocate the required shellcode to execute /// that specific syscall. /// /// This functions will return the memory address where the shellcode has been written. If any /// error has ocurred, it will return 0. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let eat = dinvoke::get_ntdll_eat(ntdll); /// let id = dinvoke::get_syscall_id(eat, "NtCreateThreadEx"); /// /// if id != -1 /// { /// let addr = dinvoke::prepare_syscall(id as u32); /// println!("NtCreateThreadEx syscall ready to be executed at address 0x{:X}", addr); /// } /// } /// ``` pub fn prepare_syscall(id: u32, eat: EAT) -> isize { let mut sh: [u8;21] = [ 0x4C, 0x8B, 0xD1, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x49, 0xBB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xFF, 0xE3 ]; unsafe { let mut ptr: *mut u8 = std::mem::transmute(&id); for i in 0..4 { sh[4 + i] = *ptr; ptr = ptr.add(1); } let max_range = eat.len(); let mut rng = rand::thread_rng(); let mut function = &"".to_string(); for s in eat.values() { let index = rng.gen_range(0..max_range); if index < max_range / 10 { function = s; } } let ntdll = get_module_base_address(&lc!("ntdll.dll")); let mut function_addr = get_function_address(ntdll, function); if function_addr == 0 { function_addr = get_function_address_by_ordinal(ntdll, id); } let syscall_addr = find_syscall_address(function_addr as usize); let mut syscall_ptr: *mut u8 = std::mem::transmute(&syscall_addr); for j in 0..8 { sh[10 + j] = *syscall_ptr; syscall_ptr = syscall_ptr.add(1); } let handle = GetCurrentProcess(); let base_address: *mut PVOID = std::mem::transmute(&usize::default()); let nsize: usize = sh.len() as usize; let size: *mut usize = std::mem::transmute(&(nsize+1)); let old_protection: *mut u32 = std::mem::transmute(&u32::default()); let ret = nt_allocate_virtual_memory(handle, base_address, 0, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if ret != 0 { return 0; } let buffer: *mut c_void = std::mem::transmute(sh.as_ptr()); let bytes_written: *mut usize = std::mem::transmute(&usize::default()); let ret = nt_write_virtual_memory(handle, *base_address, buffer, nsize, bytes_written); if ret != 0 { return 0; } let ret = nt_protect_virtual_memory(handle, base_address, size, PAGE_EXECUTE_READ, old_protection); let _r = close_handle(handle); if ret != 0 { return 0; } *base_address as isize } } /// Calls the module's entry point with the option DLL_ATTACH_PROCESS. /// /// # Examples /// /// ```ignore /// let pe = manualmap::read_and_map_module("c:\\some\\random\\file.dll").unwrap(); /// let ret = dinvoke::call_module_entry_point(pe.0, pe.1); /// /// match ret /// { /// Ok(()) => println!("Module entry point successfully executed."), /// Err(e) => println!("Error ocurred: {}", e) /// } /// ``` pub fn call_module_entry_point(pe_info: PeMetadata, module_base_address: isize) -> Result<(), String> { let entry_point; if pe_info.is_32_bit { entry_point = module_base_address + pe_info.opt_header_32.AddressOfEntryPoint as isize; } else { entry_point = module_base_address + pe_info.opt_header_64.address_of_entry_point as isize; } unsafe { let main: EntryPoint = std::mem::transmute(entry_point); let module = HINSTANCE {0: entry_point as isize}; let ret = main(module, DLL_PROCESS_ATTACH, ptr::null_mut()); if !ret.as_bool() { return Err(lc!("[x] Failed to call module's entry point (DllMain -> DLL_PROCESS_ATTACH).")); } Ok(()) } } /// Retrieves the address of an exported function from the specified module by its ordinal. /// /// In case that the function's address can't be retrieved, it will return 0. /// /// This functions internally calls LdrGetProcedureAddress. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let ordinal: u32 = 8; /// let addr = dinvoke::get_function_address_ordinal(ntdll, ordinal); /// if addr != 0 /// { /// println!("The function with ordinal 8 is located at 0x{:X}.", addr); /// } /// } /// ``` pub fn get_function_address_by_ordinal(module_base_address: isize, ordinal: u32) -> isize { let ret = ldr_get_procedure_address(module_base_address, "", ordinal); ret } /// Retrieves the address of an exported function from the specified module either by its name /// or by its ordinal number. /// /// This functions internally calls LdrGetProcedureAddress. /// /// In case that the function's address can't be retrieved, it will return 0. /// /// # Examples /// /// ``` /// let ntdll = dinvoke::get_module_base_address("ntdll.dll"); /// /// if ntdll != 0 /// { /// let ordinal: u32 = 8; // Ordinal 8 represents the function RtlDispatchAPC /// let addr = dinvoke::ldr_get_procedure_address(ntdll,"", 8); /// if addr != 0 /// { /// println!("The function with ordinal 8 is located at 0x{:X}.", addr); /// } /// } /// ``` pub fn ldr_get_procedure_address (module_handle: isize, function_name: &str, ordinal: u32) -> isize { unsafe { let ret: Option<i32>; let func_ptr: data::LdrGetProcedureAddress; let hmodule: PVOID = std::mem::transmute(module_handle); let r = usize::default(); let return_address: *mut c_void = std::mem::transmute(&r); let return_address: *mut PVOID = std::mem::transmute(return_address); let f: UnsafeCell<String> = String::default().into(); let mut fun_name: *mut String = std::mem::transmute(f.get()); if function_name == "" { fun_name = ptr::null_mut(); } else { *fun_name = function_name.to_string(); } let module_base_address = get_module_base_address(&lc!("ntdll.dll")); dynamic_invoke!(module_base_address,&lc!("LdrGetProcedureAddress"),func_ptr,ret,hmodule,fun_name,ordinal,return_address); match ret { Some(x) => { if x == 0 { return *return_address as isize; } else { return 0; } }, None => return 0, } } } /// Dynamically calls SetUnhandledExceptionFilter. pub fn set_unhandled_exception_filter(address: usize) -> LptopLevelExceptionFilter { unsafe { let ret: Option<LptopLevelExceptionFilter>; let func_ptr: data::SetUnhandledExceptionFilter; let module_base_address = get_module_base_address(&lc!("kernel32.dll")); dynamic_invoke!(module_base_address,&lc!("SetUnhandledExceptionFilter"),func_ptr,ret,address); match ret { Some(x) => return x, None => return 0, } } } /// Loads and retrieves a module's base address by dynamically calling LoadLibraryA. /// /// It will return either the module's base address or 0. /// /// # Examples /// /// ``` /// let ret = dinvoke::load_library_a("ntdll.dll"); /// /// if ret != 0 {println!("ntdll.dll base address is 0x{:X}.", addr); /// ``` pub fn load_library_a(module: &str) -> isize { unsafe { let ret: Option<i32>; let func_ptr: data::RtlQueueWorkItem; let name = CString::new(module.to_string()).expect(""); let module_name: PVOID = std::mem::transmute(name.as_ptr()); let k32 = get_module_base_address(&lc!("kernel32.dll")); let ntdll = get_module_base_address(&lc!("ntdll.dll")); let load_library = get_function_address(k32, &lc!("LoadLibraryA")) as usize; dynamic_invoke!(ntdll,&lc!("RtlQueueWorkItem"),func_ptr,ret,load_library,module_name,0); match ret { Some(x) => { if x != 0 { return 0; } else { use std::{thread, time}; let ten_millis = time::Duration::from_millis(500); thread::sleep(ten_millis); return get_module_base_address(module); } }, None => { return 0; } } } } /// Opens a HANDLE to a process. /// /// If the function fails, it will return a null HANDLE. /// /// # Examples /// /// ``` /// let pid = 792u32; /// let handle = dinvoke::open_process(0x0040, 0, pid); //PROCESS_DUP_HANDLE access right. /// /// if handle.0 != 0 /// { /// println!("Handle to process with id {} with PROCESS_DUP_HANDLE access right successfully obtained.", pid); /// } /// ``` pub fn open_process(desired_access: u32, inherit_handle: i32, process_id: u32) -> HANDLE { unsafe { let ret: Option<HANDLE>; let func_ptr: data::OpenProcess; let module_base_address = get_module_base_address(&lc!("kernel32.dll")); dynamic_invoke!(module_base_address,&lc!("OpenProcess"),func_ptr,ret,desired_access,inherit_handle,process_id); match ret { Some(x) => return x, None => return HANDLE::default(), } } } /// Closes a HANDLE object. /// /// It will return either a boolean value or an Err with a descriptive error message. If the function /// fails the bool value returned will be false. /// /// # Examples /// /// ``` /// let pid = 792u32;
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
true
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/src/main.rs
src/main.rs
#[macro_use] extern crate litcrypt; use_litcrypt!(); use std::mem::size_of; use std::{ptr, env}; use std::{collections::BTreeSet, iter::FromIterator}; use winproc::Process; use bindings::Windows::Win32::System::WindowsProgramming::IO_STATUS_BLOCK; use bindings::Windows::Win32::Foundation::HANDLE; use data::{PVOID, FILE_PROCESS_IDS_USING_FILE_INFORMATION}; use getopts::Options; fn main() { unsafe { let mut reverse = false; let mut quiet = false; let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let mut opts = Options::new(); opts.optflag("h", "help", "Print this help menu."); opts.optopt("f", "file", "Binary path to look for.",""); opts.optflag("r", "reverse", "Get processes where the binary is loaded."); opts.optflag("l", "list", "Get current process' loaded modules."); opts.optflag("q", "quiet", "Reduces cross process activity by not resolving processes' names."); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(x) => {println!("{}",x);print!("{}",lc!("[x] Invalid arguments. Use -h for detailed help.")); return; } }; if matches.opt_present("h") { print_usage(&program, opts); return; } if matches.opt_present("l") { print_modules(); return; } if !matches.opt_present("f") { print_usage(&program, opts); return; } if matches.opt_present("r") { reverse = true; } if matches.opt_present("q") { quiet = true; } let image = matches.opt_str("f").unwrap(); let k32 = dinvoke::get_module_base_address(&lc!("kernelbase.dll")); let unwanted = get_pid_from_image_path(&image); let unwanted = unwanted.to_vec(); let unwanted:Vec<u32> = unwanted.into_iter().map(|x|x as u32).collect(); if reverse { print_processes(unwanted[1..].to_vec(), k32, quiet); return; } let func: data::EnumProcesses; let ret: Option<bool>; let pids: Vec<u32> = vec![0;500]; let mut pids: *mut u32 = pids.as_ptr() as *mut _; let needed = 0u32; let needed: *mut u32 = std::mem::transmute(&needed); dinvoke::dynamic_invoke!(k32,&lc!("EnumProcesses"),func,ret,pids,500*4,needed); match ret{ Some(_x) => {} None => {println!("{}",&lc!("[x] EnumProcesses failed!")); return;} } let mut all: Vec<u32> = vec![0;500]; for _i in 0..500 { all.push(*pids); pids = pids.add(1); } let final_pids = remove_pids(all,unwanted); print_processes(final_pids, k32, quiet); } } fn print_modules() { let process = Process::current(); let modules = process.module_list().unwrap(); for m in modules { println!("[-] {}", m.path().unwrap().display()); } } fn print_processes(final_pids: Vec<u32>, k32: isize, quiet: bool) { unsafe { for pid in final_pids { if pid == 0 { return; } if !quiet { // PROCESS_QUERY_LIMITED_INFORMATION is enough for Windows 10+ and Windows Server 2016+ // If you want to make this compatible with older OS versions, change the desired access mask // to PROCESS_QUERY_INFORMATION | PROCESS_VM_READ let phand = dinvoke::open_process(0x1000, 0, pid); if phand.0 != 0 && phand.0 != -1 { let path: Vec<u16> = vec![0; 260]; let path: *mut u16 = path .as_ptr() as *mut _; let func: data::GetModuleFileNameExW; let ret: Option<u32>; dinvoke::dynamic_invoke!(k32,&lc!("GetModuleFileNameExW"),func,ret,phand,0,path,260); if ret.unwrap() != 0 { let mut path: *mut u8 = path as *mut _; print!("[+] "); for _i in 0..ret.unwrap() { print!("{}",*path as char); path = path.add(2); } print!(" -- PID {}", pid); println!(); } } else { println!("[+] Process with PID {}", pid); } } else { println!("[+] Process with PID {}", pid); } } } } // From https://stackoverflow.com/questions/64019451/how-do-i-remove-the-elements-of-vector-that-occur-in-another-vector-in-rust fn remove_pids(mut items: Vec<u32>, to_remove: Vec<u32>) -> Vec<u32> { let to_remove = BTreeSet::from_iter(to_remove); items.retain(|e| !to_remove.contains(e)); items.to_vec() } pub fn get_pid_from_image_path(path: &str) -> [usize;500] { unsafe { let mut file: Vec<u16> = path.encode_utf16().collect(); file.push(0); let k32 = dinvoke::get_module_base_address("kernel32.dll"); let create_file: data::CreateFile; let create_file_r: Option<HANDLE>; // 0x80 = FILE_READ_ATTRIBUTES // 3 = OPEN_EXISTING // 0x00000001|0x00000002|0x00000004 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE dinvoke::dynamic_invoke!( k32, "CreateFileW", create_file, create_file_r, file.as_ptr() as *const u16, 0x80, 0x00000001|0x00000002|0x00000004, ptr::null(), 3, 0, HANDLE {0: 0} ); let file_handle = create_file_r.unwrap(); if file_handle.0 == -1 { println!("{}", &lc!("[x] The specified binary does not exist or can't be opened.")); return [0;500]; } let fpi: *mut FILE_PROCESS_IDS_USING_FILE_INFORMATION; let ios: Vec<u8> = vec![0u8; size_of::<IO_STATUS_BLOCK>()]; let iosb: *mut IO_STATUS_BLOCK = std::mem::transmute(&ios); let mut ptr: PVOID; let mut buffer; let mut bytes = size_of::<FILE_PROCESS_IDS_USING_FILE_INFORMATION>() as u32; let mut c = 0; loop { buffer = vec![0u8; bytes as usize]; ptr = std::mem::transmute(buffer.as_ptr()); // 47 = FileProcessIdsUsingFileInformation let x = dinvoke::nt_query_information_file(file_handle, iosb,ptr,bytes,47); if x != 0 { bytes *= 2; } else { fpi = std::mem::transmute(ptr); let _r = dinvoke::close_handle(file_handle); // Access denied error occurs if this pointer is not liberated. (*iosb).Anonymous.Pointer = ptr::null_mut(); return (*fpi).process_id_list; } c = c + 1; if c > 20 { println!("{}", "[x] Timeout. Call to NtQueryInformationFile failed."); break; } } let _r = dinvoke::close_handle(file_handle); [0;500] } } fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); }
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
false
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/bindings/build.rs
bindings/build.rs
fn main() { windows::build!( Windows::Win32::System::Diagnostics::Debug::{GetThreadContext,SetThreadContext,IMAGE_FILE_HEADER,IMAGE_OPTIONAL_HEADER32,IMAGE_SECTION_HEADER, IMAGE_DATA_DIRECTORY,IMAGE_OPTIONAL_HEADER_MAGIC,IMAGE_SUBSYSTEM,EXCEPTION_RECORD}, Windows::Win32::System::Memory::{VIRTUAL_ALLOCATION_TYPE,PAGE_PROTECTION_FLAGS}, Windows::Win32::Foundation::{HANDLE,HINSTANCE,PSTR,BOOL}, Windows::Win32::System::Threading::{GetCurrentProcess,GetCurrentThread,PROCESS_BASIC_INFORMATION,STARTUPINFOW,PROCESS_INFORMATION}, Windows::Win32::System::SystemServices::{IMAGE_BASE_RELOCATION,IMAGE_IMPORT_DESCRIPTOR,IMAGE_THUNK_DATA32,IMAGE_THUNK_DATA64,OVERLAPPED}, Windows::Win32::System::WindowsProgramming::{PUBLIC_OBJECT_TYPE_INFORMATION,OBJECT_ATTRIBUTES,IO_STATUS_BLOCK}, Windows::Win32::Security::SECURITY_ATTRIBUTES, Windows::Win32::System::Kernel::UNICODE_STRING, ); }
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
false
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/bindings/src/lib.rs
bindings/src/lib.rs
windows::include_bindings!();
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
false
Kudaes/Bin-Finder
https://github.com/Kudaes/Bin-Finder/blob/31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f/data/src/lib.rs
data/src/lib.rs
use std::{collections::BTreeMap, ffi::c_void}; use bindings::Windows::Win32::{Foundation::{BOOL, HANDLE, HINSTANCE, PSTR}, System::{Diagnostics::Debug::{IMAGE_DATA_DIRECTORY, IMAGE_OPTIONAL_HEADER32, IMAGE_SECTION_HEADER, EXCEPTION_RECORD}, Kernel::UNICODE_STRING, WindowsProgramming::{OBJECT_ATTRIBUTES, IO_STATUS_BLOCK}, Threading::{STARTUPINFOW, PROCESS_INFORMATION}}, Security::SECURITY_ATTRIBUTES}; use winapi::shared::ntdef::LARGE_INTEGER; pub type PVOID = *mut c_void; pub type DWORD = u32; pub type EAT = BTreeMap<isize,String>; pub type EntryPoint = extern "system" fn (HINSTANCE, u32, *mut c_void) -> BOOL; pub type EnumProcesses = unsafe extern "system" fn (*mut u32, u32, *mut u32) -> bool; pub type GetModuleFileNameExW = unsafe extern "system" fn (HANDLE, isize, *mut u16, u32) -> u32; pub type CreateFile = unsafe extern "system" fn (*const u16, u32, u32, *const SECURITY_ATTRIBUTES, u32, u32, HANDLE) -> HANDLE; pub type CreateProcessW = unsafe extern "system" fn (*const u16, *mut u16, *const SECURITY_ATTRIBUTES, *const SECURITY_ATTRIBUTES, BOOL, u32, *const c_void, *const u16, *const STARTUPINFOW, *mut PROCESS_INFORMATION) -> BOOL; pub type LoadLibraryA = unsafe extern "system" fn (PSTR) -> HINSTANCE; pub type OpenProcess = unsafe extern "system" fn (u32, i32, u32) -> HANDLE; pub type GetLastError = unsafe extern "system" fn () -> u32; pub type CloseHandle = unsafe extern "system" fn (HANDLE) -> i32; pub type VirtualFree = unsafe extern "system" fn (PVOID, usize, u32) -> bool; pub type LptopLevelExceptionFilter = usize; pub type SetUnhandledExceptionFilter = unsafe extern "system" fn (filter: LptopLevelExceptionFilter) -> LptopLevelExceptionFilter; pub type LdrGetProcedureAddress = unsafe extern "system" fn (PVOID, *mut String, u32, *mut PVOID) -> i32; pub type NtWriteVirtualMemory = unsafe extern "system" fn (HANDLE, PVOID, PVOID, usize, *mut usize) -> i32; pub type NtProtectVirtualMemory = unsafe extern "system" fn (HANDLE, *mut PVOID, *mut usize, u32, *mut u32) -> i32; pub type NtAllocateVirtualMemory = unsafe extern "system" fn (HANDLE, *mut PVOID, usize, *mut usize, u32, u32) -> i32; pub type NtQueryInformationProcess = unsafe extern "system" fn (HANDLE, u32, PVOID, u32, *mut u32) -> i32; pub type NtQuerySystemInformation = unsafe extern "system" fn (u32, PVOID, u32, *mut u32) -> i32; pub type NtQueryInformationFile = unsafe extern "system" fn (HANDLE, *mut IO_STATUS_BLOCK, PVOID, u32, u32) -> i32; pub type NtDuplicateObject = unsafe extern "system" fn (HANDLE, HANDLE, HANDLE, *mut HANDLE, u32, u32, u32) -> i32; pub type NtQueryObject = unsafe extern "system" fn (HANDLE, u32, PVOID, u32, *mut u32) -> i32; pub type NtOpenFile = unsafe extern "system" fn (*mut HANDLE, u32, *mut OBJECT_ATTRIBUTES, *mut IO_STATUS_BLOCK, u32, u32) -> i32; pub type NtCreateSection = unsafe extern "system" fn (*mut HANDLE, u32, *mut OBJECT_ATTRIBUTES, *mut LARGE_INTEGER, u32, u32, HANDLE) -> i32; pub type NtMapViewOfSection = unsafe extern "system" fn (HANDLE, HANDLE, *mut PVOID, usize, usize, *mut LARGE_INTEGER, *mut usize, u32, u32, u32) -> i32; pub type NtOpenProcess = unsafe extern "system" fn (*mut HANDLE, u32, *mut OBJECT_ATTRIBUTES, *mut CLIENT_ID) -> i32; pub type NtCreateThreadEx = unsafe extern "system" fn (*mut HANDLE, u32, *mut OBJECT_ATTRIBUTES, HANDLE, PVOID, PVOID, u32, usize, usize, usize, *mut PS_ATTRIBUTE_LIST) -> i32; pub type RtlAdjustPrivilege = unsafe extern "system" fn (u32, u8, u8, *mut u8) -> i32; pub type RtlInitUnicodeString = unsafe extern "system" fn (*mut UNICODE_STRING, *const u16) -> () ; pub type RtlZeroMemory = unsafe extern "system" fn (PVOID, usize) -> (); pub type RtlQueueWorkItem = unsafe extern "system" fn (usize, PVOID, u32) -> i32; pub const DLL_PROCESS_DETACH: u32 = 0; pub const DLL_PROCESS_ATTACH: u32 = 1; pub const DLL_THREAD_ATTACH: u32 = 2; pub const DLL_THREAD_DETACH: u32 = 3; pub const PAGE_READONLY: u32 = 0x2; pub const PAGE_READWRITE: u32 = 0x4; pub const PAGE_EXECUTE_READWRITE: u32 = 0x40; pub const PAGE_EXECUTE_READ: u32 = 0x20; pub const PAGE_EXECUTE: u32 = 0x10; pub const MEM_COMMIT: u32 = 0x1000; pub const MEM_RESERVE: u32 = 0x2000; pub const SECTION_MEM_READ: u32 = 0x40000000; pub const SECTION_MEM_WRITE: u32 = 0x80000000; pub const SECTION_MEM_EXECUTE: u32 = 0x20000000; // Access mask pub const GENERIC_READ: u32 = 0x80000000; pub const GENERIC_WRITE: u32 = 0x40000000; pub const GENERIC_EXECUTE: u32 = 0x20000000; pub const GENERIC_ALL: u32 = 0x10000000; pub const SECTION_ALL_ACCESS: u32 = 0x10000000; pub const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; pub const THREAD_ALL_ACCESS: u32 = 0x000F0000 | 0x00100000 | 0xFFFF; //File share flags pub const FILE_SHARE_NONE: u32 = 0x0; pub const FILE_SHARE_READ: u32 = 0x1; pub const FILE_SHARE_WRITE: u32 = 0x2; pub const FILE_SHARE_DELETE: u32 = 0x4; //File access flags pub const DELETE: u32 = 0x10000; pub const FILE_READ_DATA: u32 = 0x1; pub const FILE_READ_ATTRIBUTES: u32 = 0x80; pub const FILE_READ_EA: u32 = 0x8; pub const READ_CONTROL: u32 = 0x20000; pub const FILE_WRITE_DATA: u32 = 0x2; pub const FILE_WRITE_ATTRIBUTES: u32 = 0x100; pub const FILE_WRITE_EA: u32 = 0x10; pub const FILE_APPEND_DATA: u32 = 0x4; pub const WRITE_DAC: u32 = 0x40000; pub const WRITE_OWNER: u32 = 0x80000; pub const SYNCHRONIZE: u32 = 0x100000; pub const FILE_EXECUTE: u32 = 0x20; // File open flags pub const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x20; pub const FILE_NON_DIRECTORY_FILE: u32 = 0x40; pub const SEC_IMAGE: u32 = 0x1000000; #[derive(Clone)] #[repr(C)] pub struct PeMetadata { pub pe: u32, pub is_32_bit: bool, pub image_file_header: IMAGE_FILE_HEADER, pub opt_header_32: IMAGE_OPTIONAL_HEADER32, pub opt_header_64: IMAGE_OPTIONAL_HEADER64, pub sections: Vec<IMAGE_SECTION_HEADER> } impl Default for PeMetadata { fn default() -> PeMetadata { PeMetadata { pe: u32::default(), is_32_bit: false, image_file_header: IMAGE_FILE_HEADER::default(), opt_header_32: IMAGE_OPTIONAL_HEADER32::default(), opt_header_64: IMAGE_OPTIONAL_HEADER64::default(), sections: Vec::default(), } } } #[repr(C)] pub struct PeManualMap { pub decoy_module: String, pub base_address: isize, pub pe_info: PeMetadata, } #[repr(C)] #[derive(Copy, Clone, Default, PartialEq, Debug, Eq)] pub struct ApiSetNamespace { pub unused: [u8;12], pub count: i32, // offset 0x0C pub entry_offset: i32, // offset 0x10 } #[repr(C)] #[derive(Copy, Clone, Default, PartialEq, Debug, Eq)] pub struct ApiSetNamespaceEntry { pub unused1: [u8;4], pub name_offset: i32, // offset 0x04 pub name_length: i32, // offset 0x08 pub unused2: [u8;4], pub value_offset: i32, // offset 0x10 pub value_length: i32, // offset 0x14 } #[repr(C)] #[derive(Copy, Clone, Default, PartialEq, Debug, Eq)] pub struct ApiSetValueEntry { pub flags: i32, // offset 0x00 pub name_offset: i32, // offset 0x04 pub name_count: i32, // offset 0x08 pub value_offset: i32, // offset 0x0C pub value_count: i32, // offset 0x10 } #[derive(Copy, Clone, Default, PartialEq, Debug, Eq)] #[repr(C)] pub struct IMAGE_FILE_HEADER { pub machine: u16, pub number_of_sections: u16, pub time_data_stamp: u32, pub pointer_to_symbol_table: u32, pub number_of_symbols: u32, pub size_of_optional_header: u16, pub characteristics: u16, } #[derive(Copy, Clone,Default)] #[repr(C)] // required to keep fields order, otherwise Rust may change that order randomly pub struct IMAGE_OPTIONAL_HEADER64 { pub magic: u16, pub major_linker_version: u8, pub minor_linker_version: u8, pub size_of_code: u32, pub size_of_initialized_data: u32, pub size_of_unitialized_data: u32, pub address_of_entry_point: u32, pub base_of_code: u32, pub image_base: u64, pub section_alignment: u32, pub file_alignment: u32, pub major_operating_system_version: u16, pub minor_operating_system_version: u16, pub major_image_version: u16, pub minor_image_version: u16, pub major_subsystem_version: u16, pub minor_subsystem_version: u16, pub win32_version_value: u32, pub size_of_image: u32, pub size_of_headers: u32, pub checksum: u32, pub subsystem: u16, pub dll_characteristics: u16, pub size_of_stack_reserve: u64, pub size_of_stack_commit: u64, pub size_of_heap_reserve: u64, pub size_of_heap_commit: u64, pub loader_flags: u32, pub number_of_rva_and_sizes: u32, pub datas_directory: [IMAGE_DATA_DIRECTORY; 16], } #[derive(Copy, Clone, Default, PartialEq, Debug, Eq)] #[repr(C)] pub struct GUID { pub data1: u32, pub data2: u16, pub data3: u16, pub data4: [u8; 8], } #[repr(C)] pub struct SYSTEM_HANDLE_INFORMATION { pub number_of_handles: u32, pub handles: Vec<SYSTEM_HANDLE_TABLE_ENTRY_INFO>, } #[repr(C)] pub struct SYSTEM_HANDLE_TABLE_ENTRY_INFO { pub process_id: u16, pub creator_back_trace_index: u16, pub object_type_index: u8, pub handle_attributes: u8, pub handle_value: u16, pub object: PVOID, pub granted_access: u32, } #[repr(C)] pub struct CLIENT_ID { pub unique_process: HANDLE, pub unique_thread: HANDLE, } pub struct NtAllocateVirtualMemoryArgs { pub handle: HANDLE, pub base_address: *mut PVOID } pub struct NtOpenProcessArgs { pub handle: *mut HANDLE, pub access: u32, pub attributes: *mut OBJECT_ATTRIBUTES, pub client_id: *mut CLIENT_ID } pub struct NtProtectVirtualMemoryArgs { pub handle: HANDLE, pub base_address: *mut PVOID, pub size: *mut usize, pub protection: u32 } pub struct NtWriteVirtualMemoryArgs { pub handle: HANDLE, pub base_address: PVOID, pub buffer: PVOID, pub size: usize } pub struct NtCreateThreadExArgs { pub thread: *mut HANDLE, pub access: u32, pub attributes: *mut OBJECT_ATTRIBUTES, pub process: HANDLE } #[repr(C)] #[allow(non_snake_case)] pub struct CONTEXT { pub P1Home: u64, pub P2Home: u64, pub P3Home: u64, pub P4Home: u64, pub P5Home: u64, pub P6Home: u64, pub ContextFlags: u32, pub MxCsr: u32, pub SegCs: u16, pub SegDs: u16, pub SegEs: u16, pub SegFs: u16, pub SegGs: u16, pub SegSs: u16, pub EFlags: u32, pub Dr0: u64, pub Dr1: u64, pub Dr2: u64, pub Dr3: u64, pub Dr6: u64, pub Dr7: u64, pub Rax: u64, pub Rcx: u64, pub Rdx: u64, pub Rbx: u64, pub Rsp: u64, pub Rbp: u64, pub Rsi: u64, pub Rdi: u64, pub R8: u64, pub R9: u64, pub R10: u64, pub R11: u64, pub R12: u64, pub R13: u64, pub R14: u64, pub R15: u64, pub Rip: u64, pub Anonymous: [u8;4096], pub VectorRegister: [u8; 128*26], pub VectorControl: u64, pub DebugControl: u64, pub LastBranchToRip: u64, pub LastBranchFromRip: u64, pub LastExceptionToRip: u64, pub LastExceptionFromRip: u64, } impl Default for CONTEXT { fn default() -> CONTEXT { CONTEXT { P1Home: 0, P2Home: 0, P3Home: 0, P4Home: 0, P5Home: 0, P6Home: 0, ContextFlags: 0, MxCsr: 0, SegCs: 0, SegDs: 0, SegEs: 0, SegFs: 0, SegGs: 0, SegSs: 0, EFlags: 0, Dr0: 0, Dr1: 0, Dr2: 0, Dr3: 0, Dr6: 0, Dr7: 0, Rax: 0, Rcx: 0, Rdx: 0, Rbx: 0, Rsp: 0, Rbp: 0, Rsi: 0, Rdi: 0, R8: 0, R9: 0, R10: 0, R11: 0, R12: 0, R13: 0, R14: 0, R15: 0, Rip: 0, Anonymous: [0;4096], VectorRegister: [0; 128*26], VectorControl: 0, DebugControl: 0, LastBranchToRip: 0, LastBranchFromRip: 0, LastExceptionToRip: 0, LastExceptionFromRip: 0 } } } #[repr(C)] pub struct EXCEPTION_POINTERS { pub exception_record: *mut EXCEPTION_RECORD, pub context_record: *mut CONTEXT, } #[repr(C)] pub struct PS_ATTRIBUTE_LIST { pub size: u32, pub unk1: u32, pub unk2: u32, pub unk3: *mut u32, pub unk4: u32, pub unk5: u32, pub unk6: u32, pub unk7: *mut u32, pub unk8: u32, } pub enum ExceptionHandleFunction { NtOpenProcess, NtAllocateVirtualMemory, NtWriteVirtualMemory, NtProtectVirtualMemory, NtCreateThreadEx } #[repr(C)] #[derive(Copy, Clone, Default)] pub struct RUNTIME_FUNCTION { pub begin_addr: u32, pub end_addr: u32, pub unwind_addr: u32 } pub struct FILE_PROCESS_IDS_USING_FILE_INFORMATION { pub number_of_process_ids_in_list: u32, pub process_id_list: [usize;500], }
rust
Apache-2.0
31a0ce7f22fd2ea5e32f5fa9a56a446127fcf66f
2026-01-04T20:24:46.785945Z
false
EightB1ts/uni-sync
https://github.com/EightB1ts/uni-sync/blob/05f39462178b60f590bfd9daa3b4863038c0f6ad/src/main.rs
src/main.rs
use std::env; use std::path::PathBuf; mod devices; fn main() -> Result<(), std::io::Error> { let mut configs = devices::Configs { configs: vec![] }; let args: Vec<String> = env::args().collect(); let mut config_path: PathBuf = env::current_exe()?; if args.len() == 2 { config_path.clear(); config_path.push(&args[1]) } else { config_path.pop(); config_path.push("uni-sync.json"); } #[cfg(target_os = "linux")] { config_path.clear(); config_path.push("/etc/uni-sync/uni-sync.json"); } #[cfg(target_os = "linux")] { let dir = std::path::Path::new("/etc/uni-sync"); if !dir.exists() { if let Err(e) = std::fs::create_dir(dir) { eprintln!("Failed to create directory: {}, error: {}", dir.to_string_lossy(), e); } } } if !config_path.exists() { println!("Config path {:?} does not exist. Generating default configuration.", config_path); std::fs::write(&config_path, serde_json::to_string_pretty(&configs).unwrap())?; } else { println!("Loading configuration {:?}", config_path) } let config_content = std::fs::read_to_string(&config_path)?; configs = serde_json::from_str::<devices::Configs>(&config_content)?; let new_configs = devices::run(configs); std::fs::write(&config_path, serde_json::to_string_pretty(&new_configs)?)?; Ok(()) }
rust
MIT
05f39462178b60f590bfd9daa3b4863038c0f6ad
2026-01-04T20:24:49.606579Z
false
EightB1ts/uni-sync
https://github.com/EightB1ts/uni-sync/blob/05f39462178b60f590bfd9daa3b4863038c0f6ad/src/devices/mod.rs
src/devices/mod.rs
use serde_derive::{Deserialize, Serialize}; use hidapi::{self, HidDevice}; use std::{thread, time}; #[derive(Serialize, Deserialize, Clone)] pub struct Configs { pub configs: Vec<Config> } #[derive(Serialize, Deserialize, Clone)] pub struct Config { pub device_id: String, pub sync_rgb: bool, pub channels: Vec<Channel> } #[derive(Serialize, Deserialize, Clone)] pub struct Channel { pub mode: String, pub speed: usize, } const VENDOR_IDS: [u16; 1] = [ 0x0cf2 ]; const PRODUCT_IDS: [u16; 7] = [ 0x7750, 0xa100, 0xa101, 0xa102, 0xa103, 0xa104, 0xa105 ]; pub fn run(mut existing_configs: Configs) -> Configs { let mut default_channels: Vec<Channel> = Vec::new(); for _x in 0..4 { default_channels.push(Channel { mode: "Manual".to_string(), speed: 50 }); } // Get All Devices let api = match hidapi::HidApi::new() { Ok(api) => api, Err(_) => panic!("Could not find any controllers") }; for hiddevice in api.device_list() { if VENDOR_IDS.contains(&hiddevice.vendor_id()) && PRODUCT_IDS.contains(&hiddevice.product_id()) { let serial_number: &str = match hiddevice.serial_number() { Some(sn) => sn, None => { println!("Serial number not available for device {:?}", hiddevice); continue; } }; let path: &str = match hiddevice.path() { p => p.to_str().unwrap_or("unknown"), }; let device_id: String = format!("VID:{}/PID:{}/SN:{}/PATH:{}", hiddevice.vendor_id().to_string(), hiddevice.product_id().to_string(), serial_number.to_string(), path.to_string()); let hid: HidDevice = match api.open_path(hiddevice.path()) { Ok(hid) => hid, Err(_) => { println!("Please run uni-sync with elevated permissions."); std::process::exit(0); } }; let mut channels: Vec<Channel> = default_channels.clone(); let mut sync_rgb: bool = false; println!("Found: {:?}", device_id); if let Some(config) = existing_configs.configs.iter().find( | config | config.device_id == device_id) { channels = config.channels.clone(); sync_rgb = config.sync_rgb; } else { existing_configs.configs.push(Config { device_id: device_id, sync_rgb: false, channels: channels.clone() }); } // Send Command to Sync to RGB Header let sync_byte: u8 = if sync_rgb { 1 } else { 0 }; let _ = match &hiddevice.product_id() { 0xa100|0x7750 => hid.write(&[224, 16, 48, sync_byte, 0, 0, 0]), // SL 0xa101 => hid.write(&[224, 16, 65, sync_byte, 0, 0, 0]), // AL 0xa102 => hid.write(&[224, 16, 97, sync_byte, 0, 0, 0]), // SLI 0xa103|0xa105 => hid.write(&[224, 16, 97, sync_byte, 0, 0, 0]), // SLv2 0xa104 => hid.write(&[224, 16, 97, sync_byte, 0, 0, 0]), // ALv2 _ => hid.write(&[224, 16, 48, sync_byte, 0, 0, 0]), // SL }; // Avoid Race Condition thread::sleep(time::Duration::from_millis(200)); for x in 0..channels.len() { // Disable Sync to fan header let mut channel_byte = 0x10 << x; if channels[x].mode == "PWM" { channel_byte = channel_byte | 0x1 << x; } let _ = match &hiddevice.product_id() { 0xa100|0x7750 => hid.write(&[224, 16, 49, channel_byte]), // SL 0xa101 => hid.write(&[224, 16, 66, channel_byte]), // AL 0xa102 => hid.write(&[224, 16, 98, channel_byte]), // SLI 0xa103|0xa105 => hid.write(&[224, 16, 98, channel_byte]), // SLv2 0xa104 => hid.write(&[224, 16, 98, channel_byte]), // ALv2 _ => hid.write(&[224, 16, 49, channel_byte]), // SL }; // Avoid Race Condition thread::sleep(time::Duration::from_millis(200)); // Set Channel Speed if channels[x].mode == "Manual" { let mut speed = channels[x].speed as f64; if speed > 100.0 { speed = 100.0 } let speed_800_1900: u8 = ((800.0 + (11.0 * speed)) as usize / 19).try_into().unwrap(); let speed_250_2000: u8 = ((250.0 + (17.5 * speed)) as usize / 20).try_into().unwrap(); let speed_200_2100: u8 = ((200.0 + (19.0 * speed)) as usize / 21).try_into().unwrap(); let _ = match &hiddevice.product_id() { 0xa100|0x7750 => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_800_1900]), // SL 0xa101 => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_800_1900]), // AL 0xa102 => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_200_2100]), // SLI 0xa103|0xa105 => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_250_2000]), // SLv2 0xa104 => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_250_2000]), // ALv2 _ => hid.write(&[224, (x+32).try_into().unwrap(), 0, speed_800_1900]), // SL }; // Avoid Race Condition thread::sleep(time::Duration::from_millis(100)); } } } } return existing_configs; }
rust
MIT
05f39462178b60f590bfd9daa3b4863038c0f6ad
2026-01-04T20:24:49.606579Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dusty/src/main.rs
dusty/src/main.rs
//! Tool to inspect the representation of USDT probes in object files. // Copyright 2021 Oxide Computer Company // // 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. use clap::Parser; use std::path::PathBuf; use usdt::probe_records; use usdt_impl::Error as UsdtError; /// Inspect data related to USDT probes in object files. #[derive(Debug, Parser)] struct Cmd { /// The object file to inspect file: PathBuf, /// Operate more verbosely, printing all available information #[arg(short, long)] verbose: bool, /// Print raw binary data along with summaries or headers #[arg(short, long, conflicts_with = "json")] raw: bool, /// Format output as JSON #[arg(short, long)] json: bool, } fn main() { let cmd = Cmd::parse(); let format_mode = if cmd.raw { dof::fmt::FormatMode::Raw { include_sections: cmd.verbose, } } else if cmd.json { dof::fmt::FormatMode::Json } else { dof::fmt::FormatMode::Pretty }; match probe_records(&cmd.file) { Ok(data) => match dof::fmt::fmt_dof(data, format_mode) { Ok(Some(dof)) => println!("{}", dof), Ok(None) => println!("No probe information found"), Err(e) => println!("Failed to format probe information, {:?}", e), }, Err(UsdtError::InvalidFile) => { println!("No probe information found"); } Err(e) => { println!("Failed to parse probe information, {:?}", e); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/probe-test-build/build.rs
probe-test-build/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=test.d"); Builder::new("test.d").build().unwrap(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/probe-test-build/src/main.rs
probe-test-build/src/main.rs
//! An example using the `usdt` crate, generating the probes via a build script. // Copyright 2022 Oxide Computer Company // // 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. use std::thread::sleep; use std::time::Duration; use usdt::register_probes; // Include the Rust implementation generated by the build script. include!(concat!(env!("OUT_DIR"), "/test.rs")); fn main() { let duration = Duration::from_secs(1); let mut counter: u8 = 0; // NOTE: One _must_ call this function in order to actually register the probes with DTrace. // Without this, it won't be possible to list, enable, or see the probes via `dtrace(1)`. register_probes().unwrap(); loop { // Call the "start_work" probe which accepts a u8. test::start_work!(|| counter); // Do some work. sleep(duration); // Call the "stop_work" probe, which accepts a string, u8, and string. test::stop_work!(|| ( format!("the probe has fired {}", counter), counter, format!("{:x}", counter) )); counter = counter.wrapping_add(1); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-tests-common/src/lib.rs
usdt-tests-common/src/lib.rs
// Copyright 2024 Oxide Computer Company // // 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. #[cfg(target_os = "illumos")] pub fn root_command() -> String { // On illumos systems, we prefer pfexec(1) but allow some other command to // be specified through the environment. std::env::var("PFEXEC").unwrap_or_else(|_| "/usr/bin/pfexec".to_string()) } #[cfg(not(target_os = "illumos"))] pub fn root_command() -> String { String::from("sudo") }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dtrace-parser/src/lib.rs
dtrace-parser/src/lib.rs
//! A small library for parsing DTrace provider files. // Copyright 2021 Oxide Computer Company // // 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. use pest::iterators::{Pair, Pairs}; use pest_derive::Parser; use std::collections::HashSet; use std::convert::TryFrom; use std::fs; use std::path::Path; use thiserror::Error; type PestError = pest::error::Error<Rule>; /// Type representing errors that occur when parsing a D file. #[derive(Error, Debug)] pub enum DTraceError { #[error("Unexpected token type, expected {expected:?}, found {found:?}")] UnexpectedToken { expected: Rule, found: Rule }, #[error("This set of pairs contains no tokens")] EmptyPairsIterator, #[error("Provider and probe name pairs must be unique: duplicated \"{0:?}\"")] DuplicateProbeName((String, String)), #[error("The provider name \"{0}\" is invalid")] InvalidProviderName(String), #[error("The probe name \"{0}\" is invalid")] InvalidProbeName(String), #[error(transparent)] IO(#[from] std::io::Error), #[error("Input is not a valid DTrace provider definition:\n{0}")] ParseError(#[from] Box<PestError>), } #[derive(Parser, Debug)] #[grammar = "dtrace.pest"] struct DTraceParser; // Helper which verifies that the given `pest::Pair` conforms to the expected grammar rule. fn expect_token(pair: &Pair<'_, Rule>, rule: Rule) -> Result<(), DTraceError> { if pair.as_rule() == rule { Ok(()) } else { Err(DTraceError::UnexpectedToken { expected: rule, found: pair.as_rule(), }) } } /// The bit-width of an integer data type #[derive(Clone, Copy, Debug, PartialEq)] pub enum BitWidth { Bit8, Bit16, Bit32, Bit64, /// The width of the native pointer type. Pointer, } /// The signed-ness of an integer data type #[derive(Clone, Copy, Debug, PartialEq)] pub enum Sign { Signed, Unsigned, } /// An integer data type #[derive(Clone, Copy, Debug, PartialEq)] pub struct Integer { pub sign: Sign, pub width: BitWidth, } const RUST_TYPE_PREFIX: &str = "::std::os::raw::c_"; impl Integer { fn width_to_c_str(&self) -> &'static str { match self.width { BitWidth::Bit8 => "8", BitWidth::Bit16 => "16", BitWidth::Bit32 => "32", BitWidth::Bit64 => "64", #[cfg(target_pointer_width = "32")] BitWidth::Pointer => "32", #[cfg(target_pointer_width = "64")] BitWidth::Pointer => "64", #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] BitWidth::Pointer => compile_error!("Unsupported pointer width"), } } pub fn to_c_type(&self) -> String { let prefix = match self.sign { Sign::Unsigned => "u", _ => "", }; format!("{prefix}int{}_t", self.width_to_c_str()) } pub fn to_rust_ffi_type(&self) -> String { let ty = match (self.sign, self.width) { (Sign::Unsigned, BitWidth::Bit8) => "uchar", (Sign::Unsigned, BitWidth::Bit16) => "ushort", (Sign::Unsigned, BitWidth::Bit32) => "uint", (Sign::Unsigned, BitWidth::Bit64) => "ulonglong", #[cfg(target_pointer_width = "32")] (Sign::Unsigned, BitWidth::Pointer) => "uint", #[cfg(target_pointer_width = "64")] (Sign::Unsigned, BitWidth::Pointer) => "ulonglong", (Sign::Signed, BitWidth::Bit8) => "schar", (Sign::Signed, BitWidth::Bit16) => "short", (Sign::Signed, BitWidth::Bit32) => "int", (Sign::Signed, BitWidth::Bit64) => "longlong", #[cfg(target_pointer_width = "32")] (Sign::Signed, BitWidth::Pointer) => "int", #[cfg(target_pointer_width = "64")] (Sign::Signed, BitWidth::Pointer) => "longlong", #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] (_, BitWidth::Pointer) => compile_error!("Unsupported pointer width"), }; format!("{RUST_TYPE_PREFIX}{ty}") } fn width_to_str(&self) -> &'static str { match self.width { BitWidth::Pointer => "size", _ => self.width_to_c_str(), } } pub fn to_rust_type(&self) -> String { let prefix = match self.sign { Sign::Signed => "i", Sign::Unsigned => "u", }; format!("{prefix}{}", self.width_to_str()) } } /// Represents the data type of a single probe argument. #[derive(Clone, Copy, Debug, PartialEq)] pub enum DataType { Integer(Integer), Pointer(Integer), String, } impl From<Pair<'_, Rule>> for Integer { fn from(integer_type: Pair<'_, Rule>) -> Integer { let sign = match integer_type.as_rule() { Rule::SIGNED_INT => Sign::Signed, Rule::UNSIGNED_INT => Sign::Unsigned, _ => unreachable!("Expected a signed or unsigned integer"), }; let width = match integer_type.into_inner().as_str() { "8" => BitWidth::Bit8, "16" => BitWidth::Bit16, "32" => BitWidth::Bit32, "64" => BitWidth::Bit64, "ptr" => BitWidth::Pointer, _ => unreachable!("Expected a bit width"), }; Integer { sign, width } } } impl TryFrom<&Pair<'_, Rule>> for DataType { type Error = DTraceError; fn try_from(pair: &Pair<'_, Rule>) -> Result<DataType, Self::Error> { expect_token(pair, Rule::DATA_TYPE)?; let inner = pair .clone() .into_inner() .next() .expect("Data type token is expected to contain a concrete type"); let typ = match inner.as_rule() { Rule::INTEGER => { let integer = pair .clone() .into_inner() .next() .expect("Expected a signed or unsigned integral type"); assert!(matches!(integer.as_rule(), Rule::INTEGER)); DataType::Integer(Integer::from( integer .clone() .into_inner() .next() .expect("Expected an integral type"), )) } Rule::INTEGER_POINTER => { let pointer = pair .clone() .into_inner() .next() .expect("Expected a pointer to a signed or unsigned integral type"); assert!(matches!(pointer.as_rule(), Rule::INTEGER_POINTER)); let mut parts = pointer.clone().into_inner(); let integer = parts .next() .expect("Expected a signed or unsigned integral type"); let star = parts.next().expect("Expected a literal `*`"); assert_eq!(star.as_rule(), Rule::STAR); DataType::Pointer(Integer::from( integer .clone() .into_inner() .next() .expect("Expected an integral type"), )) } Rule::STRING => DataType::String, _ => unreachable!("Parsed an unexpected DATA_TYPE token"), }; Ok(typ) } } impl TryFrom<&Pairs<'_, Rule>> for DataType { type Error = DTraceError; fn try_from(pairs: &Pairs<'_, Rule>) -> Result<DataType, Self::Error> { DataType::try_from(&pairs.peek().ok_or(DTraceError::EmptyPairsIterator)?) } } impl DataType { /// Convert a type into its C type representation as a string pub fn to_c_type(&self) -> String { match self { DataType::Integer(int) => int.to_c_type(), DataType::Pointer(int) => format!("{}*", int.to_c_type()), DataType::String => String::from("char*"), } } /// Return the Rust FFI type representation of this data type pub fn to_rust_ffi_type(&self) -> String { match self { DataType::Integer(int) => int.to_rust_ffi_type(), DataType::Pointer(int) => format!("*const {}", int.to_rust_ffi_type()), DataType::String => format!("*const {RUST_TYPE_PREFIX}char"), } } /// Return the native Rust type representation of this data type pub fn to_rust_type(&self) -> String { match self { DataType::Integer(int) => int.to_rust_type(), DataType::Pointer(int) => format!("*const {}", int.to_rust_type()), DataType::String => String::from("&str"), } } } /// Type representing a single D probe definition within a provider. #[derive(Clone, Debug, PartialEq)] pub struct Probe { pub name: String, pub types: Vec<DataType>, } impl TryFrom<&Pair<'_, Rule>> for Probe { type Error = DTraceError; fn try_from(pair: &Pair<'_, Rule>) -> Result<Self, Self::Error> { expect_token(pair, Rule::PROBE)?; let mut inner = pair.clone().into_inner(); expect_token( &inner.next().expect("Expected the literal 'probe'"), Rule::PROBE_KEY, )?; let token = inner.next().expect("Expected a probe name"); let name = token.as_str().to_string(); if name == "probe" || name == "start" { return Err(DTraceError::InvalidProbeName(name)); } expect_token( &inner.next().expect("Expected the literal '('"), Rule::LEFT_PAREN, )?; let possibly_argument_list = inner .next() .expect("Expected an argument list or literal ')'"); let mut types = Vec::new(); if expect_token(&possibly_argument_list, Rule::ARGUMENT_LIST).is_ok() { let arguments = possibly_argument_list.clone().into_inner(); for data_type in arguments { expect_token(&data_type, Rule::DATA_TYPE)?; types.push(DataType::try_from(&data_type)?); } } expect_token( &inner.next().expect("Expected a literal ')'"), Rule::RIGHT_PAREN, )?; expect_token( &inner.next().expect("Expected a literal ';'"), Rule::SEMICOLON, )?; Ok(Probe { name, types }) } } impl TryFrom<&Pairs<'_, Rule>> for Probe { type Error = DTraceError; fn try_from(pairs: &Pairs<'_, Rule>) -> Result<Self, Self::Error> { Probe::try_from(&pairs.peek().ok_or(DTraceError::EmptyPairsIterator)?) } } /// Type representing a single DTrace provider and all of its probes. #[derive(Debug, Clone, PartialEq)] pub struct Provider { pub name: String, pub probes: Vec<Probe>, } impl TryFrom<&Pair<'_, Rule>> for Provider { type Error = DTraceError; fn try_from(pair: &Pair<'_, Rule>) -> Result<Self, Self::Error> { expect_token(pair, Rule::PROVIDER)?; let mut inner = pair.clone().into_inner(); expect_token( &inner.next().expect("Expected the literal 'provider'"), Rule::PROVIDER_KEY, )?; let name = inner .next() .expect("Expected a provider name") .as_str() .to_string(); if name == "provider" { return Err(DTraceError::InvalidProviderName(name)); } expect_token( &inner.next().expect("Expected the literal '{'"), Rule::LEFT_BRACE, )?; let mut probes = Vec::new(); let mut possibly_probe = inner .next() .expect("Expected at least one probe in the provider"); while expect_token(&possibly_probe, Rule::PROBE).is_ok() { probes.push(Probe::try_from(&possibly_probe)?); possibly_probe = inner.next().expect("Expected a token"); } expect_token(&possibly_probe, Rule::RIGHT_BRACE)?; expect_token( &inner.next().expect("Expected a literal ';'"), Rule::SEMICOLON, )?; Ok(Provider { name, probes }) } } impl TryFrom<&Pairs<'_, Rule>> for Provider { type Error = DTraceError; fn try_from(pairs: &Pairs<'_, Rule>) -> Result<Self, Self::Error> { Provider::try_from(&pairs.peek().ok_or(DTraceError::EmptyPairsIterator)?) } } /// Type representing a single D file and all the providers it defines. #[derive(Debug, Clone, PartialEq)] pub struct File { name: String, providers: Vec<Provider>, } impl TryFrom<&Pair<'_, Rule>> for File { type Error = DTraceError; fn try_from(pair: &Pair<'_, Rule>) -> Result<Self, Self::Error> { expect_token(pair, Rule::FILE)?; let mut providers = Vec::new(); let mut names = HashSet::new(); for item in pair.clone().into_inner() { if item.as_rule() == Rule::PROVIDER { let provider = Provider::try_from(&item)?; for probe in provider.probes.iter() { let name = (provider.name.clone(), probe.name.clone()); if names.contains(&name) { return Err(DTraceError::DuplicateProbeName(name)); } names.insert(name.clone()); } providers.push(provider); } } Ok(File { name: "".to_string(), providers, }) } } impl TryFrom<&Pairs<'_, Rule>> for File { type Error = DTraceError; fn try_from(pairs: &Pairs<'_, Rule>) -> Result<Self, Self::Error> { File::try_from(&pairs.peek().ok_or(DTraceError::EmptyPairsIterator)?) } } impl File { /// Load and parse a provider from a D file at the given path. pub fn from_file(filename: &Path) -> Result<Self, DTraceError> { let mut f = File::try_from(fs::read_to_string(filename)?.as_str())?; f.name = filename .file_stem() .unwrap() .to_os_string() .into_string() .unwrap(); Ok(f) } /// Return the name of the file. pub fn name(&self) -> &String { &self.name } /// Return the list of providers this file defines. pub fn providers(&self) -> &Vec<Provider> { &self.providers } } impl TryFrom<&str> for File { type Error = DTraceError; fn try_from(s: &str) -> Result<Self, Self::Error> { use pest::Parser; File::try_from(&DTraceParser::parse(Rule::FILE, s).map_err(|e| { Box::new(e.renamed_rules(|rule| match *rule { Rule::DATA_TYPE | Rule::BIT_WIDTH => { format!( "{:?}.\n\n{}", *rule, concat!( "Unsupported type, the following are supported:\n", " - uint8_t\n", " - uint16_t\n", " - uint32_t\n", " - uint64_t\n", " - int8_t\n", " - int16_t\n", " - int32_t\n", " - int64_t\n", " - &str\n", ) ) } _ => format!("{:?}", rule), })) })?) } } #[cfg(test)] mod tests { use super::BitWidth; use super::DTraceParser; use super::DataType; use super::File; use super::Integer; use super::Probe; use super::Provider; use super::Rule; use super::Sign; use super::TryFrom; use ::pest::Parser; use rstest::{fixture, rstest}; #[rstest( token, rule, case("probe", Rule::PROBE_KEY), case("provider", Rule::PROVIDER_KEY), case(";", Rule::SEMICOLON), case("(", Rule::LEFT_PAREN), case(")", Rule::RIGHT_PAREN), case("{", Rule::LEFT_BRACE), case("}", Rule::RIGHT_BRACE) )] fn test_basic_tokens(token: &str, rule: Rule) { assert!(DTraceParser::parse(rule, token).is_ok()); } #[test] #[should_panic] fn test_bad_basic_token() { assert!(DTraceParser::parse(Rule::LEFT_BRACE, "x").is_ok()) } #[test] fn test_identifier() { assert!(DTraceParser::parse(Rule::IDENTIFIER, "foo").is_ok()); assert!(DTraceParser::parse(Rule::IDENTIFIER, "foo_bar").is_ok()); assert!(DTraceParser::parse(Rule::IDENTIFIER, "foo9").is_ok()); assert!(DTraceParser::parse(Rule::IDENTIFIER, "_bar").is_err()); assert!(DTraceParser::parse(Rule::IDENTIFIER, "").is_err()); assert!(DTraceParser::parse(Rule::IDENTIFIER, "9foo").is_err()); } #[test] fn test_data_types() { assert!(DTraceParser::parse(Rule::DATA_TYPE, "uint8_t").is_ok()); assert!(DTraceParser::parse(Rule::DATA_TYPE, "int").is_err()); assert!(DTraceParser::parse(Rule::DATA_TYPE, "flaot").is_err()); } #[test] fn test_probe() { let defn = "probe foo(uint8_t, uint16_t, uint16_t);"; assert!(DTraceParser::parse(Rule::PROBE, defn).is_ok()); assert!(DTraceParser::parse(Rule::PROBE, &defn[..defn.len() - 2]).is_err()); } #[test] fn test_basic_provider() { let defn = r#" provider foo { probe bar(); probe baz(char*, uint16_t, uint8_t); };"#; println!("{:?}", DTraceParser::parse(Rule::FILE, defn)); assert!(DTraceParser::parse(Rule::FILE, defn).is_ok()); assert!(DTraceParser::parse(Rule::FILE, &defn[..defn.len() - 2]).is_err()); } #[test] fn test_null_provider() { let defn = "provider foo { };"; assert!(DTraceParser::parse(Rule::FILE, defn).is_err()); } #[test] fn test_comment_provider() { let defn = r#" /* Check out this fly provider */ provider foo { probe bar(); probe baz(char*, uint16_t, uint8_t); };"#; assert!(DTraceParser::parse(Rule::FILE, defn).is_ok()); } #[test] fn test_pragma_provider() { let defn = r#" #pragma I am a robot provider foo { probe bar(); probe baz(char*, uint16_t, uint8_t); }; "#; println!("{}", defn); assert!(DTraceParser::parse(Rule::FILE, defn).is_ok()); } #[test] fn test_two_providers() { let defn = r#" provider foo { probe bar(); probe baz(char*, uint16_t, uint8_t); }; provider bar { probe bar(); probe baz(char*, uint16_t, uint8_t); }; "#; println!("{}", defn); assert!(DTraceParser::parse(Rule::FILE, defn).is_ok()); } #[rstest( defn, data_type, case("uint8_t", DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8 })), case("uint16_t", DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit16 })), case("uint32_t", DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit32 })), case("uint64_t", DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit64 })), case("uintptr_t", DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Pointer })), case("int8_t", DataType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Bit8 })), case("int16_t", DataType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Bit16 })), case("int32_t", DataType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Bit32 })), case("int64_t", DataType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Bit64 })), case("intptr_t", DataType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Pointer })), case("uint8_t*", DataType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8})), case("uint16_t*", DataType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit16})), case("uint32_t*", DataType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit32})), case("uint64_t*", DataType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit64})), case("int8_t*", DataType::Pointer(Integer { sign: Sign::Signed, width: BitWidth::Bit8})), case("int16_t*", DataType::Pointer(Integer { sign: Sign::Signed, width: BitWidth::Bit16})), case("int32_t*", DataType::Pointer(Integer { sign: Sign::Signed, width: BitWidth::Bit32})), case("int64_t*", DataType::Pointer(Integer { sign: Sign::Signed, width: BitWidth::Bit64})), case("char*", DataType::String) )] fn test_data_type_enum(defn: &str, data_type: DataType) { let dtype = DataType::try_from(&DTraceParser::parse(Rule::DATA_TYPE, defn).unwrap()).unwrap(); assert_eq!(dtype, data_type); } #[test] fn test_data_type_conversion() { let dtype = DataType::try_from(&DTraceParser::parse(Rule::DATA_TYPE, "uint8_t").unwrap()).unwrap(); assert_eq!(dtype.to_rust_ffi_type(), "::std::os::raw::c_uchar"); } #[fixture] fn probe_data() -> (String, String) { let provider = String::from("foo"); let probe = String::from("probe baz(char*, uint16_t, uint8_t*);"); (provider, probe) } #[fixture] fn probe(probe_data: (String, String)) -> (String, Probe) { ( probe_data.0, Probe::try_from(&DTraceParser::parse(Rule::PROBE, &probe_data.1).unwrap()).unwrap(), ) } #[rstest] fn test_probe_struct_parse(probe_data: (String, String)) { let (_, probe) = probe_data; let probe = Probe::try_from(&DTraceParser::parse(Rule::PROBE, &probe).unwrap()) .expect("Could not parse probe tokens"); assert_eq!(probe.name, "baz"); assert_eq!( probe.types, &[ DataType::String, DataType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit16, }), DataType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, }), ] ); } fn data_file(name: &str) -> String { format!("{}/test-data/{}", env!("CARGO_MANIFEST_DIR"), name) } #[test] fn test_provider_struct() { let provider_name = "foo"; let defn = std::fs::read_to_string(data_file(&format!("{}.d", provider_name))).unwrap(); let provider = Provider::try_from( &DTraceParser::parse(Rule::FILE, &defn) .unwrap() .next() .unwrap() .into_inner(), ); let provider = provider.unwrap(); assert_eq!(provider.name, provider_name); assert_eq!(provider.probes.len(), 1); assert_eq!(provider.probes[0].name, "baz"); } #[test] fn test_file_struct() { let defn = r#" /* a comment */ #pragma do stuff provider foo { probe quux(); probe quack(char*, uint16_t, uint8_t); }; provider bar { probe bar(); probe baz(char*, uint16_t, uint8_t); }; "#; let file = File::try_from(&DTraceParser::parse(Rule::FILE, defn).unwrap()).unwrap(); assert_eq!(file.providers.len(), 2); assert_eq!(file.providers[0].name, "foo"); assert_eq!(file.providers[1].probes[1].name, "baz"); let file2 = File::try_from(defn).unwrap(); assert_eq!(file, file2); assert!(File::try_from("this is not a D file").is_err()); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/empty/build.rs
tests/empty/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=provider.d"); Builder::new("provider.d") .build() .expect("Failed to build provider"); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/empty/src/main.rs
tests/empty/src/main.rs
// Copyright 2022 Oxide Computer Company // // 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. #![deny(warnings)] use usdt::register_probes; include!(concat!(env!("OUT_DIR"), "/provider.rs")); fn main() { register_probes().unwrap(); let counter: u8 = 0; stuff::start_work!(|| counter); stuff::stop_work!(|| ("the probe has fired", counter)); stuff::noargs!(|| ()); stuff::noargs!(); } #[cfg(test)] mod test { // We just want to make sure that main builds and runs. #[test] fn test_main() { super::main(); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/test-json/src/main.rs
tests/test-json/src/main.rs
//! Integration test verifying JSON output, including when serialization fails. // Copyright 2024 Oxide Computer Company // // 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. use serde::{Serialize, Serializer}; // Expected error message from serialization failure const SERIALIZATION_ERROR: &str = "nonono"; #[derive(Debug, Serialize)] pub struct ProbeArg { value: u8, buffer: Vec<i64>, } impl Default for ProbeArg { fn default() -> Self { ProbeArg { value: 1, buffer: vec![1, 2, 3], } } } // A type that intentionally fails serialization #[derive(Debug, Default)] pub struct NotJsonSerializable { _x: u8, } impl Serialize for NotJsonSerializable { fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> { Err(serde::ser::Error::custom(SERIALIZATION_ERROR)) } } #[usdt::provider] mod test_json { use crate::{NotJsonSerializable, ProbeArg as GoodArg}; fn good(_: &GoodArg) {} fn bad(_: &NotJsonSerializable) {} } fn main() { usdt::register_probes().unwrap(); let arg = ProbeArg::default(); test_json::good!(|| &arg); } #[cfg(test)] mod tests { use super::*; use std::time::Duration; use tokio::io::AsyncReadExt; use tokio::process::Child; use tokio::sync::mpsc::Receiver; use tokio::time::Instant; // Maximum duration to wait for tracer subprocess, controlling total test duration const MAX_WAIT: Duration = Duration::from_secs(30); // A sentinel printed by tracer subprocess, so we know when it starts up successfully. const BEGIN_SENTINEL: &str = "BEGIN"; // Fire the test probes in sequence, when a notification is received on the channel. async fn fire_test_probes(mut recv: Receiver<()>) { usdt::register_probes().unwrap(); // Wait for notification from the main thread println!("Test runner waiting for first notification"); recv.recv().await.unwrap(); println!("Test runner firing first probe"); // Fire the good probe until the main thread signals us to continue. let data = ProbeArg::default(); test_json::good!(|| &data); println!("Test runner fired first probe"); println!("Test runner awaiting notification to continue"); recv.recv().await.unwrap(); println!("Test runner received notification to continue"); // Fire the bad probe. println!("Test runner firing second probe"); let data = NotJsonSerializable::default(); test_json::bad!(|| &data); println!("Test runner fired second probe"); } // Check tracer subprocess stdout for the begin sentinel, telling us the program has spawned // successfully. async fn wait_for_begin_sentinel(trace: &mut Child, now: &Instant) { let mut output = String::new(); let stdout = trace.stdout.as_mut().expect("Expected piped stdout"); let max_time = *now + MAX_WAIT; // Try to read data from stdout, up to the maximum wait time. This may take multiple reads, // though it's pretty unlikely. while now.elapsed() < MAX_WAIT { let read_task = tokio::time::timeout_at(max_time, async { let mut bytes = vec![0; 128]; stdout.read(&mut bytes).await.map(|_| bytes) }); match read_task.await { Ok(read_result) => { let chunk = read_result.expect("Failed to read tracer stdout"); output.push_str(std::str::from_utf8(&chunk).expect("Non-UTF8 stdout")); if output.contains(BEGIN_SENTINEL) { println!("tracer started up successfully"); return; } } _ => {} } println!("tracer not yet ready"); continue; } panic!("tracer failed to startup within {:?}", MAX_WAIT); } #[cfg(not(target_os = "linux"))] mod dtrace { use super::*; use serde_json::Value; use std::process::Stdio; use tokio::process::Command; use tokio::sync::mpsc::channel; use tokio::sync::mpsc::Sender; use tokio::time::Instant; use usdt_tests_common::root_command; // Run DTrace as a subprocess, waiting for the JSON output of the provided probe. async fn run_dtrace_and_return_json(tx: &Sender<()>, probe_name: &str) -> Value { // Start the DTrace subprocess, and don't exit if the probe doesn't exist. let mut dtrace = Command::new(root_command()) .arg("dtrace") .arg("-Z") .arg("-q") .arg("-n") // The test probe we're interested in listening for. .arg(format!( "test_json{}:::{} {{ printf(\"%s\", copyinstr(arg0)); exit(0); }}", std::process::id(), probe_name )) .arg("-n") // An output printed by DTrace when it starts, to coordinate with the test thread // firing the probe itself. .arg(format!("BEGIN {{ trace(\"{}\"); }}", BEGIN_SENTINEL)) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("Failed to spawn DTrace subprocess"); // Wait for DTrace to correctly start up before notifying the test thread to start // firing probes. let now = Instant::now(); wait_for_begin_sentinel(&mut dtrace, &now).await; // Instruct the task firing probes to continue. tx.send(()).await.unwrap(); // Wait for the process to finish, up to a pretty generous limit. let output = tokio::time::timeout_at(now + MAX_WAIT, dtrace.wait_with_output()) .await .expect(&format!("DTrace did not complete within {:?}", MAX_WAIT)) .expect("Failed to wait for DTrace subprocess"); assert!( output.status.success(), "DTrace process failed:\n{:?}", String::from_utf8_lossy(&output.stderr), ); let stdout = std::str::from_utf8(&output.stdout).expect("Non-UTF8 stdout"); println!("DTrace output\n{}\n", stdout); let json: Value = serde_json::from_str(&stdout).unwrap(); json } #[tokio::test] async fn test_json_support() { let (tx, rx) = channel(4); let test_task = tokio::task::spawn(fire_test_probes(rx)); let json = run_dtrace_and_return_json(&tx, "good").await; assert!(json.get("ok").is_some()); assert!(json.get("err").is_none()); assert_eq!(json["ok"]["value"], Value::from(1)); assert_eq!(json["ok"]["buffer"], Value::from(vec![1, 2, 3])); // Tell the thread to continue with the bad probe let json = run_dtrace_and_return_json(&tx, "bad").await; assert!(json.get("ok").is_none()); assert!(json.get("err").is_some()); assert_eq!(json["err"], Value::from(SERIALIZATION_ERROR)); test_task.await.unwrap(); } } #[cfg(target_os = "linux")] mod stap { use super::*; use serde_json::Value; use std::process::Stdio; use tokio::process::Command; use tokio::sync::mpsc::channel; use tokio::sync::mpsc::Sender; use tokio::time::Instant; use usdt_tests_common::root_command; // Run bpftrace as a subprocess, waiting for the JSON output of the provided probe. async fn run_bpftrace_and_return_json(tx: &Sender<()>, probe_name: &str) -> Value { // Start the bpftrace subprocess, and attach to this process using its PID. let mut bpftrace = Command::new(root_command()) .arg("bpftrace") .arg("-e") // Note: bpftrace does not support multiple -e (program) // arguments, so both the test probe and the BEGIN probe are // given in the same program. // First the test probe we're interested in listening for. // After that, a "BEGIN" output printed by bpftrace when it // starts, to coordinate with the test thread firing the probe // itself. .arg(format!( "usdt:*:test_json:{} {{ printf(\"%s\\n\", str(arg0)); exit(); }}, BEGIN {{ printf(\"{}\\n\"); }}", probe_name, BEGIN_SENTINEL )) .arg("-p") .arg(std::process::id().to_string()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("Failed to spawn bpftrace subprocess"); // Wait for bpftrace to correctly start up before notifying the // test thread to start firing probes. let now = Instant::now(); wait_for_begin_sentinel(&mut bpftrace, &now).await; // Instruct the task firing probes to continue. tx.send(()).await.unwrap(); // Wait for the process to finish, up to a pretty generous limit. let output = tokio::time::timeout_at(now + MAX_WAIT, bpftrace.wait_with_output()) .await .expect(&format!("bpftrace did not complete within {:?}", MAX_WAIT)) .expect("Failed to wait for bpftrace subprocess"); assert!( output.status.success(), "bpftrace process failed:\n{:?}", String::from_utf8_lossy(&output.stderr), ); let stdout = std::str::from_utf8(&output.stdout).expect("Non-UTF8 stdout"); println!("bpftrace output\n{}\n", stdout); let json: Value = serde_json::from_str(&stdout).unwrap(); json } #[tokio::test] async fn test_json_support() { let (tx, rx) = channel(4); let test_task = tokio::task::spawn(fire_test_probes(rx)); let json = run_bpftrace_and_return_json(&tx, "good").await; assert!(json.get("ok").is_some()); assert!(json.get("err").is_none()); assert_eq!(json["ok"]["value"], Value::from(1)); assert_eq!(json["ok"]["buffer"], Value::from(vec![1, 2, 3])); // Tell the thread to continue with the bad probe let json = run_bpftrace_and_return_json(&tx, "bad").await; assert!(json.get("ok").is_none()); assert!(json.get("err").is_some()); assert_eq!(json["err"], Value::from(SERIALIZATION_ERROR)); test_task.await.unwrap(); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/does-it-work/build.rs
tests/does-it-work/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=test.d"); Builder::new("test.d").build().unwrap(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/does-it-work/src/main.rs
tests/does-it-work/src/main.rs
//! Small example which tests that this whole thing works. Specifically, this constructs and //! registers a single probe with arguments, and then verifies that this probe is visible to the //! `dtrace(1)` command-line tool. // Copyright 2024 Oxide Computer Company // // 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. #![allow(non_snake_case)] use usdt::register_probes; include!(concat!(env!("OUT_DIR"), "/test.rs")); fn main() { does__it::work!(|| (0, "something")); } // Dissuade the compiler from inlining this, which would ruin the test for `probefunc`. #[inline(never)] #[allow(dead_code)] fn run_test(rx: std::sync::mpsc::Receiver<()>) { register_probes().unwrap(); does__it::work!(|| (0, "something")); let _ = rx.recv(); } #[cfg(test)] mod tests { use super::run_test; #[cfg(not(target_os = "linux"))] mod dtrace { use super::run_test; use std::process::Stdio; use std::sync::mpsc::channel; use std::thread; #[test] fn test_does_it_work() { use usdt_tests_common::root_command; let (send, recv) = channel(); let thr = thread::spawn(move || run_test(recv)); let dtrace = std::process::Command::new(root_command()) .arg("dtrace") .arg("-l") .arg("-v") .arg("-n") .arg("does__it*:::") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("Could not start DTrace"); let output = dtrace .wait_with_output() .expect("Failed to read DTrace stdout"); // Kill the test thread let _ = send.send(()); // Collect the actual output let output = String::from_utf8_lossy(&output.stdout); println!("{}", output); // Check the line giving the full description of the probe let mut lines = output.lines().skip_while(|line| !line.contains("does__it")); let line = lines .next() .expect("Expected a line containing the provider name"); let mut parts = line.split_whitespace(); let _ = parts.next().expect("Expected an ID"); let provider = parts.next().expect("Expected a provider name"); assert!( provider.starts_with("does__it"), "Provider name appears incorrect: {}", provider ); let module = parts.next().expect("Expected a module name"); assert!( module.starts_with("does_it_work"), "Module name appears incorrect: {}", module ); let mangled_function = parts.next().expect("Expected a mangled function name"); assert!( mangled_function.contains("does_it_work8run_test"), "Mangled function name appears incorrect: {}", mangled_function ); // Verify the argument types let mut lines = lines.skip_while(|line| !line.contains("args[0]")); let first = lines .next() .expect("Expected a line with the argument description") .trim(); assert_eq!( first, "args[0]: uint8_t", "Argument is incorrect: {}", first ); let second = lines .next() .expect("Expected a line with the argument description") .trim(); assert_eq!( second, "args[1]: char *", "Argument is incorrect: {}", second ); thr.join().expect("Failed to join test runner thread"); } } #[cfg(target_os = "linux")] mod stap { use super::run_test; use std::process::Stdio; use std::sync::mpsc::channel; use std::thread; #[test] fn test_does_it_work() { // Note: other stap tests use bpftrace, but here we use readelf. // The reason for this is that while bpftrace can be used to read // out USDTs in processes, it does not print out their argument // types even with the verbose flag. // This is the readelf format we expect to see: // ``` // Displaying notes found in: .note.stapsdt // Owner Data size Description // stapsdt 0x00000034 NT_STAPSDT (SystemTap probe descriptors) // Provider: does__it // Name: work // Location: 0x00000000000618b4, Base: 0x00000000000332b4, Semaphore: 0x000000000011ccc8 // Arguments: 1@%dil 8@%rsi // ``` let (send, recv) = channel(); let thr = thread::spawn(move || run_test(recv)); let test_exe = std::env::current_exe().unwrap(); let readelf = std::process::Command::new("readelf") .arg("-n") .arg(&test_exe) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("Could not start readelf"); let output = readelf .wait_with_output() .expect("Failed to read readelf stdout"); // Kill the test thread let _ = send.send(()); // Collect the actual output let output = String::from_utf8_lossy(&output.stdout); println!("{}", output); // Skip lines until we find the first line of interest. let mut lines = output.lines().skip_while(|line| !line.contains("does__it")); // "Provider: does__it" let line = lines .next() .expect("Expected a line containing the provider name"); let line = line.trim(); assert_eq!( line, "Provider: does__it", "Provider name line appears incorrect: {}", line ); // "Name: work" let line = lines .next() .expect("Expected a line containing the probe name"); let line = line.trim(); assert_eq!( line, "Name: work", "Probe name line appears incorrect: {}", line ); // "Location: 0x00001234, Base: 0x0001234, Semaphore: 0x0001234" let line = lines.next().expect("Expected an addresses line"); let mut parts = line.trim().split_whitespace(); assert_eq!( parts.next().expect("Expected a 'Location:' text"), "Location:", "Addresses line appears incorrect: {}", line ); let location_address = parts.next().expect("Expected a location address"); assert!( location_address.starts_with("0x") && location_address.ends_with(",") && usize::from_str_radix(&location_address[2..location_address.len() - 1], 16) .is_ok_and(|addr| addr != 0), "Location address appears incorrect: {}", location_address ); assert_eq!( parts.next().expect("Expected a 'Base:' text"), "Base:", "Addresses line appears incorrect: {}", line ); let base_address = parts.next().expect("Expected a base address"); assert!( base_address.starts_with("0x") && base_address.ends_with(",") && usize::from_str_radix(&base_address[2..base_address.len() - 1], 16) .is_ok_and(|addr| addr != 0), "Base address appears incorrect: {}", base_address ); assert_eq!( parts.next().expect("Expected a 'Semaphore:' text"), "Semaphore:", "Addresses line appears incorrect: {}", line ); let semaphore_address = parts.next().expect("Expected a semaphore address"); assert!( semaphore_address.starts_with("0x") && usize::from_str_radix(&semaphore_address[2..], 16) .is_ok_and(|addr| addr != 0 && (addr % std::mem::align_of::<u16>()) == 0), "Semaphore address appears incorrect: {}", semaphore_address ); // Verify the argument types let line = lines.next().expect("Expected a line containing arguments"); let line = line.trim(); let arguments_line = if cfg!(target_arch = "x86_64") { "Arguments: 1@%dil 8@%rsi" } else if cfg!(target_arch = "aarch64") { "Arguments: 1@x0 8@x1" } else { unreachable!("Unsupported Linux target architecture") }; assert_eq!( line, arguments_line, "Arguments line appears incorrect: {}", line ); thr.join().expect("Failed to join test runner thread"); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/rename/src/main.rs
tests/rename/src/main.rs
//! Integration test verifying that provider modules are renamed correctly. // Copyright 2022 Oxide Computer Company // // 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. #[usdt::provider(provider = "something", probe_format = "probe_{probe}")] mod probes { fn something() {} } fn main() { usdt::register_probes().unwrap(); probes::probe_something!(|| ()); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/usize/src/main.rs
tests/usize/src/main.rs
//! Integration test verifying that we correctly compile usize/isize probes. // Copyright 2023 Oxide Computer Company // // 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. #[usdt::provider] mod usize__test { fn emit_usize(_: usize) {} fn emit_isize(_: &isize) {} fn emit_u8(_: u8) {} } fn main() { usdt::register_probes().unwrap(); usize__test::emit_usize!(|| 1usize); usize__test::emit_isize!(|| &1isize); usize__test::emit_u8!(|| 1); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/fake-lib/build.rs
tests/fake-lib/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=test.d"); Builder::new("test.d").build().unwrap(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/fake-lib/src/lib.rs
tests/fake-lib/src/lib.rs
// Copyright 2022 Oxide Computer Company // // 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. #![deny(warnings)] pub use usdt::register_probes; include!(concat!(env!("OUT_DIR"), "/test.rs")); pub fn dummy() { test::here__i__am!(); test::here__i__am!(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/lib.rs
tests/compile-errors/src/lib.rs
// Copyright 2022 Oxide Computer Company // // 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. #![deny(warnings)] // These tests are only valid when running on the Rust version specified // in rust-toolchain.toml #[cfg(test)] mod tests { #[test] fn test_compile_errors() { let t = trybuild::TestCases::new(); t.compile_fail("src/type-mismatch.rs"); t.compile_fail("src/unsupported-type.rs"); t.compile_fail("src/no-closure.rs"); t.compile_fail("src/no-provider-file.rs"); t.compile_fail("src/zero-arg-probe-type-check.rs"); t.compile_fail("src/different-serializable-type.rs"); t.compile_fail("src/relative-import.rs"); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/no-closure.rs
tests/compile-errors/src/no-closure.rs
// Copyright 2022 Oxide Computer Company // // 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. usdt::dtrace_provider!("../../../tests/compile-errors/providers/type-mismatch.d"); fn main() { let arg: u8 = 0; mismatch::bad!(arg); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/zero-arg-probe-type-check.rs
tests/compile-errors/src/zero-arg-probe-type-check.rs
//! Test that a zero-argument probe is correctly type-checked // Copyright 2022 Oxide Computer Company // // 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. #[usdt::provider] mod my_provider { fn my_probe() {} } fn main() { my_provider::my_probe!(|| "This should fail"); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/different-serializable-type.rs
tests/compile-errors/src/different-serializable-type.rs
//! Test that passing a type that is serializable, but not the same concrete type as the probe //! signature, fails compilation. // Copyright 2022 Oxide Computer Company // // 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. #[derive(serde::Serialize)] struct Expected { x: u8, } #[derive(serde::Serialize)] struct Different { x: u8, } #[usdt::provider] mod my_provider { use crate::Expected; fn my_probe(_: Expected) {} } fn main() { my_provider::my_probe!(|| Different { x: 0 }); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/relative-import.rs
tests/compile-errors/src/relative-import.rs
//! Test that we can't name types into the provider module using a relative import // Copyright 2021 Oxide Computer Company // // 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. #[derive(serde::Serialize)] struct Expected { x: u8, } #[usdt::provider] mod my_provider { use super::Expected; fn my_probe(_: Expected) {} } fn main() { my_provider::my_probe!(|| Different { x: 0 }); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/type-mismatch.rs
tests/compile-errors/src/type-mismatch.rs
// Copyright 2022 Oxide Computer Company // // 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. usdt::dtrace_provider!("../../../tests/compile-errors/providers/type-mismatch.d"); fn main() { let bad: f32 = 0.0; mismatch::bad!(|| (bad)); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/no-provider-file.rs
tests/compile-errors/src/no-provider-file.rs
// Copyright 2022 Oxide Computer Company // // 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. usdt::dtrace_provider!("non-existent.d"); fn main() {}
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/compile-errors/src/unsupported-type.rs
tests/compile-errors/src/unsupported-type.rs
// Copyright 2022 Oxide Computer Company // // 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. usdt::dtrace_provider!("../../../tests/compile-errors/providers/unsupported-type.d"); fn main() { let bad: u8 = 0; unsupported::bad!(|| (bad)); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/test-unique-id/src/main.rs
tests/test-unique-id/src/main.rs
//! Integration test for `usdt::UniqueId` // Copyright 2022 Oxide Computer Company // // 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. #[usdt::provider] mod with_ids { use usdt::UniqueId; fn start_work(_: &UniqueId) {} fn waypoint_from_thread(_: &UniqueId, message: &str) {} fn work_finished(_: &UniqueId, result: u64) {} } fn main() {} #[cfg(test)] mod tests { use super::with_ids; #[cfg(not(target_os = "linux"))] mod dtrace { use super::with_ids; use std::thread; use std::time::Duration; use subprocess::Exec; use usdt::UniqueId; #[test] fn test_unique_ids() { usdt::register_probes().unwrap(); let id = UniqueId::new(); with_ids::start_work!(|| &id); let id2 = id.clone(); let thr = thread::spawn(move || { for _ in 0..10 { with_ids::waypoint_from_thread!(|| (&id2, "we're in a thread")); thread::sleep(Duration::from_millis(10)); } id2.as_u64() }); let result = thr.join().unwrap(); with_ids::work_finished!(|| (&id, result)); assert_eq!(result, id.as_u64()); // Actually verify that the same value is received by DTrace. let sudo = if cfg!(target_os = "illumos") { "pfexec" } else { "sudo" }; let mut dtrace = Exec::cmd(sudo) .arg("/usr/sbin/dtrace") .arg("-q") .arg("-n") .arg(r#"with_ids*:::waypoint_from_thread { printf("%u\n", arg0); exit(0); }"#) .stdin(subprocess::NullFile) .stderr(subprocess::Redirection::Pipe) .stdout(subprocess::Redirection::Pipe) .popen() .expect("Failed to run DTrace"); thread::sleep(Duration::from_millis(1000)); let id = UniqueId::new(); let id2 = id.clone(); let thr = thread::spawn(move || { with_ids::waypoint_from_thread!(|| (&id2, "we're in a thread")); }); thr.join().unwrap(); const TIMEOUT: Duration = Duration::from_secs(10); let mut comm = dtrace.communicate_start(None).limit_time(TIMEOUT); if dtrace .wait_timeout(TIMEOUT) .expect("DTrace command failed") .is_none() { std::process::Command::new(sudo) .arg("kill") .arg(format!("{}", dtrace.pid().unwrap())) .spawn() .expect("Failed to spawn kill") .wait() .expect("Failed to kill DTrace subprocess"); panic!("DTrace didn't exit within timeout of {:?}", TIMEOUT); } let (stdout, stderr) = comm.read_string().expect("Failed to read DTrace output"); let stdout = stdout.unwrap_or_else(|| String::from("<EMPTY>")); let stderr = stderr.unwrap_or_else(|| String::from("<EMPTY>")); let actual_id: u64 = stdout.trim().parse().unwrap_or_else(|_| { panic!( concat!( "Expected a u64\n", "stdout\n", "------\n", "{}\n", "stderr\n", "------\n", "{}" ), stdout, stderr ) }); assert_eq!(actual_id, id.as_u64()); } } #[cfg(target_os = "linux")] mod stap { use super::with_ids; use std::thread; use std::time::Duration; use subprocess::Exec; use usdt::UniqueId; use usdt_tests_common::root_command; #[test] fn test_unique_ids() { usdt::register_probes().unwrap(); let id = UniqueId::new(); with_ids::start_work!(|| &id); let id2 = id.clone(); let thr = thread::spawn(move || { for _ in 0..10 { with_ids::waypoint_from_thread!(|| (&id2, "we're in a thread")); thread::sleep(Duration::from_millis(10)); } id2.as_u64() }); let result = thr.join().unwrap(); with_ids::work_finished!(|| (&id, result)); assert_eq!(result, id.as_u64()); // Actually verify that the same value is received by bpftrace. let mut bpftrace = Exec::cmd(root_command()) .arg("bpftrace") .arg("-q") .arg("-e") .arg(r#"usdt:*:with_ids:waypoint_from_thread { printf("%lu\n", arg0); exit(); }"#) .arg("-p") .arg(std::process::id().to_string()) .stderr(subprocess::Redirection::Pipe) .stdout(subprocess::Redirection::Pipe) .popen() .expect("Failed to run bpftrace"); thread::sleep(Duration::from_millis(1000)); let id = UniqueId::new(); let id2 = id.clone(); let thr = thread::spawn(move || { with_ids::waypoint_from_thread!(|| (&id2, "we're in a thread")); }); thr.join().unwrap(); const TIMEOUT: Duration = Duration::from_secs(10); let mut comm = bpftrace.communicate_start(None).limit_time(TIMEOUT); if bpftrace .wait_timeout(TIMEOUT) .expect("bpftrace command failed") .is_none() { std::process::Command::new(root_command()) .arg("kill") .arg(format!("{}", bpftrace.pid().unwrap())) .spawn() .expect("Failed to spawn kill") .wait() .expect("Failed to kill bpftrace subprocess"); panic!("bpftrace didn't exit within timeout of {:?}", TIMEOUT); } let (stdout, stderr) = comm.read_string().expect("Failed to read bpftrace output"); let stdout = stdout.unwrap_or_else(|| String::from("<EMPTY>")); let stderr = stderr.unwrap_or_else(|| String::from("<EMPTY>")); eprintln!("stdout: {}", stdout.trim()); eprintln!("stderr: {}", stderr.trim()); let actual_id: u64 = stdout.trim().parse().unwrap_or_else(|_| { panic!( concat!( "Expected a u64\n", "stdout\n", "------\n", "{}\n", "stderr\n", "------\n", "{}" ), stdout, stderr ) }); assert_eq!(actual_id, id.as_u64()); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/argument-types/src/main.rs
tests/argument-types/src/main.rs
//! An example and compile-test showing the various ways in which probe arguments may be specified, //! both in the parameter list and when passing values in the probe argument closure. // Copyright 2022 Oxide Computer Company // // 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. use serde::Serialize; /// Most struct or tuple types implementing serde::Serialize may be used in probes. #[derive(Default, Clone, Serialize)] struct Arg { x: Vec<i32>, } /// Types with references are not supported. #[derive(Serialize)] #[allow(dead_code)] struct NotSupported<'a> { x: &'a [i32], } #[usdt::provider] mod refs { /// Simple types such as integers may be taken by value ... fn u8_as_value(_: u8) {} /// ... or by reference fn u8_as_reference(_: &u8) {} /// Same with strings fn string_as_value(_: String) {} fn string_as_reference(_: &String) {} /// Slices are supported fn slice(_: &[u8]) {} /// As are arrays. fn array(_: [u8; 4]) {} /// And tuples. fn tuple(_: (u8, &[u8])) {} /// Tuples cannot be passed by reference, so this won't work. This would require naming the /// lifetime of the inner shared slice, which isn't currently supported. // fn tuple_by_reference(_: &(u8, &[u8])) {} /// Serializable types may also be taken by value or reference. fn serializable_as_value(_: crate::Arg) {} fn serializable_as_reference(_: &crate::Arg) {} } fn main() { usdt::register_probes().unwrap(); // Probe macros internally take a _reference_ to the data whenever possible. This means probes // that accept a type by value... refs::u8_as_value!(|| 0); // ... may also take that type by reference. refs::u8_as_value!(|| &0); // And vice-versa: a probe accepting a parameter by reference may take it by value as well. refs::u8_as_reference!(|| 0); refs::u8_as_reference!(|| &0); // This is true for string types as well. Probes accepting a string type may be called with // anything that implements `AsRef<str>`, which includes `&str`, owned `String`s, and // `&String` as well. refs::string_as_value!(|| "&'static str"); refs::string_as_value!(|| String::from("owned")); refs::string_as_reference!(|| "&'static str"); refs::string_as_reference!(|| String::from("owned")); // Vectors are supported as well. In this case, the probe argument behaves the way it might in // a "normal" function -- with a signature like `fn foo(_: Vec<T>)`, one can pass a `Vec<T>`. // (In this case a reference would also work, i.e., `&Vec<T>`.) However, with a _slice_ as the // argument, `fn foo(_: &[T])`, one may pass anything that implements `AsRef<[T]>`, which // includes slices and `Vec<T>`. let x = vec![0, 1, 2]; // Call with an actual slice ... refs::slice!(|| &x[..]); // .. Or the vector itself, just like any function `fn(&[T])`. refs::slice!(|| &x); // Arrays may also be passed to something expecting a slice. let arr: [u8; 4] = [0, 1, 2, 3]; refs::slice!(|| &arr[..2]); refs::array!(|| arr); refs::array!(|| &arr); // Tuples may be passed in by value. refs::tuple!(|| (0, &x[..])); // Serializable types may be passed by value or reference, to a probe expecting either a value // or a reference. Note, however, that the normal lifetime rules apply: you can't return a // reference from an argument closure to data constructed _inside_ the closure. I.e., this will // _not_ work: // // ``` // refs::serializable_as_reference!(|| &crate::Arg::default()); // ``` let arg = crate::Arg::default(); refs::serializable_as_value!(crate::Arg::default); refs::serializable_as_value!(|| &arg); refs::serializable_as_reference!(crate::Arg::default); refs::serializable_as_reference!(|| &arg); // It's also possible to capture and return local variables by value in the probe argument // closure. This behaves just like any other captured variable, and so `arg` cannot be used // again, unless it implements Copy. refs::serializable_as_reference!(|| arg); // This line will fail to compile, indicating that `arg` is borrowed after it's been moved. // println!("{:#?}", arg.x); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/modules/src/inner.rs
tests/modules/src/inner.rs
// Copyright 2021 Oxide Computer Company // // 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. #[usdt::provider(provider = "modules")] pub mod probes { fn am_i_visible() {} }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/modules/src/main.rs
tests/modules/src/main.rs
// Copyright 2022 Oxide Computer Company // // 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. mod inner; fn main() { usdt::register_probes().expect("Could not register probes"); // Verify that we can call the probe from its full path. inner::probes::am_i_visible!(|| ()); // This is an overly-cautious test for macOS. We define extern symbols inside each expanded // probe macro, with a link-name for a symbol that the macOS linker will generate for us. This // checks that there is no issue defining these locally-scoped extern symbols multiple times. inner::probes::am_i_visible!(|| ()); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/zero-arg-probe/build.rs
tests/zero-arg-probe/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=test.d"); Builder::new("test.d").build().unwrap(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/zero-arg-probe/src/main.rs
tests/zero-arg-probe/src/main.rs
// Copyright 2022 Oxide Computer Company // // 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. #![deny(warnings)] use usdt::register_probes; include!(concat!(env!("OUT_DIR"), "/test.rs")); fn main() { register_probes().unwrap(); zero::here__i__am!(|| ()); zero::here__i__am!(); } #[cfg(test)] mod test { // We just want to make sure that main builds and runs. #[test] fn test_main() { super::main(); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/fake-cmd/src/main.rs
tests/fake-cmd/src/main.rs
// Copyright 2022 Oxide Computer Company // // 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. #![deny(warnings)] fn main() { fake_lib::register_probes().unwrap(); fake_lib::dummy(); } #[cfg(test)] mod test { // We just want to make sure that main builds and runs. #[test] fn test_main() { super::main(); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/rename-builder/build.rs
tests/rename-builder/build.rs
// Copyright 2022 Oxide Computer Company // // 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. use usdt::Builder; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=test.d"); Builder::new("test.d").module("still_test").build().unwrap(); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/tests/rename-builder/src/main.rs
tests/rename-builder/src/main.rs
//! Test verifying that renaming the provider/probes in various ways works when using a build //! script. // Copyright 2022 Oxide Computer Company // // 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. include!(concat!(env!("OUT_DIR"), "/test.rs")); fn main() { usdt::register_probes().unwrap(); // Renamed the module that the probes are generated to `still_test`. So naming them as // `test::start_work` will fail. still_test::start_work!(|| 0); }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/build.rs
usdt-impl/build.rs
// Copyright 2022 Oxide Computer Company // // 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. // use std::env; #[derive(Copy, Clone)] enum Backend { // Standard (read: illumos) probe registration Standard, // MacOS linker-aware probe registration Linker, // SystemTap version 3 probes (read: Linux without dtrace) Stap3, // Provide probe macros, but probes are no-ops (dtrace-less OSes) NoOp, } fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rustc-check-cfg=cfg(usdt_backend_noop)"); println!("cargo:rustc-check-cfg=cfg(usdt_backend_stapsdt)"); println!("cargo:rustc-check-cfg=cfg(usdt_backend_linker)"); println!("cargo:rustc-check-cfg=cfg(usdt_backend_standard)"); let backend = match env::var("CARGO_CFG_TARGET_OS").ok().as_deref() { Some("macos") => Backend::Linker, Some("illumos") | Some("solaris") | Some("freebsd") => Backend::Standard, Some("linux") => Backend::Stap3, _ => Backend::NoOp, }; match backend { Backend::NoOp => { println!("cargo:rustc-cfg=usdt_backend_noop"); } Backend::Stap3 => { println!("cargo:rustc-cfg=usdt_backend_stapsdt"); } Backend::Linker => { println!("cargo:rustc-cfg=usdt_backend_linker"); } Backend::Standard => { println!("cargo:rustc-cfg=usdt_backend_standard"); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/lib.rs
usdt-impl/src/lib.rs
//! Main implementation crate for the USDT package. // Copyright 2022 Oxide Computer Company // // 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. use serde::Deserialize; use std::cell::RefCell; use thiserror::Error; // Probe record parsing required for standard backend (and `des` feature used by `dusty util) #[cfg(any(usdt_backend_standard, usdt_backend_stapsdt, feature = "des"))] pub mod record; #[cfg_attr(usdt_backend_noop, path = "empty.rs")] #[cfg_attr(usdt_backend_linker, path = "linker.rs")] #[cfg_attr(usdt_backend_standard, path = "no-linker.rs")] #[cfg_attr(usdt_backend_stapsdt, path = "stapsdt.rs")] mod internal; // Since the `empty` is mostly a no-op, parts of the common code will go unused when it is // selected for use. #[cfg_attr(usdt_backend_noop, allow(dead_code))] mod common; /// Register an application's probe points with DTrace. /// /// This function collects information about the probe points defined in an application and ensures /// that they are registered with the DTrace kernel module. It is critical to note that if this /// method is not called (at some point in an application), _no probes will be visible_ via the /// `dtrace(1)` command line tool. /// /// NOTE: This method presents a quandary for library developers, as consumers of their library may /// forget to (or choose not to) call this function. There are potential workarounds for this /// problem, but each comes with significant tradeoffs. Library developers are encouraged to /// re-export this function and document to their users that this function should be called to /// guarantee that the library's probes are registered. pub fn register_probes() -> Result<(), Error> { crate::internal::register_probes() } /// Errors related to building DTrace probes into Rust code #[derive(Error, Debug)] pub enum Error { /// Error during parsing of DTrace provider source #[error(transparent)] ParseError(#[from] dtrace_parser::DTraceError), /// Error reading or writing files, or registering DTrace probes #[error(transparent)] IO(#[from] std::io::Error), /// Error related to environment variables, e.g., while running a build script #[error(transparent)] Env(#[from] std::env::VarError), /// An error occurred extracting probe information from the encoded object file sections #[error("The file is not a valid object file")] InvalidFile, /// Error related to calling out to DTrace itself #[error("Failed to call DTrace subprocess")] DTraceError, /// Error converting input to JSON #[error(transparent)] Json(#[from] serde_json::Error), } #[derive(Default, Debug, Deserialize)] pub struct CompileProvidersConfig { pub provider: Option<String>, pub probe_format: Option<String>, pub module: Option<String>, } impl CompileProvidersConfig { /// Return the formatted name of a probe. pub fn format_probe(&self, probe_name: &str) -> String { if let Some(fmt) = &self.probe_format { fmt.replace( "{provider}", self.provider .as_ref() .expect("Expected a provider name when formatting a rpobe"), ) .replace("{probe}", probe_name) } else { String::from(probe_name) } } /// Return the formatted name of the probe as an identifier. pub fn probe_ident(&self, probe_name: &str) -> proc_macro2::Ident { quote::format_ident!("{}", self.format_probe(probe_name)) } /// Return the formatted module name as an identifier. pub fn module_ident(&self) -> proc_macro2::Ident { let name = self.module.as_ref().unwrap_or_else(|| { self.provider .as_ref() .expect("Expected a provider name when making a module ident") }); quote::format_ident!("{}", name) } } // Compile DTrace provider source code into Rust. // // This function parses a provider definition, and, for each probe, a corresponding Rust macro is // returned. This macro may be called throughout Rust code to fire the corresponding DTrace probe // (if it's enabled). See [probe_test_macro] for a detailed example. // // [probe_test_macro]: https://github.com/oxidecomputer/usdt/tree/master/probe-test-macro pub fn compile_provider_source( source: &str, config: &CompileProvidersConfig, ) -> Result<proc_macro2::TokenStream, Error> { crate::internal::compile_provider_source(source, config) } // Compile a DTrace provider from its representation in the USDT crate. pub fn compile_provider( provider: &Provider, config: &CompileProvidersConfig, ) -> proc_macro2::TokenStream { crate::internal::compile_provider_from_definition(provider, config) } /// A data type supported by the `usdt` crate. #[derive(Debug, Clone, PartialEq)] pub enum DataType { Native(dtrace_parser::DataType), UniqueId, Serializable(syn::Type), } impl DataType { /// Convert a data type to its C type representation as a string. pub fn to_c_type(&self) -> String { match self { DataType::Native(ty) => ty.to_c_type(), DataType::UniqueId => String::from("uint64_t"), DataType::Serializable(_) => String::from("char*"), } } /// Return the Rust FFI type representation of this data type. pub fn to_rust_ffi_type(&self) -> syn::Type { match self { DataType::Native(ty) => syn::parse_str(&ty.to_rust_ffi_type()).unwrap(), DataType::UniqueId => syn::parse_str("::std::os::raw::c_ulonglong").unwrap(), DataType::Serializable(_) => syn::parse_str("*const ::std::os::raw::c_char").unwrap(), } } /// Return the native Rust type representation of this data type. pub fn to_rust_type(&self) -> syn::Type { match self { DataType::Native(ty) => syn::parse_str(&ty.to_rust_type()).unwrap(), DataType::UniqueId => syn::parse_str("::usdt::UniqueId").unwrap(), DataType::Serializable(ref inner) => inner.clone(), } } } impl From<dtrace_parser::DataType> for DataType { fn from(ty: dtrace_parser::DataType) -> Self { DataType::Native(ty) } } impl From<&syn::Type> for DataType { fn from(t: &syn::Type) -> Self { DataType::Serializable(t.clone()) } } /// A single DTrace probe function #[derive(Debug, Clone)] pub struct Probe { pub name: String, pub types: Vec<DataType>, } impl From<dtrace_parser::Probe> for Probe { fn from(p: dtrace_parser::Probe) -> Self { Self { name: p.name, types: p.types.into_iter().map(DataType::from).collect(), } } } impl Probe { /// Return the representation of this probe in D source code. pub fn to_d_source(&self) -> String { let types = self .types .iter() .map(|typ| typ.to_c_type()) .collect::<Vec<_>>() .join(", "); format!("probe {name}({types});", name = self.name, types = types) } } /// The `Provider` represents a single DTrace provider, with a collection of probes. #[derive(Debug, Clone)] pub struct Provider { pub name: String, pub probes: Vec<Probe>, pub use_statements: Vec<syn::ItemUse>, } impl Provider { /// Return the representation of this provider in D source code. pub fn to_d_source(&self) -> String { let probes = self .probes .iter() .map(|probe| format!("\t{}", probe.to_d_source())) .collect::<Vec<_>>() .join("\n"); format!( "provider {provider_name} {{\n{probes}\n}};", provider_name = self.name, probes = probes ) } } impl From<dtrace_parser::Provider> for Provider { fn from(p: dtrace_parser::Provider) -> Self { Self { name: p.name, probes: p.probes.into_iter().map(Probe::from).collect(), use_statements: vec![], } } } impl From<&dtrace_parser::Provider> for Provider { fn from(p: &dtrace_parser::Provider) -> Self { Self::from(p.clone()) } } /// Convert a serializable type into a JSON string, if possible. /// /// NOTE: This is essentially a re-export of the `serde_json::to_string` function, used to avoid /// foisting an explicity dependency on that crate in user's `Cargo.toml`. pub fn to_json<T>(x: &T) -> Result<String, Error> where T: ?Sized + ::serde::Serialize, { ::serde_json::to_string(x).map_err(Error::from) } thread_local! { static CURRENT_ID: RefCell<u32> = const { RefCell::new(0) }; static THREAD_ID: RefCell<usize> = RefCell::new(thread_id::get()); } /// A unique identifier that can be used to correlate multiple USDT probes together. /// /// It's a common pattern in DTrace scripts to correlate multiple probes. For example, one can time /// system calls by storing a timestamp on the `syscall:::entry` probe and then computing the /// elapsed time in the `syscall:::return` probe. This requires some way to "match up" these two /// probes, to ensure that the elapsed time is correctly attributed to a single system call. Doing /// so requires an identifier. User code may already have an ID appropriate for this use case, but /// the `UniqueId` type may be used when one is not already available. These unique IDs can be used /// to correlate multiple probes occurring in a section or span of user code. /// /// A probe function may accept a `UniqueId`, which appears in a D as a `u64`. The value is /// guaranteed to be unique, even if multiple threads run the same traced section of code. (See the /// [notes] for caveats.) The value may be shared between threads by calling `clone()` on a /// constructed span -- in this case, the cloned object shares the same value, so that a traced /// span running in multiple threads (or asynchronous tasks) shares the same identifier. /// /// A `UniqueId` is very cheap to construct. The internal value is "materialized" in two /// situations: /// /// - When an _enabled_ probe fires /// - When the value is cloned (e.g., for sharing with another thread) /// /// This minimizes the disabled-probe effect, but still allows sharing a consistent ID in the case /// of multithreaded work. /// /// Example /// ------- /// ```ignore /// #[usdt::provider] /// mod with_id { /// fn work_started(_: &usdt::UniqueId) {} /// fn halfway_there(_: &usdt::UniqueId, msg: &str) {} /// fn work_completed(_: &usdt::UniqueId, result: u64) {} /// } /// /// // Constructing an ID is very cheap. /// let id = usdt::UniqueId::new(); /// /// // The ID will only be materialized if this probe is enabled. /// with_id_work_started!(|| &id); /// /// // If the ID has been materialized above, this simply clone the internal value. If the ID has /// // _not_ yet been materialized, say because the `work_started` probe was not enabled, this will /// // do so now. /// let id2 = id.clone(); /// let handle = std::thread::spawn(move || { /// for i in 0..10 { /// // Do our work. /// if i == 5 { /// with_id_halfway_there!(|| (&id2, "work is half completed")); /// } /// } /// 10 /// }); /// /// let result = handle.join().unwrap(); /// with_id_work_completed!(|| (&id, result)); /// ``` /// /// Note that this type is not `Sync`, which means we cannot accidentally share the value between /// threads. The only way to track the same ID in work spanning threads is to first clone the type, /// which materializes the internal value. For example, this will fail to compile: /// /// ```compile_fail /// #[usdt::provider] /// mod with_id { /// fn work_started(_: &usdt::UniqueId) {} /// fn halfway_there(_: &usdt::UniqueId, msg: &str) {} /// fn work_completed(_: &usdt::UniqueId, result: u64) {} /// } /// /// let id = usdt::UniqueId::new(); /// with_id_work_started!(|| &id); /// let handle = std::thread::spawn(move || { /// for i in 0..10 { /// // Do our work. /// if i == 5 { /// // Note that we're using `id`, not a clone as the previous example. /// with_id_halfway_there!(|| (&id, "work is half completed")); /// } /// } /// 10 /// }); /// let result = handle.join().unwrap(); /// with_id_work_completed!(|| (&id, result)); /// ``` /// /// Notes /// ----- /// /// In any practical situation, the generated ID is unique. Its value is assigned on the basis of /// the thread that creates the `UniqueId` object, plus a monotonic thread-local counter. However, /// the counter is 32 bits, and so wraps around after about 4 billion unique values. So /// theoretically, multiple `UniqueId`s could manifest as the same value to DTrace, if they are /// exceptionally long-lived or generated very often. #[derive(Debug)] pub struct UniqueId { id: RefCell<Option<u64>>, } impl UniqueId { /// Construct a new identifier. /// /// A `UniqueId` is cheap to create, and is not materialized into an actual value until it's /// needed, either by a probe function or during `clone`ing to share the value between threads. pub const fn new() -> Self { Self { id: RefCell::new(None), } } // Helper function to actually materialize a u64 value internally. // // This method assigns a value on the basis of the current thread and a monotonic counter, in // the upper and lower 32-bits of a u64, respectively. fn materialize(&self) { // Safety: This type is not Sync, which means the current thread maintains the only // reference to the contained ID. A `UniqueId` in another thread is a clone, at which // point the value has been materialized as well. The `id` field of that object is a // different `RefCell` -- that type is here just to enable interior mutability. let mut inner = self.id.borrow_mut(); if inner.is_none() { let id = CURRENT_ID.with(|id| { let thread_id = THREAD_ID.with(|id| *id.borrow_mut() as u64); let mut inner = id.borrow_mut(); *inner = inner.wrapping_add(1); (thread_id << 32) | (*inner as u64) }); inner.replace(id); } } /// Return the internal `u64` value, materializing it if needed. #[doc(hidden)] pub fn as_u64(&self) -> u64 { self.materialize(); // Safety: This is an immutable borrow, so is safe from multiple threads. The cell cannot // be borrowed mutably at the same time, as that only occurs within the scope of the // `materialize` method. This method can't be called on the _same_ `UniqueId` from multiple // threads, because the type is not `Sync`. self.id.borrow().unwrap() } } impl Clone for UniqueId { fn clone(&self) -> Self { self.materialize(); Self { id: self.id.clone(), } } } #[cfg(test)] mod test { use super::*; use dtrace_parser::BitWidth; use dtrace_parser::DataType as DType; use dtrace_parser::Integer; use dtrace_parser::Sign; #[test] fn test_probe_to_d_source() { let probe = Probe { name: String::from("my_probe"), types: vec![DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, }))], }; assert_eq!(probe.to_d_source(), "probe my_probe(uint8_t*);"); } #[test] fn test_provider_to_d_source() { let probe = Probe { name: String::from("my_probe"), types: vec![DataType::Native(DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, }))], }; let provider = Provider { name: String::from("my_provider"), probes: vec![probe], use_statements: vec![], }; assert_eq!( provider.to_d_source(), "provider my_provider {\n\tprobe my_probe(uint8_t);\n};" ); } #[test] fn test_data_type() { let ty = DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })); assert_eq!(ty.to_rust_type(), syn::parse_str("*const u8").unwrap()); let ty = DataType::Native(dtrace_parser::DataType::String); assert_eq!(ty.to_rust_type(), syn::parse_str("&str").unwrap()); let ty = DataType::UniqueId; assert_eq!( ty.to_rust_type(), syn::parse_str("::usdt::UniqueId").unwrap() ); } #[test] fn test_unique_id() { let id = UniqueId::new(); assert!(id.id.borrow().is_none()); let x = id.as_u64(); assert_eq!(x & 0xFFFF_FFFF, 1); assert_eq!(id.id.borrow().unwrap(), x); } #[test] fn test_unique_id_clone() { let id = UniqueId::new(); let id2 = id.clone(); assert!(id.id.borrow().is_some()); assert!(id2.id.borrow().is_some()); assert_eq!(id.id.borrow().unwrap(), id2.id.borrow().unwrap()); // Verify that the actual RefCells inside the type point to different locations. This is // important to check that sending a clone to a different thread will operate on a // different cell, so that they can both borrow the value (either mutably or immutably) // without panics. assert_ne!(&(id.id) as *const _, &(id2.id) as *const _); assert_ne!(id.id.as_ptr(), id2.id.as_ptr()); } #[test] fn test_compile_providers_config() { let config = CompileProvidersConfig { provider: Some(String::from("prov")), probe_format: Some(String::from("probe_{probe}")), module: Some(String::from("not_prov")), }; assert_eq!(config.format_probe("prob"), "probe_prob"); let module = config.module_ident(); assert_eq!( quote::quote! { #module }.to_string(), quote::quote! { not_prov }.to_string(), ); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/empty.rs
usdt-impl/src/empty.rs
//! The empty implementation of the USDT crate. //! //! Used on platforms without DTrace. // Copyright 2024 Oxide Computer Company // // 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. use crate::common; use crate::{Probe, Provider}; use proc_macro2::TokenStream; use quote::quote; use std::convert::TryFrom; pub fn compile_provider_source( source: &str, config: &crate::CompileProvidersConfig, ) -> Result<TokenStream, crate::Error> { let dfile = dtrace_parser::File::try_from(source)?; let providers = dfile .providers() .into_iter() .map(|provider| { let provider = Provider::from(provider); // Ensure that the name of the module in the config is set, either by the caller or // defaulting to the provider name. let config = crate::CompileProvidersConfig { provider: Some(provider.name.clone()), probe_format: config.probe_format.clone(), module: match &config.module { None => Some(provider.name.clone()), other => other.clone(), }, }; compile_provider(&provider, &config) }) .collect::<Vec<_>>(); Ok(quote! { #(#providers)* }) } pub fn compile_provider_from_definition( provider: &Provider, config: &crate::CompileProvidersConfig, ) -> TokenStream { compile_provider(provider, config) } fn compile_provider(provider: &Provider, config: &crate::CompileProvidersConfig) -> TokenStream { let probe_impls = provider .probes .iter() .map(|probe| compile_probe(provider, probe, config)) .collect::<Vec<_>>(); let module = config.module_ident(); quote! { pub(crate) mod #module { #(#probe_impls)* } } } fn compile_probe( provider: &Provider, probe: &Probe, config: &crate::CompileProvidersConfig, ) -> TokenStream { // We don't need to add any actual probe emission code, but we do still want // to perform type-checking of its arguments here. let args = common::call_argument_closure(&probe.types); let type_check_fn = common::construct_type_check( &provider.name, &probe.name, &provider.use_statements, &probe.types, ); let impl_block = quote! { #args #type_check_fn }; common::build_probe_macro(config, &probe.name, &probe.types, impl_block) } pub fn register_probes() -> Result<(), crate::Error> { Ok(()) }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/record.rs
usdt-impl/src/record.rs
//! Implementation of construction and extraction of custom linker section records used to store //! probe information in an object file. // Copyright 2024 Oxide Computer Company // // 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. use crate::DataType; use byteorder::{NativeEndian, ReadBytesExt}; use dof::{Probe, Provider, Section}; use std::collections::BTreeMap; use std::mem::size_of; use std::sync::atomic::AtomicU8; use std::sync::atomic::Ordering; // Version number for probe records containing data about all probes. // // NOTE: This must have a maximum of `u8::MAX - 1`. See `read_record_version` for // details. pub(crate) const PROBE_REC_VERSION: u8 = 1; /// Extract records for all defined probes from our custom linker sections. pub fn process_section(mut data: &mut [u8], register: bool) -> Result<Section, crate::Error> { let mut providers = BTreeMap::new(); while !data.is_empty() { assert!( data.len() >= size_of::<u32>(), "Not enough bytes for length header" ); // Read the length without consuming it let len = (&data[..size_of::<u32>()]).read_u32::<NativeEndian>()? as usize; let (rec, rest) = data.split_at_mut(len); process_probe_record(&mut providers, rec, register)?; data = rest; } Ok(Section { providers, ..Default::default() }) } #[cfg(all(unix, not(target_os = "freebsd")))] /// Convert an address in an object file into a function and file name, if possible. pub(crate) fn addr_to_info(addr: u64) -> (Option<String>, Option<String>) { unsafe { let mut info = libc::Dl_info { dli_fname: std::ptr::null(), dli_fbase: std::ptr::null_mut(), dli_sname: std::ptr::null(), dli_saddr: std::ptr::null_mut(), }; if libc::dladdr(addr as *const libc::c_void, &mut info as *mut _) == 0 { (None, None) } else { ( Some( std::ffi::CStr::from_ptr(info.dli_sname) .to_string_lossy() .to_string(), ), Some( std::ffi::CStr::from_ptr(info.dli_fname) .to_string_lossy() .to_string(), ), ) } } } // On FreeBSD, dladdr(3M) only examines the dynamic symbol table. Which is pretty useless as it // will always return a dli_sname. To workaround this issue, we use `backtrace_symbols_fmt` from // libexecinfo, which internally looks in the executable to determine the symbol of the given // address. // See: https://man.freebsd.org/cgi/man.cgi?query=backtrace&sektion=3 #[cfg(target_os = "freebsd")] pub(crate) fn addr_to_info(addr: u64) -> (Option<String>, Option<String>) { unsafe { #[link(name = "execinfo")] extern "C" { pub fn backtrace_symbols_fmt( _: *const *mut libc::c_void, _: libc::size_t, _: *const libc::c_char, ) -> *mut *mut libc::c_char; } let addrs_arr = [addr]; let addrs = addrs_arr.as_ptr() as *const *mut libc::c_void; let format = std::ffi::CString::new("%n\n%f").unwrap(); let symbols = backtrace_symbols_fmt(addrs, 1, format.as_ptr()); if !symbols.is_null() { if let Some((sname, fname)) = std::ffi::CStr::from_ptr(*symbols) .to_string_lossy() .split_once('\n') { (Some(sname.to_string()), Some(fname.to_string())) } else { (None, None) } } else { (None, None) } } } #[cfg(not(unix))] /// Convert an address in an object file into a function and file name, if possible. pub(crate) fn addr_to_info(_addr: u64) -> (Option<String>, Option<String>) { (None, None) } // Limit a string to the DTrace-imposed maxima. Note that this ensures a null-terminated C string // result, i.e., the actual string is of length `limit - 1`. // See dtrace.h, // // DTrace appends the PID to the provider name. The exact size is platform dependent, but use the // largest known value of 999,999 on illumos. MacOS and the BSDs are 32-99K. We take the log to get // the number of digits. const MAX_PROVIDER_NAME_LEN: usize = 64 - 6; const MAX_PROBE_NAME_LEN: usize = 64; const MAX_FUNC_NAME_LEN: usize = 128; const MAX_ARG_TYPE_LEN: usize = 128; fn limit_string_length<S: AsRef<str>>(s: S, limit: usize) -> String { let s = s.as_ref(); let limit = s.len().min(limit - 1); s[..limit].to_string() } // Return the probe record version, atomically updating it if the probe record will be handled. fn read_record_version(version: &mut u8, register: bool) -> u8 { // First check if (1) we need to do anything other than read the version and // (2) if this is a version number this compiled crate could feasibly // handle. let ver = *version; if !register || ver > PROBE_REC_VERSION { return ver; } // At this point we know we need to potentially update the version, and that // we also have code that can handle it. We'll exchange it with the sentinel // unconditionally. // // If we get back the sentinel, another thread beat us to the punch. If we // get back anything else, it is a version we are capable of handling. // // TODO-safety: We'd love to use `AtomicU8::from_mut`, but that remains a // nightly-only feature. In the meantime, this is safe because we have a // mutable reference to the data in this method, and atomic types are // guaranteed to have the same layout as their inner type. let ver = unsafe { std::mem::transmute::<&mut u8, &AtomicU8>(version) }; ver.swap(u8::MAX, Ordering::SeqCst) } // Process a single record from the custom linker section. fn process_probe_record( providers: &mut BTreeMap<String, Provider>, rec: &mut [u8], register: bool, ) -> Result<(), crate::Error> { // First four bytes are the length, next byte is the version number. let (rec, mut data) = { // We need `rec` to be mutable and have type `&mut [u8]`, and `data` to // be mutable, but have type `&[u8]`. Use `split_at_mut` to get two // `&mut [u8]` and then convert the latter to a shared reference. let (rec, data) = rec.split_at_mut(5); (rec, &*data) }; let version = read_record_version(&mut rec[4], register); // If this record comes from a future version of the data format, we skip it // and hope that the author of main will *also* include a call to a more // recent version. Note that future versions should handle previous formats. // // NOTE: This version check is also used to implement one-time registration of probes. On the // first pass through the probe section, the version is rewritten to `u8::MAX`, so that any // future read of the section skips all previously-read records. if version > PROBE_REC_VERSION { return Ok(()); } let n_args = data.read_u8()? as usize; let flags = data.read_u16::<NativeEndian>()?; let address = data.read_u64::<NativeEndian>()?; let provname = data.read_cstr(); let probename = data.read_cstr(); let args = { let mut args = Vec::with_capacity(n_args); for _ in 0..n_args { args.push(limit_string_length(data.read_cstr(), MAX_ARG_TYPE_LEN)); } args }; let funcname = match addr_to_info(address).0 { Some(s) => limit_string_length(s, MAX_FUNC_NAME_LEN), None => format!("?{:#x}", address), }; let provname = limit_string_length(provname, MAX_PROVIDER_NAME_LEN); let provider = providers.entry(provname.clone()).or_insert(Provider { name: provname, probes: BTreeMap::new(), }); let probename = limit_string_length(probename, MAX_PROBE_NAME_LEN); let probe = provider.probes.entry(probename.clone()).or_insert(Probe { name: probename, function: funcname, address, offsets: vec![], enabled_offsets: vec![], arguments: vec![], }); probe.arguments = args; // We expect to get records in address order for a given probe; our offsets // would be negative otherwise. assert!(address >= probe.address); if flags == 0 { probe.offsets.push((address - probe.address) as u32); } else { probe.enabled_offsets.push((address - probe.address) as u32); } Ok(()) } trait ReadCstrExt<'a> { fn read_cstr(&mut self) -> &'a str; } impl<'a> ReadCstrExt<'a> for &'a [u8] { fn read_cstr(&mut self) -> &'a str { let index = self .iter() .position(|ch| *ch == 0) .expect("ran out of bytes before we found a zero"); let ret = std::str::from_utf8(&self[..index]).unwrap(); *self = &self[index + 1..]; ret } } // Construct the ASM record for a probe. If `types` is `None`, then is is an is-enabled probe. #[allow(dead_code)] pub(crate) fn emit_probe_record(prov: &str, probe: &str, types: Option<&[DataType]>) -> String { #[cfg(not(target_os = "freebsd"))] let section_ident = r#"set_dtrace_probes,"aw","progbits""#; #[cfg(target_os = "freebsd")] let section_ident = r#"set_dtrace_probes,"awR","progbits""#; let is_enabled = types.is_none(); let n_args = types.map_or(0, |typ| typ.len()); let arguments = types.map_or_else(String::new, |types| { types .iter() .map(|typ| format!(".asciz \"{}\"", typ.to_c_type())) .collect::<Vec<_>>() .join("\n") }); format!( r#" .pushsection {section_ident} .balign 8 991: .4byte 992f-991b // length .byte {version} .byte {n_args} .2byte {flags} .8byte 990b // address .asciz "{prov}" .asciz "{probe}" {arguments} // null-terminated strings for each argument .balign 8 992: .popsection {yeet} "#, section_ident = section_ident, version = PROBE_REC_VERSION, n_args = n_args, flags = if is_enabled { 1 } else { 0 }, prov = prov, probe = probe.replace("__", "-"), arguments = arguments, yeet = if cfg!(any(target_os = "illumos", target_os = "freebsd")) { // The illumos and FreeBSD linkers may yeet our probes section into the trash under // certain conditions. To counteract this, we yeet references to the // probes section into another section. This causes the linker to // retain the probes section. r#" .pushsection yeet_dtrace_probes .8byte 991b .popsection "# } else { "" }, ) } #[cfg(test)] mod test { use std::collections::BTreeMap; use byteorder::{NativeEndian, WriteBytesExt}; use super::emit_probe_record; use super::process_probe_record; use super::process_section; use super::DataType; use super::PROBE_REC_VERSION; use super::{MAX_PROBE_NAME_LEN, MAX_PROVIDER_NAME_LEN}; use dtrace_parser::BitWidth; use dtrace_parser::DataType as DType; use dtrace_parser::Integer; use dtrace_parser::Sign; #[test] fn test_process_probe_record() { let mut rec = Vec::<u8>::new(); // write a dummy length rec.write_u32::<NativeEndian>(0).unwrap(); rec.write_u8(PROBE_REC_VERSION).unwrap(); rec.write_u8(0).unwrap(); rec.write_u16::<NativeEndian>(0).unwrap(); rec.write_u64::<NativeEndian>(0x1234).unwrap(); rec.write_cstr("provider"); rec.write_cstr("probe"); // fix the length field let len = rec.len(); (&mut rec[0..]) .write_u32::<NativeEndian>(len as u32) .unwrap(); let mut providers = BTreeMap::new(); process_probe_record(&mut providers, &mut rec, true).unwrap(); let probe = providers .get("provider") .unwrap() .probes .get("probe") .unwrap(); assert_eq!(probe.name, "probe"); assert_eq!(probe.address, 0x1234); } #[test] fn test_process_probe_record_long_names() { let mut rec = Vec::<u8>::new(); // write a dummy length let long_name = "p".repeat(130); rec.write_u32::<NativeEndian>(0).unwrap(); rec.write_u8(PROBE_REC_VERSION).unwrap(); rec.write_u8(0).unwrap(); rec.write_u16::<NativeEndian>(0).unwrap(); rec.write_u64::<NativeEndian>(0x1234).unwrap(); rec.write_cstr(&long_name); rec.write_cstr(&long_name); // fix the length field let len = rec.len(); (&mut rec[0..]) .write_u32::<NativeEndian>(len as u32) .unwrap(); let mut providers = BTreeMap::new(); process_probe_record(&mut providers, &mut rec, true).unwrap(); let expected_provider_name = &long_name[..MAX_PROVIDER_NAME_LEN - 1]; let expected_probe_name = &long_name[..MAX_PROBE_NAME_LEN - 1]; assert!(providers.get(&long_name).is_none()); let probe = providers .get(expected_provider_name) .unwrap() .probes .get(expected_probe_name) .unwrap(); assert_eq!(probe.name, expected_probe_name); assert_eq!(probe.address, 0x1234); } // Write two probe records, from the same provider. // // The version argument is used to control the probe record version, which helps test one-time // registration of probes. fn make_record(version: u8) -> Vec<u8> { let mut data = Vec::<u8>::new(); // write a dummy length for the first record data.write_u32::<NativeEndian>(0).unwrap(); data.write_u8(version).unwrap(); data.write_u8(0).unwrap(); data.write_u16::<NativeEndian>(0).unwrap(); data.write_u64::<NativeEndian>(0x1234).unwrap(); data.write_cstr("provider"); data.write_cstr("probe"); let len = data.len(); (&mut data[0..]) .write_u32::<NativeEndian>(len as u32) .unwrap(); data.write_u32::<NativeEndian>(0).unwrap(); data.write_u8(version).unwrap(); data.write_u8(0).unwrap(); data.write_u16::<NativeEndian>(0).unwrap(); data.write_u64::<NativeEndian>(0x12ab).unwrap(); data.write_cstr("provider"); data.write_cstr("probe"); let len2 = data.len() - len; (&mut data[len..]) .write_u32::<NativeEndian>(len2 as u32) .unwrap(); data } #[test] fn test_process_section() { let mut data = make_record(PROBE_REC_VERSION); let section = process_section(&mut data, true).unwrap(); let probe = section .providers .get("provider") .unwrap() .probes .get("probe") .unwrap(); assert_eq!(probe.name, "probe"); assert_eq!(probe.address, 0x1234); assert_eq!(probe.offsets, vec![0, 0x12ab - 0x1234]); } #[test] fn test_re_process_section() { // Ensure that re-processing the same section returns zero probes, as they should have all // been previously processed. let mut data = make_record(PROBE_REC_VERSION); let section = process_section(&mut data, true).unwrap(); assert_eq!(section.providers.len(), 1); assert_eq!(data[4], u8::MAX); let section = process_section(&mut data, true).unwrap(); assert_eq!(data[4], u8::MAX); assert_eq!(section.providers.len(), 0); } #[test] fn test_process_section_future_version() { // Ensure that we _don't_ modify a future version number in a probe record, but that the // probes are still skipped (since by definition we're ignoring future versions). let mut data = make_record(PROBE_REC_VERSION + 1); let section = process_section(&mut data, true).unwrap(); assert_eq!(section.providers.len(), 0); assert_eq!(data[4], PROBE_REC_VERSION + 1); } trait WriteCstrExt { fn write_cstr(&mut self, s: &str); } impl WriteCstrExt for Vec<u8> { fn write_cstr(&mut self, s: &str) { self.extend_from_slice(s.as_bytes()); self.push(0); } } #[test] fn test_emit_probe_record() { let provider = "provider"; let probe = "probe"; let types = [ DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), DataType::Native(DType::String), ]; let record = emit_probe_record(provider, probe, Some(&types)); let mut lines = record.lines(); println!("{}", record); lines.next(); // empty line assert!(lines.next().unwrap().contains(".pushsection")); let mut lines = lines.skip(3); assert!(lines .next() .unwrap() .contains(&format!(".byte {}", PROBE_REC_VERSION))); assert!(lines .next() .unwrap() .contains(&format!(".byte {}", types.len()))); for (typ, line) in types.iter().zip(lines.skip(4)) { assert!(line.contains(&format!(".asciz \"{}\"", typ.to_c_type()))); } } #[test] fn test_emit_probe_record_dunders() { let provider = "provider"; let probe = "my__probe"; let types = [ DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), DataType::Native(dtrace_parser::DataType::String), ]; let record = emit_probe_record(provider, probe, Some(&types)); assert!( record.contains("my-probe"), "Expected double-underscores to be translated to a single dash" ); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/common.rs
usdt-impl/src/common.rs
//! Shared code used in both the linker and no-linker implementations of this crate. // Copyright 2024 Oxide Computer Company // // 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. use crate::DataType; use proc_macro2::TokenStream; use quote::{format_ident, quote}; /// Construct a function to type-check the argument closure. /// /// This constructs a function that is never called, but is used to ensure that /// the closure provided to each probe macro returns arguments of the right /// type. pub fn construct_type_check( provider_name: &str, probe_name: &str, use_statements: &[syn::ItemUse], types: &[DataType], ) -> TokenStream { // If there are zero arguments, we need to make sure we can assign the // result of the closure to (). if types.is_empty() { return quote! { let _: () = ($args_lambda)(); }; } let type_check_params = types .iter() .map(|typ| match typ { DataType::Serializable(ty) => { match ty { syn::Type::Reference(reference) => { if let Some(elem) = shared_slice_elem_type(reference) { quote! { _: impl AsRef<[#elem]> } } else { let elem = &*reference.elem; quote! { _: impl ::std::borrow::Borrow<#elem> } } } syn::Type::Slice(slice) => { let elem = &*slice.elem; quote! { _: impl AsRef<[#elem]> } } syn::Type::Array(array) => { let elem = &*array.elem; quote! { _: impl AsRef<[#elem]> } } syn::Type::Path(_) => { quote! { _: impl ::std::borrow::Borrow<#ty> } } _ => { // Any other type must be specified exactly as given in the probe parameter quote! { _: #ty } } } } DataType::Native(dtrace_parser::DataType::String) => quote! { _: impl AsRef<str> }, _ => { let arg = typ.to_rust_type(); quote! { _: impl ::std::borrow::Borrow<#arg> } } }) .collect::<Vec<_>>(); // Create a list of arguments `arg.0`, `arg.1`, ... to pass to the check // function. let type_check_args = (0..types.len()) .map(|i| { let index = syn::Index::from(i); quote! { args.#index } }) .collect::<Vec<_>>(); let type_check_fn = format_ident!("__usdt_private_{}_{}_type_check", provider_name, probe_name); quote! { #[allow(unused_imports)] #(#use_statements)* #[allow(non_snake_case)] fn #type_check_fn(#(#type_check_params),*) {} let _ = || { #type_check_fn(#(#type_check_args),*); }; } } fn shared_slice_elem_type(reference: &syn::TypeReference) -> Option<&syn::Type> { if let syn::Type::Slice(slice) = &*reference.elem { Some(&*slice.elem) } else { None } } // Return code to destructure a probe arguments into identifiers, and to pass those to ASM // registers. pub fn construct_probe_args(types: &[DataType]) -> (TokenStream, TokenStream) { // x86_64 passes the first 6 arguments in registers, with the rest on the stack. // We limit this to 6 arguments in all cases for now, as handling those stack // arguments would be challenging with the current `asm!` macro implementation. #[cfg(target_arch = "x86_64")] let abi_regs = ["rdi", "rsi", "rdx", "rcx", "r8", "r9"]; #[cfg(target_arch = "aarch64")] let abi_regs = ["x0", "x1", "x2", "x3", "x4", "x5"]; #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] compile_error!("USDT only supports x86_64 and ARM64 architectures"); assert!( types.len() <= abi_regs.len(), "Up to 6 probe arguments are currently supported" ); let (unpacked_args, in_regs): (Vec<_>, Vec<_>) = types .iter() .zip(&abi_regs) .enumerate() .map(|(i, (typ, reg))| { let arg = format_ident!("arg_{}", i); let index = syn::Index::from(i); let input = quote! { args.#index }; let (value, at_use) = asm_type_convert(typ, input); // These values must refer to the actual traced data and prevent it // from being dropped until after we've completed the probe // invocation. let destructured_arg = quote! { let #arg = #value; }; // Here, we convert the argument to store it within a register. let register_arg = quote! { in(#reg) (#arg #at_use) }; (destructured_arg, register_arg) }) .unzip(); let arg_lambda = call_argument_closure(types); let unpacked_args = quote! { #arg_lambda #(#unpacked_args)* }; let in_regs = quote! { #(#in_regs,)* }; (unpacked_args, in_regs) } /// Call the argument closure, assigning its output to `args`. pub fn call_argument_closure(types: &[DataType]) -> TokenStream { match types.len() { // Don't bother with any closure if there are no arguments. 0 => quote! {}, // Wrap a single argument in a tuple. 1 => quote! { let args = (($args_lambda)(),); }, // General case. _ => quote! { let args = ($args_lambda)(); }, } } // Convert a supported data type to 1. a type to store for the duration of the // probe invocation and 2. a transformation for compatibility with an asm // register. fn asm_type_convert(typ: &DataType, input: TokenStream) -> (TokenStream, TokenStream) { match typ { DataType::Serializable(_) => ( // Convert the input to JSON. This is a fallible operation, however, so we wrap the // data in a result-like JSON blob, mapping the `Result`'s variants to the keys "ok" // and "err". quote! { [ match ::usdt::to_json(&#input) { Ok(json) => format!("{{\"ok\":{}}}", json), Err(e) => format!("{{\"err\":\"{}\"}}", e.to_string()), }.as_bytes(), &[0_u8] ].concat() }, quote! { .as_ptr() as usize }, ), DataType::Native(dtrace_parser::DataType::String) => ( quote! { [(#input.as_ref() as &str).as_bytes(), &[0_u8]].concat() }, quote! { .as_ptr() as usize }, ), DataType::Native(_) => { let ty = typ.to_rust_type(); ( quote! { (*<_ as ::std::borrow::Borrow<#ty>>::borrow(&#input) as usize) }, quote! {}, ) } DataType::UniqueId => (quote! { #input.as_u64() as usize }, quote! {}), } } /// Create the top-level probe macro. /// /// This takes the implementation block constructed elsewhere, and builds out /// the actual macro users call in their code to fire the probe. pub(crate) fn build_probe_macro( config: &crate::CompileProvidersConfig, probe_name: &str, types: &[DataType], impl_block: TokenStream, ) -> TokenStream { let module = config.module_ident(); let macro_name = config.probe_ident(probe_name); let no_args_match = if types.is_empty() { quote! { () => { crate::#module::#macro_name!(|| ()) }; } } else { quote! {} }; quote! { #[allow(unused_macros)] macro_rules! #macro_name { #no_args_match ($tree:tt) => { compile_error!("USDT probe macros should be invoked with a closure returning the arguments"); }; ($args_lambda:expr) => { { #impl_block } }; } #[allow(unused_imports)] pub(crate) use #macro_name; } } #[cfg(test)] mod tests { use super::*; use dtrace_parser::BitWidth; use dtrace_parser::DataType as DType; use dtrace_parser::Integer; use dtrace_parser::Sign; #[test] fn test_construct_type_check_empty() { let expected = quote! { let _ : () = ($args_lambda)(); }; let block = construct_type_check("", "", &[], &[]); assert_eq!(block.to_string(), expected.to_string()); } #[test] fn test_construct_type_check_native() { let provider = "provider"; let probe = "probe"; let types = &[ DataType::Native(DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), DataType::Native(DType::Integer(Integer { sign: Sign::Signed, width: BitWidth::Bit64, })), ]; let expected = quote! { #[allow(unused_imports)] #[allow(non_snake_case)] fn __usdt_private_provider_probe_type_check( _: impl ::std::borrow::Borrow<u8>, _: impl ::std::borrow::Borrow<i64> ) { } let _ = || { __usdt_private_provider_probe_type_check(args.0, args.1); }; }; let block = construct_type_check(provider, probe, &[], types); assert_eq!(block.to_string(), expected.to_string()); } #[test] fn test_construct_type_check_with_string() { let provider = "provider"; let probe = "probe"; let types = &[DataType::Native(dtrace_parser::DataType::String)]; let use_statements = vec![]; let expected = quote! { #[allow(unused_imports)] #[allow(non_snake_case)] fn __usdt_private_provider_probe_type_check(_: impl AsRef<str>) { } let _ = || { __usdt_private_provider_probe_type_check(args.0); }; }; let block = construct_type_check(provider, probe, &use_statements, types); assert_eq!(block.to_string(), expected.to_string()); } #[test] fn test_construct_type_check_with_shared_slice() { let provider = "provider"; let probe = "probe"; let types = &[DataType::Serializable(syn::parse_str("&[u8]").unwrap())]; let use_statements = vec![]; let expected = quote! { #[allow(unused_imports)] #[allow(non_snake_case)] fn __usdt_private_provider_probe_type_check(_: impl AsRef<[u8]>) { } let _ = || { __usdt_private_provider_probe_type_check(args.0); }; }; let block = construct_type_check(provider, probe, &use_statements, types); assert_eq!(block.to_string(), expected.to_string()); } #[test] fn test_construct_type_check_with_custom_type() { let provider = "provider"; let probe = "probe"; let types = &[DataType::Serializable(syn::parse_str("MyType").unwrap())]; let use_statements = vec![syn::parse2(quote! { use my_module::MyType; }).unwrap()]; let expected = quote! { #[allow(unused_imports)] use my_module::MyType; #[allow(non_snake_case)] fn __usdt_private_provider_probe_type_check(_: impl ::std::borrow::Borrow<MyType>) { } let _ = || { __usdt_private_provider_probe_type_check(args.0); }; }; let block = construct_type_check(provider, probe, &use_statements, types); assert_eq!(block.to_string(), expected.to_string()); } #[test] fn test_construct_probe_args() { let types = &[ DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), DataType::Native(dtrace_parser::DataType::String), ]; #[cfg(target_arch = "x86_64")] let registers = ["rdi", "rsi"]; #[cfg(target_arch = "aarch64")] let registers = ["x0", "x1"]; let (args, regs) = construct_probe_args(types); let expected = quote! { let args = ($args_lambda)(); let arg_0 = (*<_ as ::std::borrow::Borrow<*const u8>>::borrow(&args.0) as usize); let arg_1 = [(args.1.as_ref() as &str).as_bytes(), &[0_u8]].concat(); }; assert_eq!(args.to_string(), expected.to_string()); for (i, (expected, actual)) in registers .iter() .zip(regs.to_string().split(',')) .enumerate() { let reg = actual.replace(' ', ""); let expected = format!("in(\"{}\")(arg_{}", expected, i); assert!( reg.starts_with(&expected), "reg: {}; expected {}", reg, expected, ); } } #[test] fn test_asm_type_convert() { use std::str::FromStr; let (out, post) = asm_type_convert( &DataType::Native(DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), TokenStream::from_str("foo").unwrap(), ); assert_eq!( out.to_string(), quote! {(*<_ as ::std::borrow::Borrow<u8>>::borrow(&foo) as usize)}.to_string() ); assert_eq!(post.to_string(), quote! {}.to_string()); let (out, post) = asm_type_convert( &DataType::Native(dtrace_parser::DataType::String), TokenStream::from_str("foo").unwrap(), ); assert_eq!( out.to_string(), quote! { [(foo.as_ref() as &str).as_bytes(), &[0_u8]].concat() }.to_string() ); assert_eq!(post.to_string(), quote! { .as_ptr() as usize }.to_string()); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/linker.rs
usdt-impl/src/linker.rs
//! USDT implementation on platforms with linker support (macOS). //! //! On systems with linker support for the compile-time construction of DTrace //! USDT probes we can lean heavily on those mechanisms. Rather than interpreting //! the provider file ourselves, we invoke the system's `dtrace -h` to generate a C //! header file. That header file contains the linker directives that convey //! information from the provider definition such as types and stability. We parse //! that header file and generate code that effectively reproduces in Rust the //! equivalent of what we would see in C. //! //! For example, the header file might contain code like this: //! ```ignore //! #define FOO_STABILITY "___dtrace_stability$foo$v1$1_1_0_1_1_0_1_1_0_1_1_0_1_1_0" //! #define FOO_TYPEDEFS "___dtrace_typedefs$foo$v2" //! //! #if !defined(DTRACE_PROBES_DISABLED) || !DTRACE_PROBES_DISABLED //! //! #define FOO_BAR() \ //! do { \ //! __asm__ volatile(".reference " FOO_TYPEDEFS); \ //! __dtrace_probe$foo$bar$v1(); \ //! __asm__ volatile(".reference " FOO_STABILITY); \ //! } while (0) //! ``` //! //! In rust, we'll want the probe site to look something like this: //! ```ignore //! unsafe extern "C" { //! #[link_name = "__dtrace_stability$foo$v1$1_1_0_1_1_0_1_1_0_1_1_0_1_1_0"] //! fn stability(); //! #[link_name = "__dtrace_probe$foo$bar$v1"] //! fn probe(); //! #[link_name = "__dtrace_typedefs$foo$v2"] //! fn typedefs(); //! //! } //! unsafe { //! asm!(".reference {}", sym typedefs); //! probe(); //! asm!(".reference {}", sym stability); //! } //! ``` //! There are a few things to note above: //! 1. We cannot simply generate code with the symbol name embedded in the asm! //! block e.g. `asm!(".reference __dtrace_typedefs$foo$v2")`. The asm! macro //! removes '$' characters yielding the incorrect symbol. //! 2. The header file stability and typedefs contain three '_'s whereas the //! Rust code has just two. The `sym <symbol_name>` apparently prepends an //! extra underscore in this case. //! 3. The probe needs to be a function type (because we call it), but the types //! of the `stability` and `typedefs` symbols could be anything--we just need //! a symbol name we can reference for the asm! macro that won't get garbled. // Copyright 2024 Oxide Computer Company // // 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. use crate::{common, DataType, Provider}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use std::{ collections::BTreeMap, convert::TryFrom, env, io::Write, process::{Command, Stdio}, }; /// Compile a DTrace provider definition into Rust tokens that implement its probes. pub fn compile_provider_source( source: &str, config: &crate::CompileProvidersConfig, ) -> Result<TokenStream, crate::Error> { let dfile = dtrace_parser::File::try_from(source)?; let header = build_header_from_provider(&source)?; let provider_info = extract_providers(&header); let providers = dfile .providers() .into_iter() .map(|provider| { let provider = Provider::from(provider); // Ensure that the name of the module in the config is set, either by the caller or // defaulting to the provider name. let config = crate::CompileProvidersConfig { provider: Some(provider.name.clone()), probe_format: config.probe_format.clone(), module: match &config.module { None => Some(provider.name.clone()), other => other.clone(), }, }; compile_provider(&provider, &provider_info[&provider.name], &config) }) .collect::<Vec<_>>(); Ok(quote! { #(#providers)* }) } pub fn compile_provider_from_definition( provider: &Provider, config: &crate::CompileProvidersConfig, ) -> TokenStream { // Unwrap safety: The type signature confirms that `provider` is valid. let header = build_header_from_provider(&provider.to_d_source()).unwrap(); let provider_info = extract_providers(&header); let provider_tokens = compile_provider(provider, &provider_info[&provider.name], config); quote! { #provider_tokens } } fn compile_provider( provider: &Provider, provider_info: &ProviderInfo, config: &crate::CompileProvidersConfig, ) -> TokenStream { let mut probe_impls = Vec::new(); for probe in provider.probes.iter() { probe_impls.push(compile_probe( provider, &probe.name, config, provider_info, &probe.types, )); } let module = config.module_ident(); quote! { pub(crate) mod #module { #(#probe_impls)* } } } fn compile_probe( provider: &Provider, probe_name: &str, config: &crate::CompileProvidersConfig, provider_info: &ProviderInfo, types: &[DataType], ) -> TokenStream { // Retrieve the string names and the Rust identifiers used for the extern functions. // These are provided by the macOS linker, but have invalid Rust identifier names, like // `foo$bar`. We name them with valid Rust idents, and specify their link name as that of the // function provided by the macOS linker. let stability = &provider_info.stability; let stability_fn = format_ident!("stability"); let typedefs = &provider_info.typedefs; let typedef_fn = format_ident!("typedefs"); let is_enabled = &provider_info.is_enabled[probe_name]; let is_enabled_fn = format_ident!("{}_{}_enabled", &provider.name, probe_name); // The probe function is a little different. We prefix it with `__` because otherwise it has // the same name as the macro itself, which leads to conflicts. let probe = &provider_info.probes[probe_name]; let extern_probe_fn = format_ident!("__{}", config.probe_ident(probe_name)); let ffi_param_list = types.iter().map(|typ| { let ty = typ.to_rust_ffi_type(); syn::parse2::<syn::FnArg>(quote! { _: #ty }).unwrap() }); let (unpacked_args, in_regs) = common::construct_probe_args(types); let type_check_fn = common::construct_type_check(&provider.name, probe_name, &provider.use_statements, types); #[cfg(target_arch = "x86_64")] let call_instruction = quote! { "call {extern_probe_fn}" }; #[cfg(target_arch = "aarch64")] let call_instruction = quote! { "bl {extern_probe_fn}" }; #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] compile_error!("USDT only supports x86_64 and AArch64 architectures"); let impl_block = quote! { unsafe extern "C" { #[allow(unused)] #[link_name = #stability] fn stability(); #[allow(unused)] #[link_name = #typedefs] fn typedefs(); #[allow(unused)] #[link_name = #is_enabled] fn #is_enabled_fn() -> i32; #[allow(unused)] #[link_name = #probe] fn #extern_probe_fn(#(#ffi_param_list,)*); } unsafe { if #is_enabled_fn() != 0 { #unpacked_args #type_check_fn ::std::arch::asm!( ".reference {typedefs}", #call_instruction, ".reference {stability}", typedefs = sym #typedef_fn, extern_probe_fn = sym #extern_probe_fn, stability = sym #stability_fn, #in_regs options(nomem, nostack, preserves_flags) ); } } }; common::build_probe_macro(config, probe_name, types, impl_block) } #[derive(Debug, Default, Clone)] struct ProviderInfo { pub stability: String, pub typedefs: String, pub is_enabled: BTreeMap<String, String>, pub probes: BTreeMap<String, String>, } fn extract_providers(header: &str) -> BTreeMap<String, ProviderInfo> { let mut providers = BTreeMap::new(); for line in header.lines() { if let Some((provider_name, stability)) = is_stability_line(&line) { let mut info = ProviderInfo::default(); info.stability = stability.to_string(); providers.insert(provider_name.to_string(), info); } if let Some((provider_name, typedefs)) = is_typedefs_line(&line) { providers.get_mut(provider_name).unwrap().typedefs = typedefs.to_string(); } if let Some((provider_name, probe_name, enabled)) = is_enabled_line(&line) { providers .get_mut(provider_name) .unwrap() .is_enabled .insert(probe_name.to_string(), enabled.to_string()); } if let Some((provider_name, probe_name, probe)) = is_probe_line(&line) { providers .get_mut(provider_name) .unwrap() .probes .insert(probe_name.to_string(), probe.to_string()); } } providers } // Return the (provider_name, stability) from a line, if it looks like the appropriate #define'd // line from the autogenerated header file. fn is_stability_line(line: &str) -> Option<(&str, &str)> { contains_needle(line, "___dtrace_stability$") } // Return the (provider_name, typedefs) from a line, if it looks like the appropriate #define'd // line from the autogenerated header file. fn is_typedefs_line(line: &str) -> Option<(&str, &str)> { contains_needle(line, "___dtrace_typedefs$") } fn contains_needle<'a>(line: &'a str, needle: &str) -> Option<(&'a str, &'a str)> { if let Some(index) = line.find(needle) { let rest = &line[index + needle.len()..]; let provider_end = rest.find("$").unwrap(); let provider_name = &rest[..provider_end]; // NOTE: The extra offset to the start index works as follows. The symbol name really needs // to be `___dtrace_stability$...`. But that symbol name will have a "_" prefixed to it // during compilation, so we remove the leading one here, knowing it will be added back. let needle = &line[index + 1..line.len() - 1]; Some((provider_name, needle)) } else { None } } // Return the (provider, probe, enabled) from a line, if it looks like the appropriate extern // function declaration from the autogenerated header file. fn is_enabled_line(line: &str) -> Option<(&str, &str, &str)> { contains_needle2(line, "extern int __dtrace_isenabled$") } // Return the (provider, probe, probe) from a line, if it looks like the appropriate extern // function declaration from the autogenerated header file. fn is_probe_line(line: &str) -> Option<(&str, &str, &str)> { contains_needle2(line, "extern void __dtrace_probe$") } fn contains_needle2<'a>(line: &'a str, needle: &str) -> Option<(&'a str, &'a str, &'a str)> { if let Some(index) = line.find(needle) { let rest = &line[index + needle.len()..]; let provider_end = rest.find("$").unwrap(); let provider_name = &rest[..provider_end]; let rest = &rest[provider_end + 1..]; let probe_end = rest.find("$").unwrap(); let probe_name = &rest[..probe_end]; let end = line.rfind("(").unwrap(); let start = line.find(line.split(" ").nth(2).unwrap()).unwrap(); let needle = &line[start..end]; Some((provider_name, probe_name, needle)) } else { None } } fn build_header_from_provider(source: &str) -> Result<String, crate::Error> { // Ensure that `/usr/sbin` is on the PATH, since that is the typical // location for `dtrace`, but some build systems (such as Bazel) reset // the environment variables. let mut path = env::var_os("PATH").unwrap_or_default(); if !path.is_empty() { path.push(":"); } path.push("/usr/sbin"); let mut child = Command::new("dtrace") .env("PATH", path) .arg("-h") .arg("-s") .arg("/dev/stdin") .arg("-o") .arg("/dev/stdout") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn()?; { let stdin = child.stdin.as_mut().ok_or(crate::Error::DTraceError)?; stdin .write_all(source.as_bytes()) .map_err(|_| crate::Error::DTraceError)?; } let output = child.wait_with_output()?; String::from_utf8(output.stdout).map_err(|_| crate::Error::DTraceError) } pub fn register_probes() -> Result<(), crate::Error> { // This function is a NOP, since we're using Apple's linker to create the DOF and call ioctl(2) // to send it to the driver. Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::Probe; #[test] fn test_is_stability_line() { let line = "this line is ok \"___dtrace_stability$foo$bar\""; let result = is_stability_line(line); assert!(result.is_some()); assert_eq!(result.unwrap().0, "foo"); assert_eq!(result.unwrap().1, "__dtrace_stability$foo$bar"); assert!(is_stability_line("bad").is_none()); } #[test] fn test_is_typedefs_line() { let line = "this line is ok \"___dtrace_typedefs$foo$bar\""; let result = is_typedefs_line(line); assert!(result.is_some()); assert_eq!(result.unwrap().0, "foo"); assert_eq!(result.unwrap().1, "__dtrace_typedefs$foo$bar"); assert!(is_typedefs_line("bad").is_none()); } #[test] fn test_is_enabled_line() { let line = "extern int __dtrace_isenabled$foo$bar$xxx(void);"; let result = is_enabled_line(line); assert!(result.is_some()); assert_eq!(result.unwrap().0, "foo"); assert_eq!(result.unwrap().1, "bar"); assert_eq!(result.unwrap().2, "__dtrace_isenabled$foo$bar$xxx"); assert!(is_enabled_line("bad").is_none()); } #[test] fn test_is_probe_line() { let line = "extern void __dtrace_probe$foo$bar$xxx(whatever);"; let result = is_probe_line(line); assert!(result.is_some()); assert_eq!(result.unwrap().0, "foo"); assert_eq!(result.unwrap().1, "bar"); assert_eq!(result.unwrap().2, "__dtrace_probe$foo$bar$xxx"); assert!(is_enabled_line("bad").is_none()); } #[test] fn test_compile_probe() { let provider_name = "foo"; let probe_name = "bar"; let extern_probe_name = "__bar"; let is_enabled = "__dtrace_isenabled$foo$bar$xxx"; let probe = "__dtrace_probe$foo$bar$xxx"; let stability = "__dtrace_probe$foo$v1$1_1_1"; let typedefs = "__dtrace_typedefs$foo$v2"; let types = vec![]; let provider = Provider { name: provider_name.to_string(), probes: vec![Probe { name: probe_name.to_string(), types: types.clone(), }], use_statements: vec![], }; let mut is_enabled_map = BTreeMap::new(); is_enabled_map.insert(String::from(probe_name), String::from(is_enabled)); let mut probes_map = BTreeMap::new(); probes_map.insert(String::from(probe_name), String::from(probe)); let provider_info = ProviderInfo { stability: String::from(stability), typedefs: String::from(typedefs), is_enabled: is_enabled_map, probes: probes_map, }; let tokens = compile_probe( &provider, probe_name, &crate::CompileProvidersConfig { provider: Some(provider_name.to_string()), ..Default::default() }, &provider_info, &types, ); let output = tokens.to_string(); let needle = format!("link_name = \"{is_enabled}\"", is_enabled = is_enabled); assert!(output.contains(&needle)); let needle = format!("link_name = \"{probe}\"", probe = probe); assert!(output.contains(&needle)); let needle = format!( "fn {provider_name}_{probe_name}", provider_name = provider_name, probe_name = probe_name ); assert!(output.contains(&needle)); let needles = &[ "asm ! (\".reference {typedefs}\"", #[cfg(target_arch = "x86_64")] "call {extern_probe_fn}", #[cfg(target_arch = "aarch64")] "bl {extern_probe_fn}", "\".reference {stability}", "typedefs = sym typedefs", &format!( "probe_fn = sym {extern_probe_name}", extern_probe_name = extern_probe_name ), "stability = sym stability", ]; for needle in needles.iter() { assert!( output.contains(needle), "needle {} not found in haystack {}", needle, output, ); } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/stapsdt.rs
usdt-impl/src/stapsdt.rs
// Copyright 2024 Oxide Computer Company // // 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. //! The SystemTap probe version 3 of the USDT crate. //! //! Used on Linux platforms without DTrace. //! //! Name of the file comes from the `NT_STAPSDT` SystemTap probe descriptors' //! type name in `readelf` output. #[path = "stapsdt/args.rs"] mod args; use crate::{common, DataType}; use crate::{Probe, Provider}; use args::format_argument; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use std::convert::TryFrom; pub fn compile_provider_source( source: &str, config: &crate::CompileProvidersConfig, ) -> Result<TokenStream, crate::Error> { let dfile = dtrace_parser::File::try_from(source)?; let providers = dfile .providers() .iter() .map(|provider| { let provider = Provider::from(provider); // Ensure that the name of the module in the config is set, either by the caller or // defaulting to the provider name. let config = crate::CompileProvidersConfig { provider: Some(provider.name.clone()), probe_format: config.probe_format.clone(), module: match &config.module { None => Some(provider.name.clone()), other => other.clone(), }, }; compile_provider(&provider, &config) }) .collect::<Vec<_>>(); Ok(quote! { #(#providers)* }) } pub fn compile_provider_from_definition( provider: &Provider, config: &crate::CompileProvidersConfig, ) -> TokenStream { compile_provider(provider, config) } fn compile_provider(provider: &Provider, config: &crate::CompileProvidersConfig) -> TokenStream { let probe_impls = provider .probes .iter() .map(|probe| compile_probe(provider, probe, config)) .collect::<Vec<_>>(); let module = config.module_ident(); quote! { pub(crate) mod #module { #(#probe_impls)* } } } /// ## Emit a SystemTap probe (version 3 format). /// /// Source: https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation /// /// A STAPSDT probe expands to a single `nop` in the generated code (the `nop` /// instruction is generated in `compile_probe`) and a non-allocated ELF note. /// Additionally, a special `.stapsdt.base` section is needed (once only) for /// detecting prelink address adjustments (its contents do not matter at all). /// /// This method generates the ELF note assembly and an `.ifndef _.stapsdt.base` /// section for the address adjustments. Additionally, this method generates a /// 16 bit "semaphore" (counter) and links it to the ELF note. This semaphore /// is then used to gate invocations of the probe by reading its value at /// runtime and checking it against 0. A value of 0 means that no consumers are /// currently active and the probe and any parameter massaging work can be /// skipped. /// /// ### Summary /// /// A STAPSDT probe in plain pseudo-Rust would look roughly like this: /// ```rust,ignore /// // WARNING: PSEUDO-CODE! /// /// #[linkage = "weak", visibility = "hidden"] /// static __usdt_sema_provider_probe: SyncUnsafeCell<u16> = SyncUnsafeCell::new(0); /// /// let is_enabled = unsafe { __usdt_sema_provider_probe.get().read_volatile() } > 0; /// /// if is_enabled { /// let arg1: u64 = get_arg1(); /// let arg2: u32 = get_arg2(); /// let arg3: *const u8 = get_arg3(); /// const { /// // Build time: Generate a USDT ELF header pointing to this location as /// // the probe location with probe argument types defined as generics /// // and provider name, probe name, and semaphore pointer given as /// // parameters. /// usdt::define::<(u64, u32, *const u8)>("provider", "probe", &__usdt_sema_provider_probe); /// } /// core::arch::nop(); /// } /// ``` /// /// When probing is started using SystemTap, perf, an eBPF program, or other, /// then the above `nop()` instruction will turn into an interrupt instruction /// that transfers control to the kernel which will then run the probe's kernel /// side code (such as an eBPF program). fn emit_probe_record(prov: &str, probe: &str, types: Option<&[DataType]>) -> String { let sema_name = format!("__usdt_sema_{}_{}", prov, probe); let arguments = types.map_or_else(String::new, |types| { types .iter() .enumerate() .map(format_argument) .collect::<Vec<_>>() .join(" ") }); format!( r#"// First define the semaphore // Note: This uses ifndef to make sure the same probe name can be used // in multiple places but they all use the same semaphore. This can be // used to eg. guard additional preparatory work far away from the // actual probe site that will only be used by the probe. .ifndef {sema_name} .pushsection .probes, "aw", "progbits" .weak {sema_name} .hidden {sema_name} .align 2 // align the semaphore to 16 bits {sema_name}: .zero 2 .type {sema_name}, @object .size {sema_name}, 2 .popsection .endif // Second define the actual USDT probe .pushsection .note.stapsdt, "", "note" .balign 4 .4byte 992f-991f, 994f-993f, 3 // length, type 991: .asciz "stapsdt" // vendor string 992: .balign 4 993: .8byte 990b // probe PC address .8byte _.stapsdt.base // link-time sh_addr of base .stapsdt.base section .8byte {sema_name} // probe semaphore address .asciz "{prov}" // provider name .asciz "{probe}" // probe name .asciz "{arguments}" // argument format (null-terminated string) 994: .balign 4 .popsection // Finally define (if not defined yet) the base used to detect prelink // address adjustments. .ifndef _.stapsdt.base .pushsection .stapsdt.base, "aGR", "progbits", .stapsdt.base, comdat .weak _.stapsdt.base .hidden _.stapsdt.base _.stapsdt.base: .space 1 .size _.stapsdt.base, 1 .popsection .endif"#, prov = prov, probe = probe.replace("__", "-"), arguments = arguments, ) } fn compile_probe( provider: &Provider, probe: &Probe, config: &crate::CompileProvidersConfig, ) -> TokenStream { let (unpacked_args, in_regs) = common::construct_probe_args(&probe.types); let probe_rec = emit_probe_record(&provider.name, &probe.name, Some(&probe.types)); let type_check_fn = common::construct_type_check( &provider.name, &probe.name, &provider.use_statements, &probe.types, ); let sema_name = format_ident!("__usdt_sema_{}_{}", provider.name, probe.name); let impl_block = quote! { unsafe extern "C" { // Note: C libraries use a struct containing an unsigned short // for the semaphore counter. Using just a u16 here directly // offers the slightest risk that on some platforms the struct // wrapping could be loadbearing but it is not to the best of // knowledge. static #sema_name: u16; } let is_enabled: u16; unsafe { is_enabled = (&raw const #sema_name).read_volatile(); } if is_enabled != 0 { #unpacked_args #type_check_fn #[allow(named_asm_labels)] unsafe { ::std::arch::asm!( "990: nop", #probe_rec, #in_regs options(nomem, nostack, preserves_flags) ); } } }; common::build_probe_macro(config, &probe.name, &probe.types, impl_block) } pub fn register_probes() -> Result<(), crate::Error> { Ok(()) }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/no-linker.rs
usdt-impl/src/no-linker.rs
//! Implementation of USDT functionality on platforms without runtime linker support. // Copyright 2022 Oxide Computer Company // // 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. use std::convert::TryFrom; use std::fs::OpenOptions; use std::os::unix::io::AsRawFd; use crate::record::{emit_probe_record, process_section}; use crate::{common, Probe, Provider}; use dof::{serialize_section, Section}; use proc_macro2::TokenStream; use quote::quote; /// Compile a DTrace provider definition into Rust tokens that implement its probes. pub fn compile_provider_source( source: &str, config: &crate::CompileProvidersConfig, ) -> Result<TokenStream, crate::Error> { let dfile = dtrace_parser::File::try_from(source)?; let providers = dfile .providers() .iter() .map(|provider| { let provider = Provider::from(provider); // Ensure that the name of the module in the config is set, either by the caller or // defaulting to the provider name. let config = crate::CompileProvidersConfig { provider: Some(provider.name.clone()), probe_format: config.probe_format.clone(), module: match &config.module { None => Some(provider.name.clone()), other => other.clone(), }, }; compile_provider(&provider, &config) }) .collect::<Vec<_>>(); Ok(quote! { #(#providers)* }) } pub fn compile_provider_from_definition( provider: &Provider, config: &crate::CompileProvidersConfig, ) -> TokenStream { compile_provider(provider, config) } fn compile_provider(provider: &Provider, config: &crate::CompileProvidersConfig) -> TokenStream { let probe_impls = provider .probes .iter() .map(|probe| compile_probe(provider, probe, config)) .collect::<Vec<_>>(); let module = config.module_ident(); quote! { pub(crate) mod #module { #(#probe_impls)* } } } fn compile_probe( provider: &Provider, probe: &Probe, config: &crate::CompileProvidersConfig, ) -> TokenStream { let (unpacked_args, in_regs) = common::construct_probe_args(&probe.types); let is_enabled_rec = emit_probe_record(&provider.name, &probe.name, None); let probe_rec = emit_probe_record(&provider.name, &probe.name, Some(&probe.types)); let type_check_fn = common::construct_type_check( &provider.name, &probe.name, &provider.use_statements, &probe.types, ); let impl_block = quote! { { let mut is_enabled: u64; unsafe { ::std::arch::asm!( "990: clr rax", #is_enabled_rec, out("rax") is_enabled, options(nomem, nostack) ); } if is_enabled != 0 { #unpacked_args #type_check_fn unsafe { ::std::arch::asm!( "990: nop", #probe_rec, #in_regs options(nomem, nostack, preserves_flags) ); } } } }; common::build_probe_macro(config, &probe.name, &probe.types, impl_block) } fn extract_probe_records_from_section() -> Result<Section, crate::Error> { unsafe extern "C" { #[link_name = "__start_set_dtrace_probes"] static dtrace_probes_start: usize; #[link_name = "__stop_set_dtrace_probes"] static dtrace_probes_stop: usize; } // Without this the illumos and FreeBSD linker may decide to omit the symbols above // that denote the start and stop addresses for this section. Note that the variable // must be mutable, otherwise this will generate a read-only section with the // name `set_dtrace_probes`. The section containing the actual probe records is // writable (to implement one-time registration), so an immutable variable here // leads to _two_ sections, one writable and one read-only. A mutable variable // here ensures this ends up in a mutable section, the same as the probe records. #[cfg(any(target_os = "illumos", target_os = "freebsd"))] #[link_section = "set_dtrace_probes"] #[used] static mut FORCE_LOAD: [u64; 0] = []; let data = unsafe { let start = (&dtrace_probes_start as *const usize) as usize; let stop = (&dtrace_probes_stop as *const usize) as usize; std::slice::from_raw_parts_mut(start as *mut u8, stop - start) }; process_section(data, /* register = */ true) } pub fn register_probes() -> Result<(), crate::Error> { let section = extract_probe_records_from_section()?; let module_name = section .providers .values() .next() .and_then(|provider| { provider.probes.values().next().and_then(|probe| { crate::record::addr_to_info(probe.address) .1 .map(|path| path.rsplit('/').next().map(String::from).unwrap_or(path)) .or_else(|| Some(format!("?{:#x}", probe.address))) }) }) .unwrap_or_else(|| String::from("unknown-module")); let mut modname = [0; 64]; for (i, byte) in module_name.bytes().take(modname.len() - 1).enumerate() { modname[i] = byte as i8; } ioctl_section(&serialize_section(&section), modname) } fn ioctl_section(buf: &[u8], modname: [std::os::raw::c_char; 64]) -> Result<(), crate::Error> { let helper = dof::dof_bindings::dof_helper { dofhp_mod: modname, dofhp_addr: buf.as_ptr() as u64, dofhp_dof: buf.as_ptr() as u64, #[cfg(target_os = "freebsd")] dofhp_pid: std::process::id() as i32, #[cfg(target_os = "freebsd")] dofhp_gen: 0, }; let data = &helper as *const _; #[cfg(target_os = "illumos")] let cmd: i32 = 0x64746803; #[cfg(target_os = "freebsd")] let cmd: u64 = 0xc0587a03; let file = OpenOptions::new() .read(true) .write(true) .open("/dev/dtrace/helper")?; if unsafe { libc::ioctl(file.as_raw_fd(), cmd, data) } < 0 { Err(crate::Error::IO(std::io::Error::last_os_error())) } else { Ok(()) } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-impl/src/stapsdt/args.rs
usdt-impl/src/stapsdt/args.rs
// Copyright 2024 Aapo Alasuutari // // 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. //! Helpers for generating GNU Assembler format for use in STAPSDT probes. use crate::DataType; use dtrace_parser::{BitWidth, DataType as NativeDataType, Integer, Sign}; /// Convert an Integer type and a register index into a GNU Assembler operation /// that reads the integer's value from the correct register. Effectively this /// means generating a string like `%REG` where `REG` is the register that the /// data is located in. fn integer_to_asm_op(integer: &Integer, reg_index: u8) -> &'static str { // See common.rs for note on argument passing and maximum supported // argument count. assert!( reg_index <= 5, "Up to 6 probe arguments are currently supported" ); if cfg!(target_arch = "x86_64") { match (integer.width, reg_index) { (BitWidth::Bit8, 0) => "%dil", (BitWidth::Bit16, 0) => "%di", (BitWidth::Bit32, 0) => "%edi", (BitWidth::Bit64, 0) => "%rdi", (BitWidth::Bit8, 1) => "%sil", (BitWidth::Bit16, 1) => "%si", (BitWidth::Bit32, 1) => "%esi", (BitWidth::Bit64, 1) => "%rsi", (BitWidth::Bit8, 2) => "%dl", (BitWidth::Bit16, 2) => "%dx", (BitWidth::Bit32, 2) => "%edx", (BitWidth::Bit64, 2) => "%rdx", (BitWidth::Bit8, 3) => "%cl", (BitWidth::Bit16, 3) => "%cx", (BitWidth::Bit32, 3) => "%ecx", (BitWidth::Bit64, 3) => "%rcx", (BitWidth::Bit8, 4) => "%r8b", (BitWidth::Bit16, 4) => "%r8w", (BitWidth::Bit32, 4) => "%r8d", (BitWidth::Bit64, 4) => "%r8", (BitWidth::Bit8, 5) => "%r9b", (BitWidth::Bit16, 5) => "%r9w", (BitWidth::Bit32, 5) => "%r9d", (BitWidth::Bit64, 5) => "%r9", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 0) => "%edi", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 0) => "%rdi", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 1) => "%esi", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 1) => "%rsi", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 2) => "%edx", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 2) => "%rdx", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 3) => "%ecx", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 3) => "%rcx", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 4) => "%e8", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 4) => "%r8", #[cfg(target_pointer_width = "32")] (BitWidth::Pointer, 5) => "%e9", #[cfg(target_pointer_width = "64")] (BitWidth::Pointer, 5) => "%r9", #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] (BitWidth::Pointer, _) => compile_error!("Unsupported pointer width"), _ => unreachable!(), } } else if cfg!(target_arch = "aarch64") { // GNU Assembly syntax for SystemTap only uses the extended register // for some reason. match reg_index { 0 => "x0", 1 => "x1", 2 => "x2", 3 => "x3", 4 => "x4", 5 => "x5", _ => unreachable!(), } } else { unreachable!("Unsupported Linux target architecture") } } /// Convert an Integer type into its STAPSDT probe arguments definition /// signedness and size value as a String. fn integer_to_arg_size(integer: &Integer) -> &'static str { match integer.width { BitWidth::Bit8 => match integer.sign { Sign::Unsigned => "1", _ => "-1", }, BitWidth::Bit16 => match integer.sign { Sign::Unsigned => "2", _ => "-2", }, BitWidth::Bit32 => match integer.sign { Sign::Unsigned => "4", _ => "-4", }, BitWidth::Bit64 => match integer.sign { Sign::Unsigned => "8", _ => "-8", }, #[cfg(target_pointer_width = "32")] BitWidth::Pointer => "4", #[cfg(target_pointer_width = "64")] BitWidth::Pointer => "8", #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] BitWidth::Pointer => compile_error!("Unsupported pointer width"), } } const POINTER: Integer = Integer { sign: Sign::Unsigned, width: BitWidth::Pointer, }; const UNIQUE_ID: Integer = Integer { sign: Sign::Unsigned, width: BitWidth::Bit64, }; /// Convert a type and register index to its GNU Assembler operation as a /// String. fn native_data_type_to_asm_op(typ: &NativeDataType, reg_index: u8) -> String { match typ { NativeDataType::Integer(int) => integer_to_asm_op(int, reg_index).into(), // Integer pointers are dereferenced by wrapping the pointer assembly // into parentheses. NativeDataType::Pointer(_) => format!("({})", integer_to_asm_op(&POINTER, reg_index)), NativeDataType::String => integer_to_asm_op(&POINTER, reg_index).into(), } } /// Convert a type to its GNU Assembler size representation as a string. fn native_data_type_to_arg_size(typ: &NativeDataType) -> &'static str { match typ { NativeDataType::Integer(int) => integer_to_arg_size(int), NativeDataType::Pointer(_) | NativeDataType::String => integer_to_arg_size(&POINTER), // Note: If NativeDataType::Float becomes supported, it will need an // "f" suffix in the type, eg. `4f` or `8f`. } } /// Convert a DataType and register index to its GNU Assembler operation as a /// String. fn data_type_to_asm_op(typ: &DataType, reg_index: u8) -> String { match typ { DataType::Native(ty) => native_data_type_to_asm_op(ty, reg_index), DataType::UniqueId => integer_to_asm_op(&UNIQUE_ID, reg_index).into(), DataType::Serializable(_) => integer_to_asm_op(&POINTER, reg_index).into(), } } /// Convert a DataType to its STAPSDT probe argument size representation as a /// String. fn data_type_to_arg_size(typ: &DataType) -> &'static str { match typ { DataType::Native(ty) => native_data_type_to_arg_size(ty), DataType::UniqueId => integer_to_arg_size(&UNIQUE_ID), DataType::Serializable(_) => integer_to_arg_size(&POINTER), } } /// ## Format a STAPSDT probe argument into the SystemTap argument format. /// Source: https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation /// /// ### Summary /// /// Argument format is `Nf@OP`, N is an optional `-` to signal signedness /// followed by one of `{1,2,4,8}` for bit width, `f` is an optional marker /// for floating point values, @ is a separator, and OP is the /// "actual assembly operand". The assembly operand is given in the GNU /// Assembler format. See /// https://en.wikibooks.org/wiki/X86_Assembly/GNU_assembly_syntax /// for details. /// /// ### Examples /// /// 1. Read a u64 from RDI: `8@%rdi`. /// 2. Read an i32 through a pointer in RSI: `-4@(%rsi)`. /// 3. Read an f64 through a pointer in RDI: `8f@(%rdi)`. /// (Not sure if `-` should be added.) /// 4. Read a u64 through a pointer with an offset: `8%-4(%rdi)`. pub(crate) fn format_argument((reg_index, typ): (usize, &DataType)) -> String { format!( "{}@{}", data_type_to_arg_size(typ), data_type_to_asm_op(typ, u8::try_from(reg_index).unwrap()) ) }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-macro/src/lib.rs
usdt-macro/src/lib.rs
//! Prototype proc-macro crate for parsing a DTrace provider definition into Rust code. // Copyright 2021 Oxide Computer Company // // 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. use std::iter::FromIterator; use std::{fs, path::Path}; use quote::quote; use syn::{parse_macro_input, Lit}; use usdt_impl::compile_provider_source; /// Generate DTrace probe macros from a provider definition file. /// /// This macro parses a DTrace provider.d file, given as a single literal string path. It then /// generates a Rust macro for each of the DTrace probe definitions. /// /// For example, let's say the file `"test.d"` has the following contents: /// /// ```ignore /// provider test { /// probe start(uint8_t); /// probe stop(char *, uint8_t); /// }; /// ``` /// /// In a Rust library or application, write: /// /// ```ignore /// dtrace_provider!("test.d"); /// ``` /// /// The macro looks for the file relative to the root of the package, so `"test.d"` /// in this case would be in the same directory as `"Cargo.toml"`. /// /// By default probe macros are named `{provider}_{probe}!`. Arguments are passed /// via a closure that returns a tuple. Note that the provided closure is only /// evaluated when the probe is enabled. One can then add points of instrumentation /// by invoking the macro: /// /// ```ignore /// fn do_stuff(count: u8, name: String) { /// // doing stuff /// test_stop!(|| (name, count)); /// } /// ``` /// /// The probe macro names can be customized by adding `, format = /// my_prefix_{provider}_{probe}` to the macro invocation where `{provider}` and /// `{probe}` are optional and will be substituted with the actual provider and /// probe names: /// /// ```ignore /// dtrace_provider!("test.d", format = "dtrace_{provider}_{probe}"); /// ``` /// /// Note /// ---- /// The only supported types are integers of specific bit-width (e.g., `uint16_t`), /// pointers to integers, and `char *`. #[proc_macro] pub fn dtrace_provider(item: proc_macro::TokenStream) -> proc_macro::TokenStream { let mut tokens = item.into_iter().collect::<Vec<proc_macro::TokenTree>>(); let comma_index = tokens .iter() .enumerate() .find_map(|(i, token)| match token { proc_macro::TokenTree::Punct(p) if p.as_char() == ',' => Some(i), _ => None, }); // Split off the tokens after the comma if there is one. let rest = if let Some(index) = comma_index { let mut rest = tokens.split_off(index); let _ = rest.remove(0); rest } else { Vec::new() }; // Parse the config from the remaining tokens. let config: usdt_impl::CompileProvidersConfig = serde_tokenstream::from_tokenstream( &proc_macro2::TokenStream::from(proc_macro::TokenStream::from_iter(rest)), ) .unwrap(); let first_item = proc_macro::TokenStream::from_iter(tokens); let tok = parse_macro_input!(first_item as Lit); let filename = match tok { Lit::Str(f) => f.value(), _ => panic!("DTrace provider must be a single literal string filename"), }; let source = if filename.ends_with(".d") { let dir = std::env::var("CARGO_MANIFEST_DIR").map_or_else( |_| std::env::current_dir().unwrap(), |s| Path::new(&s).to_path_buf(), ); let path = dir.join(&filename); fs::read_to_string(path).unwrap_or_else(|_| { panic!( "Could not read D source file \"{}\" in {:?}", &filename, dir, ) }) } else { filename.clone() }; match compile_provider_source(&source, &config) { Ok(provider) => provider.into(), Err(e) => { let message = format!( "Error building provider definition in \"{}\"\n\n{}", filename, e ); let out = quote! { compile_error!(#message); }; out.into() } } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/probe-test-macro/src/main.rs
probe-test-macro/src/main.rs
//! An example using the `usdt` crate, generating the probes via a procedural macro // Copyright 2022 Oxide Computer Company // // 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. use std::thread::sleep; use std::time::Duration; // Import the `dtrace_provider` procedural macro, which generates Rust code to call the probes // defined in the given provider file. use usdt::{dtrace_provider, register_probes}; // Call the macro, which generates a Rust macro for each probe in the provider. dtrace_provider!("test.d"); fn main() { let duration = Duration::from_secs(1); let mut counter: u8 = 0; // NOTE: One _must_ call this function in order to actually register the probes with DTrace. // Without this, it won't be possible to list, enable, or see the probes via `dtrace(1)`. register_probes().unwrap(); loop { // Call the "start_work" probe which accepts a u8. test::start_work!(|| counter); // Do some work. sleep(duration); // Call the "stop-work" probe, which accepts a string, u8, and string. test::stop_work!(|| ( format!("the probe has fired {}", counter), counter, format!("{:x}", counter) )); counter = counter.wrapping_add(1); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/ser.rs
dof/src/ser.rs
//! Functions to serialize crate types into DOF. // Copyright 2021 Oxide Computer Company // // 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. use std::mem::size_of; use zerocopy::IntoBytes; use crate::dof_bindings::*; use crate::Section; // Build the binary data for each section of a serialized Section object, as a vector of // (section_type, section_data) tuples. fn build_section_data(section: &Section) -> Vec<(u32, Vec<u8>)> { let mut probe_sections = Vec::new(); let mut provider_sections = Vec::new(); let mut strings = Vec::<u8>::new(); strings.push(0); // starts with a NULL byte let mut arguments = Vec::<u8>::new(); let mut offsets = Vec::new(); let mut enabled_offsets = Vec::new(); for (i, provider) in section.providers.values().enumerate() { let mut provider_section = dof_provider { dofpv_name: strings.len() as _, ..Default::default() }; strings.extend_from_slice(provider.name.as_bytes()); strings.push(0); // Links to the constituent sections for this provider. Note that the probes are all placed // first, with one section (array of probes) for each provider. provider_section.dofpv_strtab = 0; provider_section.dofpv_prargs = 1; provider_section.dofpv_proffs = 2; provider_section.dofpv_prenoffs = 3; provider_section.dofpv_probes = (4 + i) as _; let mut probe_section = Vec::with_capacity(provider.probes.len() * size_of::<dof_probe>()); for probe in provider.probes.values() { let mut probe_t = dof_probe { dofpr_addr: probe.address, ..Default::default() }; // Insert function name and store strtab index probe_t.dofpr_func = strings.len() as _; strings.extend_from_slice(probe.function.as_bytes()); strings.push(0); // Insert probe name and store strtab index probe_t.dofpr_name = strings.len() as _; strings.extend_from_slice(probe.name.as_bytes()); strings.push(0); // Insert argument strings and store strtab indices probe_t.dofpr_argidx = arguments.len() as _; let argv = strings.len() as u32; for (i, arg) in probe.arguments.iter().enumerate() { strings.extend_from_slice(arg.as_bytes()); strings.push(0); arguments.push(i as _); } probe_t.dofpr_nargv = argv; probe_t.dofpr_nargc = probe.arguments.len() as _; probe_t.dofpr_xargv = argv; probe_t.dofpr_xargc = probe.arguments.len() as _; // Insert probe offsets and store indices probe_t.dofpr_offidx = offsets.len() as _; offsets.extend_from_slice(&probe.offsets); probe_t.dofpr_noffs = probe.offsets.len() as _; // Insert is-enabled offset and store indices probe_t.dofpr_enoffidx = enabled_offsets.len() as _; enabled_offsets.extend_from_slice(&probe.enabled_offsets); probe_t.dofpr_nenoffs = probe.enabled_offsets.len() as _; probe_section.extend_from_slice(probe_t.as_bytes()); } probe_sections.push(probe_section); provider_sections.push(provider_section.as_bytes().to_vec()); } // Construct the string table. let mut section_data = Vec::with_capacity(4 + 2 * probe_sections.len()); section_data.push((DOF_SECT_STRTAB, strings)); // Construct the argument mappings table if arguments.is_empty() { arguments.push(0); } section_data.push((DOF_SECT_PRARGS, arguments)); // Construct the offset table let offset_section = offsets .iter() .flat_map(|offset| offset.to_ne_bytes().to_vec()) .collect::<Vec<_>>(); section_data.push((DOF_SECT_PROFFS, offset_section)); // Construct enabled offset table let enabled_offset_section = enabled_offsets .iter() .flat_map(|offset| offset.to_ne_bytes().to_vec()) .collect::<Vec<_>>(); section_data.push((DOF_SECT_PRENOFFS, enabled_offset_section)); // Push remaining probe and provider data. They must be done in this order so the indices to // the probe section for each provider is accurate. for probe_section in probe_sections.into_iter() { section_data.push((DOF_SECT_PROBES, probe_section)); } for provider_section in provider_sections.into_iter() { section_data.push((DOF_SECT_PROVIDER, provider_section)); } section_data } fn build_section_headers( sections: Vec<(u32, Vec<u8>)>, mut offset: usize, ) -> (Vec<dof_sec>, Vec<Vec<u8>>, usize) { let mut section_headers = Vec::with_capacity(sections.len()); let mut section_data = Vec::<Vec<u8>>::with_capacity(sections.len()); for (sec_type, data) in sections.into_iter() { // Different sections expect different alignment and entry sizes. let (alignment, entry_size) = match sec_type { DOF_SECT_STRTAB | DOF_SECT_PRARGS => (1, 1), DOF_SECT_PROFFS | DOF_SECT_PRENOFFS => (size_of::<u32>(), size_of::<u32>()), DOF_SECT_PROVIDER => (size_of::<u32>(), 0), DOF_SECT_PROBES => (size_of::<u64>(), size_of::<dof_probe>()), _ => unimplemented!(), }; // Pad the data of the *previous* section as needed. Note that this space // is not accounted for by the dofs_size field of any section, but it // is--of course--part of the total dofh_filesz. if offset % alignment > 0 { let padding = alignment - offset % alignment; section_data.last_mut().unwrap().extend(vec![0; padding]); offset += padding; } let header = dof_sec { dofs_type: sec_type, dofs_align: alignment as u32, dofs_flags: DOF_SECF_LOAD, dofs_entsize: entry_size as u32, dofs_offset: offset as u64, dofs_size: data.len() as u64, }; offset += data.len(); section_headers.push(header); section_data.push(data); } (section_headers, section_data, offset) } /// Serialize a Section into a vector of DOF bytes pub fn serialize_section(section: &Section) -> Vec<u8> { let sections = build_section_data(section); let hdr_size = size_of::<dof_hdr>() + sections.len() * size_of::<dof_sec>(); let (section_headers, section_data, size) = build_section_headers(sections, hdr_size); let header = dof_hdr { dofh_ident: section.ident.as_bytes(), dofh_flags: 0, dofh_hdrsize: size_of::<dof_hdr>() as _, dofh_secsize: size_of::<dof_sec>() as _, dofh_secnum: section_headers.len() as _, dofh_secoff: size_of::<dof_hdr>() as _, dofh_loadsz: size as _, dofh_filesz: size as _, dofh_pad: 0, }; let mut file_data = Vec::with_capacity(header.dofh_filesz as _); file_data.extend(header.as_bytes()); for header in section_headers.into_iter() { file_data.extend(header.as_bytes()); } for data in section_data.into_iter() { file_data.extend(data); } file_data } #[cfg(test)] mod test { use super::build_section_headers; use crate::dof_bindings::*; #[test] fn test_padding() { let sections = vec![ (DOF_SECT_STRTAB, vec![96_u8]), (DOF_SECT_PROFFS, vec![0x11_u8, 0x22_u8, 0x33_u8, 0x44_u8]), ]; assert_eq!(sections[0].1.len(), 1); let (_, section_data, size) = build_section_headers(sections, 0); assert_eq!(section_data[0].len(), 4); assert_eq!(size, 8); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/lib.rs
dof/src/lib.rs
//! Tools for extracting and parsing data in DTrace Object Format (DOF). //! //! The `dof` crate provides types and functions for reading and writing the DTrace Object Format, //! an ELF-like serialization format used to store information about DTrace providers and probes in //! object files. DOF sections are generated from source code at compile time, and used to //! communicate information to the in-kernel portions of DTrace about the providers and probes //! defined in the source. //! //! Low-level bindings to the DOF C structures are contained in the [`dof_bindings`] module, //! however most client code with interact with the more convenient stuctures defined in the crate //! root. The [`Section`] type describes a complete DOF section as contained in an object file. It //! contains one or more [`Provider`]s, each of which contains one or more [`Probe`]s. //! //! A [`Probe`] describes the names of the related components, such as the function in which it is //! called, the provider to which it belongs, and the probe name itself. It also contains //! information about the location of the probe callsite in the object file itself. This is used by //! DTrace to enable and disable the probe dynamically. //! //! Users of the crate will most likely be interested in deserializing existing DOF data from an //! object file. The function [`extract_dof_sections`] may be used to pull all sections (and all //! providers and probes) from either an ELF or Mach-O object file. //! //! The [`Section::from_bytes`] and [`Section::as_bytes`] methods can be used for ser/des of a //! section directly to DOF itself, i.e., ignoring the larger object file format. //! //! Most useful methods and types are exported in the crate root. However, the lower-level Rust //! bindings to the raw C-structs are also exposed in the [`dof_bindings`] module, and may be //! extracted from a DOF byte slice with the [`des::deserialize_raw_sections`] function. // Copyright 2021 Oxide Computer Company // // 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. #[cfg(feature = "des")] pub mod des; pub mod dof; pub mod dof_bindings; #[cfg(feature = "des")] pub mod fmt; pub mod ser; #[cfg(feature = "des")] pub use crate::des::{ collect_dof_sections, deserialize_section, extract_dof_sections, is_dof_section, }; pub use crate::dof::*; pub use crate::ser::serialize_section;
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/dof.rs
dof/src/dof.rs
//! Types representing DTrace Object Format data structures. //! //! The [`Section`] struct is used to represent a complete DTrace Object Format section as //! contained in an object file. It contains one or more [`Provider`]s, each with one or more //! [`Probe`]s. The `Probe` type contains all the information required to locate a probe callsite //! within an object file. // Copyright 2021 Oxide Computer Company // // 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. use std::mem::size_of; use std::{ collections::BTreeMap, convert::{TryFrom, TryInto}, }; use serde::Serialize; use thiserror::Error; // Magic bytes for a DOF section pub(crate) const DOF_MAGIC: [u8; 4] = [0x7F, b'D', b'O', b'F']; /// Errors related to building or manipulating the DOF format #[derive(Error, Debug)] pub enum Error { /// The DOF identifier is invalid, such as invalid magic bytes #[error("invalid DOF identifier (magic bytes, endianness, or version)")] InvalidIdentifier, /// An error occurred parsing a type from an underlying byte slice #[error("data does not match expected struct layout or is misaligned")] ParseError, /// Attempt to read from an unsupported object file format #[error("unsupported object file format")] UnsupportedObjectFile, /// An error related to parsing the object file #[cfg(feature = "des")] #[error(transparent)] ObjectError(#[from] goblin::error::Error), /// An error during IO #[error(transparent)] IO(#[from] std::io::Error), } /// Represents the DTrace data model, e.g. the pointer width of the platform #[derive(Debug, Clone, Copy, Serialize)] #[repr(u8)] pub enum DataModel { None = 0, ILP32 = 1, LP64 = 2, } impl Default for DataModel { fn default() -> Self { if cfg!(target_pointer_width = "64") { DataModel::LP64 } else { DataModel::ILP32 } } } impl TryFrom<u8> for DataModel { type Error = Error; fn try_from(x: u8) -> Result<Self, Self::Error> { match x { 0 => Ok(DataModel::None), 1 => Ok(DataModel::ILP32), 2 => Ok(DataModel::LP64), _ => Err(Error::InvalidIdentifier), } } } /// Represents the endianness of the platform #[derive(Debug, Clone, Copy, Serialize)] #[repr(u8)] pub enum DataEncoding { None = 0, LittleEndian = 1, BigEndian = 2, } impl Default for DataEncoding { fn default() -> Self { if cfg!(target_endian = "big") { DataEncoding::BigEndian } else { DataEncoding::LittleEndian } } } impl TryFrom<u8> for DataEncoding { type Error = Error; fn try_from(x: u8) -> Result<Self, Self::Error> { match x { 0 => Ok(DataEncoding::None), 1 => Ok(DataEncoding::LittleEndian), 2 => Ok(DataEncoding::BigEndian), _ => Err(Error::InvalidIdentifier), } } } /// Static identifying information about a DOF section (such as version numbers) #[derive(Debug, Clone, Copy, Serialize)] pub struct Ident { pub magic: [u8; 4], pub model: DataModel, pub encoding: DataEncoding, pub version: u8, pub dif_vers: u8, pub dif_ireg: u8, pub dif_treg: u8, } impl<'a> TryFrom<&'a [u8]> for Ident { type Error = Error; fn try_from(buf: &'a [u8]) -> Result<Self, Self::Error> { if buf.len() < size_of::<Ident>() { return Err(Error::ParseError); } let magic = &buf[..DOF_MAGIC.len()]; if magic != DOF_MAGIC { return Err(Error::InvalidIdentifier); } let model = DataModel::try_from(buf[crate::dof_bindings::DOF_ID_MODEL as usize])?; let encoding = DataEncoding::try_from(buf[crate::dof_bindings::DOF_ID_ENCODING as usize])?; let version = buf[crate::dof_bindings::DOF_ID_VERSION as usize]; let dif_vers = buf[crate::dof_bindings::DOF_ID_DIFVERS as usize]; let dif_ireg = buf[crate::dof_bindings::DOF_ID_DIFIREG as usize]; let dif_treg = buf[crate::dof_bindings::DOF_ID_DIFTREG as usize]; Ok(Ident { // Unwrap is safe if the above check against DOF_MAGIC passes magic: magic.try_into().unwrap(), model, encoding, version, dif_vers, dif_ireg, dif_treg, }) } } impl Ident { pub fn as_bytes(&self) -> [u8; 16] { let mut out = [0; 16]; let start = self.magic.len(); out[..start].copy_from_slice(&self.magic[..]); out[start] = self.model as _; out[start + 1] = self.encoding as _; out[start + 2] = self.version; out[start + 3] = self.dif_vers; out[start + 4] = self.dif_ireg; out[start + 5] = self.dif_treg; out } } /// Representation of a DOF section of an object file #[derive(Debug, Clone, Serialize)] pub struct Section { /// The identifying bytes of this section pub ident: Ident, /// The list of providers defined in this section pub providers: BTreeMap<String, Provider>, } impl Section { /// Construct a section from a DOF byte array. #[cfg(feature = "des")] pub fn from_bytes(buf: &[u8]) -> Result<Section, Error> { crate::des::deserialize_section(buf) } /// Serialize a section into DOF object file section. pub fn as_bytes(&self) -> Vec<u8> { crate::ser::serialize_section(self) } /// Serialize a section into a JSON representation of the DOF object file section. pub fn to_json(&self) -> String { serde_json::to_string_pretty(self).unwrap() } } impl Default for Section { fn default() -> Self { Self { ident: Ident { magic: DOF_MAGIC, model: DataModel::LP64, encoding: DataEncoding::LittleEndian, version: crate::dof_bindings::DOF_VERSION as u8, dif_vers: crate::dof_bindings::DIF_VERSION as u8, dif_ireg: crate::dof_bindings::DIF_DIR_NREGS as u8, dif_treg: crate::dof_bindings::DIF_DTR_NREGS as u8, }, providers: BTreeMap::new(), } } } /// Information about a single DTrace probe #[derive(Debug, Clone, Serialize)] pub struct Probe { /// Name of this probe pub name: String, /// Name of the function containing this probe pub function: String, /// Address or offset in the resulting object code pub address: u64, /// Offsets in containing function at which this probe occurs. pub offsets: Vec<u32>, /// Offsets in the containing function at which this probe's is-enabled functions occur. pub enabled_offsets: Vec<u32>, /// Type information for each argument pub arguments: Vec<String>, } /// Information about a single provider #[derive(Debug, Clone, Serialize)] pub struct Provider { /// Name of the provider pub name: String, /// List of probes this provider exports pub probes: BTreeMap<String, Probe>, }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/des.rs
dof/src/des.rs
//! Functions to deserialize crate types from DOF. // Copyright 2021 Oxide Computer Company // // 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. use std::convert::{TryFrom, TryInto}; use std::mem::size_of; use std::path::Path; use goblin::Object; use zerocopy::Ref; use crate::dof::DOF_MAGIC; use crate::dof_bindings::*; use crate::{Error, Ident, Probe, Provider, Section}; // Extract one or more null-terminated strings from the given byte slice. fn extract_strings(buf: &[u8], count: Option<usize>) -> Vec<String> { let chunks = buf.split(|&x| x == 0); if let Some(count) = count { chunks .take(count) .map(|chunk| String::from_utf8(chunk.to_vec()).unwrap()) .collect() } else { chunks .map(|chunk| String::from_utf8(chunk.to_vec()).unwrap()) .collect() } } // Parse a section of probes. The buffer must already be guaranteed to come from a DOF_SECT_PROBES // section, and be the correct length. fn parse_probe_section( buf: &[u8], strtab: &[u8], offsets: &[u32], enabled_offsets: &[u32], _argument_indices: &[u8], ) -> Vec<Probe> { let parse_probe = |buf| { let probe = *Ref::<_, dof_probe>::from_bytes(buf).unwrap(); let offset_index = probe.dofpr_offidx as usize; let offs = (offset_index..offset_index + probe.dofpr_noffs as usize) .map(|index| offsets[index]) .collect(); let enabled_offset_index = probe.dofpr_enoffidx as usize; let enabled_offs = (enabled_offset_index ..enabled_offset_index + probe.dofpr_nenoffs as usize) .map(|index| enabled_offsets[index]) .collect(); let arg_base = probe.dofpr_nargv as usize; let arguments = extract_strings(&strtab[arg_base..], Some(probe.dofpr_nargc as _)); Probe { name: extract_strings(&strtab[probe.dofpr_name as _..], Some(1))[0].clone(), function: extract_strings(&strtab[probe.dofpr_func as _..], Some(1))[0].clone(), address: probe.dofpr_addr, offsets: offs, enabled_offsets: enabled_offs, arguments, } }; buf.chunks(size_of::<dof_probe>()) .map(parse_probe) .collect() } // Extract the bytes of a section by index fn extract_section<'a>(sections: &[dof_sec], index: usize, buf: &'a [u8]) -> &'a [u8] { let offset = sections[index].dofs_offset as usize; let size = sections[index].dofs_size as usize; &buf[offset..offset + size] } // Parse all provider sections fn parse_providers(sections: &[dof_sec], buf: &[u8]) -> Vec<Provider> { let provider_sections = sections .iter() .filter(|sec| sec.dofs_type == DOF_SECT_PROVIDER); let mut providers = Vec::new(); for section_header in provider_sections { let section_start = section_header.dofs_offset as usize; let section_size = section_header.dofs_size as usize; let provider = *Ref::<_, dof_provider>::from_bytes(&buf[section_start..section_start + section_size]) .unwrap(); let strtab = extract_section(sections, provider.dofpv_strtab as _, buf); let name = extract_strings(&strtab[provider.dofpv_name as _..], Some(1))[0].clone(); // Extract the offset/index sections as vectors of a specific type let offsets: Vec<_> = extract_section(sections, provider.dofpv_proffs as _, buf) .chunks(size_of::<u32>()) .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap())) .collect(); let enabled_offsets: Vec<_> = extract_section(sections, provider.dofpv_prenoffs as _, buf) .chunks(size_of::<u32>()) .map(|chunk| u32::from_ne_bytes(chunk.try_into().unwrap())) .collect(); let arguments = extract_section(sections, provider.dofpv_prargs as _, buf).to_vec(); let probes_list = parse_probe_section( extract_section(sections, provider.dofpv_probes as _, buf), strtab, &offsets, &enabled_offsets, &arguments, ); let probes = probes_list .into_iter() .map(|probe| (probe.name.clone(), probe)) .collect(); providers.push(Provider { name, probes }); } providers } fn deserialize_raw_headers(buf: &[u8]) -> Result<(dof_hdr, Vec<dof_sec>), Error> { let file_header = *Ref::<_, dof_hdr>::from_bytes(&buf[..size_of::<dof_hdr>()]) .map_err(|_| Error::ParseError)?; let n_sections: usize = file_header.dofh_secnum as _; let mut section_headers = Vec::with_capacity(n_sections); for i in 0..n_sections { let start = file_header.dofh_secoff as usize + file_header.dofh_secsize as usize * i; let end = start + file_header.dofh_secsize as usize; section_headers .push(*Ref::<_, dof_sec>::from_bytes(&buf[start..end]).map_err(|_| Error::ParseError)?); } Ok((file_header, section_headers)) } /// Simple container for raw DOF data, including header and sections. #[derive(Clone, Debug)] pub struct RawSections { /// The DOF header. pub header: dof_hdr, /// A list of each section, along with its raw bytes. pub sections: Vec<(dof_sec, Vec<u8>)>, } /// Deserialize the raw C-structs for the file header and each section header, along with the byte /// array for those sections. pub fn deserialize_raw_sections(buf: &[u8]) -> Result<RawSections, Error> { let (file_headers, section_headers) = deserialize_raw_headers(buf)?; let sections = section_headers .into_iter() .map(|header| { let start = header.dofs_offset as usize; let end = start + header.dofs_size as usize; (header, buf[start..end].to_vec()) }) .collect(); Ok(RawSections { header: file_headers, sections, }) } /// Deserialize a `Section` from a slice of DOF bytes pub fn deserialize_section(buf: &[u8]) -> Result<Section, Error> { let (file_header, section_headers) = deserialize_raw_headers(buf)?; let ident = Ident::try_from(&file_header.dofh_ident[..])?; let providers_list = parse_providers(&section_headers, buf); let providers = providers_list .into_iter() .map(|provider| (provider.name.clone(), provider)) .collect(); Ok(Section { ident, providers }) } /// Return true if the given byte slice is a DOF section of an object file. pub fn is_dof_section(buf: &[u8]) -> bool { buf.len() >= DOF_MAGIC.len() && buf.starts_with(&DOF_MAGIC) } /// Return the raw byte blobs for each DOF section in the given object file pub fn collect_dof_sections<P: AsRef<Path>>(path: P) -> Result<Vec<Vec<u8>>, Error> { let data = std::fs::read(path)?; match Object::parse(&data)? { Object::Elf(elf) => Ok(elf .section_headers .iter() .filter_map(|section| { let start = section.sh_offset as usize; let end = start + section.sh_size as usize; if is_dof_section(&data[start..end]) { Some(data[start..end].to_vec()) } else { None } }) .collect()), Object::Mach(goblin::mach::Mach::Binary(mach)) => Ok(mach .segments .sections() .flatten() .filter_map(|item| { if let Ok((_, section_data)) = item { if is_dof_section(section_data) { Some(section_data.to_vec()) } else { None } } else { None } }) .collect()), _ => Err(Error::UnsupportedObjectFile), } } /// Extract DOF sections from the given object file (ELF or Mach-O) pub fn extract_dof_sections<P: AsRef<Path>>(path: P) -> Result<Vec<Section>, Error> { collect_dof_sections(path)? .into_iter() .map(|sect| Section::from_bytes(&sect)) .collect() }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/dof_bindings.rs
dof/src/dof_bindings.rs
//! Auto-generated bindings to the DOF-related types in `dtrace.h` /* automatically generated by rust-bindgen 0.57.0 */ #![allow(non_camel_case_types)] use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; pub const DIF_VERSION_1: u32 = 1; pub const DIF_VERSION_2: u32 = 2; pub const DIF_VERSION: u32 = 2; pub const DIF_DIR_NREGS: u32 = 8; pub const DIF_DTR_NREGS: u32 = 8; pub const DIF_OP_OR: u32 = 1; pub const DIF_OP_XOR: u32 = 2; pub const DIF_OP_AND: u32 = 3; pub const DIF_OP_SLL: u32 = 4; pub const DIF_OP_SRL: u32 = 5; pub const DIF_OP_SUB: u32 = 6; pub const DIF_OP_ADD: u32 = 7; pub const DIF_OP_MUL: u32 = 8; pub const DIF_OP_SDIV: u32 = 9; pub const DIF_OP_UDIV: u32 = 10; pub const DIF_OP_SREM: u32 = 11; pub const DIF_OP_UREM: u32 = 12; pub const DIF_OP_NOT: u32 = 13; pub const DIF_OP_MOV: u32 = 14; pub const DIF_OP_CMP: u32 = 15; pub const DIF_OP_TST: u32 = 16; pub const DIF_OP_BA: u32 = 17; pub const DIF_OP_BE: u32 = 18; pub const DIF_OP_BNE: u32 = 19; pub const DIF_OP_BG: u32 = 20; pub const DIF_OP_BGU: u32 = 21; pub const DIF_OP_BGE: u32 = 22; pub const DIF_OP_BGEU: u32 = 23; pub const DIF_OP_BL: u32 = 24; pub const DIF_OP_BLU: u32 = 25; pub const DIF_OP_BLE: u32 = 26; pub const DIF_OP_BLEU: u32 = 27; pub const DIF_OP_LDSB: u32 = 28; pub const DIF_OP_LDSH: u32 = 29; pub const DIF_OP_LDSW: u32 = 30; pub const DIF_OP_LDUB: u32 = 31; pub const DIF_OP_LDUH: u32 = 32; pub const DIF_OP_LDUW: u32 = 33; pub const DIF_OP_LDX: u32 = 34; pub const DIF_OP_RET: u32 = 35; pub const DIF_OP_NOP: u32 = 36; pub const DIF_OP_SETX: u32 = 37; pub const DIF_OP_SETS: u32 = 38; pub const DIF_OP_SCMP: u32 = 39; pub const DIF_OP_LDGA: u32 = 40; pub const DIF_OP_LDGS: u32 = 41; pub const DIF_OP_STGS: u32 = 42; pub const DIF_OP_LDTA: u32 = 43; pub const DIF_OP_LDTS: u32 = 44; pub const DIF_OP_STTS: u32 = 45; pub const DIF_OP_SRA: u32 = 46; pub const DIF_OP_CALL: u32 = 47; pub const DIF_OP_PUSHTR: u32 = 48; pub const DIF_OP_PUSHTV: u32 = 49; pub const DIF_OP_POPTS: u32 = 50; pub const DIF_OP_FLUSHTS: u32 = 51; pub const DIF_OP_LDGAA: u32 = 52; pub const DIF_OP_LDTAA: u32 = 53; pub const DIF_OP_STGAA: u32 = 54; pub const DIF_OP_STTAA: u32 = 55; pub const DIF_OP_LDLS: u32 = 56; pub const DIF_OP_STLS: u32 = 57; pub const DIF_OP_ALLOCS: u32 = 58; pub const DIF_OP_COPYS: u32 = 59; pub const DIF_OP_STB: u32 = 60; pub const DIF_OP_STH: u32 = 61; pub const DIF_OP_STW: u32 = 62; pub const DIF_OP_STX: u32 = 63; pub const DIF_OP_ULDSB: u32 = 64; pub const DIF_OP_ULDSH: u32 = 65; pub const DIF_OP_ULDSW: u32 = 66; pub const DIF_OP_ULDUB: u32 = 67; pub const DIF_OP_ULDUH: u32 = 68; pub const DIF_OP_ULDUW: u32 = 69; pub const DIF_OP_ULDX: u32 = 70; pub const DIF_OP_RLDSB: u32 = 71; pub const DIF_OP_RLDSH: u32 = 72; pub const DIF_OP_RLDSW: u32 = 73; pub const DIF_OP_RLDUB: u32 = 74; pub const DIF_OP_RLDUH: u32 = 75; pub const DIF_OP_RLDUW: u32 = 76; pub const DIF_OP_RLDX: u32 = 77; pub const DIF_OP_XLATE: u32 = 78; pub const DIF_OP_XLARG: u32 = 79; pub const DIF_OP_STRIP: u32 = 80; pub const DIF_INTOFF_MAX: u32 = 65535; pub const DIF_STROFF_MAX: u32 = 65535; pub const DIF_REGISTER_MAX: u32 = 255; pub const DIF_VARIABLE_MAX: u32 = 65535; pub const DIF_SUBROUTINE_MAX: u32 = 65535; pub const DIF_VAR_ARRAY_MIN: u32 = 0; pub const DIF_VAR_ARRAY_UBASE: u32 = 128; pub const DIF_VAR_ARRAY_MAX: u32 = 255; pub const DIF_VAR_OTHER_MIN: u32 = 256; pub const DIF_VAR_OTHER_UBASE: u32 = 1280; pub const DIF_VAR_OTHER_MAX: u32 = 65535; pub const DIF_VAR_ARGS: u32 = 0; pub const DIF_VAR_REGS: u32 = 1; pub const DIF_VAR_UREGS: u32 = 2; pub const DIF_VAR_CURTHREAD: u32 = 256; pub const DIF_VAR_TIMESTAMP: u32 = 257; pub const DIF_VAR_VTIMESTAMP: u32 = 258; pub const DIF_VAR_IPL: u32 = 259; pub const DIF_VAR_EPID: u32 = 260; pub const DIF_VAR_ID: u32 = 261; pub const DIF_VAR_ARG0: u32 = 262; pub const DIF_VAR_ARG1: u32 = 263; pub const DIF_VAR_ARG2: u32 = 264; pub const DIF_VAR_ARG3: u32 = 265; pub const DIF_VAR_ARG4: u32 = 266; pub const DIF_VAR_ARG5: u32 = 267; pub const DIF_VAR_ARG6: u32 = 268; pub const DIF_VAR_ARG7: u32 = 269; pub const DIF_VAR_ARG8: u32 = 270; pub const DIF_VAR_ARG9: u32 = 271; pub const DIF_VAR_STACKDEPTH: u32 = 272; pub const DIF_VAR_CALLER: u32 = 273; pub const DIF_VAR_PROBEPROV: u32 = 274; pub const DIF_VAR_PROBEMOD: u32 = 275; pub const DIF_VAR_PROBEFUNC: u32 = 276; pub const DIF_VAR_PROBENAME: u32 = 277; pub const DIF_VAR_PID: u32 = 278; pub const DIF_VAR_TID: u32 = 279; pub const DIF_VAR_EXECNAME: u32 = 280; pub const DIF_VAR_ZONENAME: u32 = 281; pub const DIF_VAR_WALLTIMESTAMP: u32 = 282; pub const DIF_VAR_USTACKDEPTH: u32 = 283; pub const DIF_VAR_UCALLER: u32 = 284; pub const DIF_VAR_PPID: u32 = 285; pub const DIF_VAR_UID: u32 = 286; pub const DIF_VAR_GID: u32 = 287; pub const DIF_VAR_ERRNO: u32 = 288; pub const DIF_VAR_PTHREAD_SELF: u32 = 512; pub const DIF_VAR_DISPATCHQADDR: u32 = 513; pub const DIF_VAR_MACHTIMESTAMP: u32 = 514; pub const DIF_VAR_CPU: u32 = 515; pub const DIF_VAR_CPUINSTRS: u32 = 516; pub const DIF_VAR_CPUCYCLES: u32 = 517; pub const DIF_VAR_VINSTRS: u32 = 518; pub const DIF_VAR_VCYCLES: u32 = 519; pub const DIF_SUBR_RAND: u32 = 0; pub const DIF_SUBR_MUTEX_OWNED: u32 = 1; pub const DIF_SUBR_MUTEX_OWNER: u32 = 2; pub const DIF_SUBR_MUTEX_TYPE_ADAPTIVE: u32 = 3; pub const DIF_SUBR_MUTEX_TYPE_SPIN: u32 = 4; pub const DIF_SUBR_RW_READ_HELD: u32 = 5; pub const DIF_SUBR_RW_WRITE_HELD: u32 = 6; pub const DIF_SUBR_RW_ISWRITER: u32 = 7; pub const DIF_SUBR_COPYIN: u32 = 8; pub const DIF_SUBR_COPYINSTR: u32 = 9; pub const DIF_SUBR_SPECULATION: u32 = 10; pub const DIF_SUBR_PROGENYOF: u32 = 11; pub const DIF_SUBR_STRLEN: u32 = 12; pub const DIF_SUBR_COPYOUT: u32 = 13; pub const DIF_SUBR_COPYOUTSTR: u32 = 14; pub const DIF_SUBR_ALLOCA: u32 = 15; pub const DIF_SUBR_BCOPY: u32 = 16; pub const DIF_SUBR_COPYINTO: u32 = 17; pub const DIF_SUBR_MSGDSIZE: u32 = 18; pub const DIF_SUBR_MSGSIZE: u32 = 19; pub const DIF_SUBR_GETMAJOR: u32 = 20; pub const DIF_SUBR_GETMINOR: u32 = 21; pub const DIF_SUBR_DDI_PATHNAME: u32 = 22; pub const DIF_SUBR_STRJOIN: u32 = 23; pub const DIF_SUBR_LLTOSTR: u32 = 24; pub const DIF_SUBR_BASENAME: u32 = 25; pub const DIF_SUBR_DIRNAME: u32 = 26; pub const DIF_SUBR_CLEANPATH: u32 = 27; pub const DIF_SUBR_STRCHR: u32 = 28; pub const DIF_SUBR_STRRCHR: u32 = 29; pub const DIF_SUBR_STRSTR: u32 = 30; pub const DIF_SUBR_STRTOK: u32 = 31; pub const DIF_SUBR_SUBSTR: u32 = 32; pub const DIF_SUBR_INDEX: u32 = 33; pub const DIF_SUBR_RINDEX: u32 = 34; pub const DIF_SUBR_HTONS: u32 = 35; pub const DIF_SUBR_HTONL: u32 = 36; pub const DIF_SUBR_HTONLL: u32 = 37; pub const DIF_SUBR_NTOHS: u32 = 38; pub const DIF_SUBR_NTOHL: u32 = 39; pub const DIF_SUBR_NTOHLL: u32 = 40; pub const DIF_SUBR_INET_NTOP: u32 = 41; pub const DIF_SUBR_INET_NTOA: u32 = 42; pub const DIF_SUBR_INET_NTOA6: u32 = 43; pub const DIF_SUBR_TOUPPER: u32 = 44; pub const DIF_SUBR_TOLOWER: u32 = 45; pub const DIF_SUBR_JSON: u32 = 46; pub const DIF_SUBR_STRTOLL: u32 = 47; pub const DIF_SUBR_STRIP: u32 = 48; pub const DIF_SUBR_MAX: u32 = 48; pub const DIF_SUBR_APPLE_MIN: u32 = 200; pub const DIF_SUBR_VM_KERNEL_ADDRPERM: u32 = 200; pub const DIF_SUBR_KDEBUG_TRACE: u32 = 201; pub const DIF_SUBR_KDEBUG_TRACE_STRING: u32 = 202; pub const DIF_SUBR_APPLE_MAX: u32 = 202; pub const DIF_INSTR_NOP: u32 = 603979776; pub const DIF_INSTR_POPTS: u32 = 838860800; pub const DIF_INSTR_FLUSHTS: u32 = 855638016; pub const DIF_REG_R0: u32 = 0; pub const DIF_TYPE_CTF: u32 = 0; pub const DIF_TYPE_STRING: u32 = 1; pub const DIF_TF_BYREF: u32 = 1; pub const DIF_TF_BYUREF: u32 = 2; pub const DOF_ID_SIZE: u32 = 16; pub const DOF_ID_MAG0: u32 = 0; pub const DOF_ID_MAG1: u32 = 1; pub const DOF_ID_MAG2: u32 = 2; pub const DOF_ID_MAG3: u32 = 3; pub const DOF_ID_MODEL: u32 = 4; pub const DOF_ID_ENCODING: u32 = 5; pub const DOF_ID_VERSION: u32 = 6; pub const DOF_ID_DIFVERS: u32 = 7; pub const DOF_ID_DIFIREG: u32 = 8; pub const DOF_ID_DIFTREG: u32 = 9; pub const DOF_ID_PAD: u32 = 10; pub const DOF_MAG_MAG0: u32 = 127; pub const DOF_MAG_MAG1: u8 = 68u8; pub const DOF_MAG_MAG2: u8 = 79u8; pub const DOF_MAG_MAG3: u8 = 70u8; pub const DOF_MAG_STRING: &[u8; 5usize] = b"\x7FDOF\0"; pub const DOF_MAG_STRLEN: u32 = 4; pub const DOF_MODEL_NONE: u32 = 0; pub const DOF_MODEL_ILP32: u32 = 1; pub const DOF_MODEL_LP64: u32 = 2; pub const DOF_MODEL_NATIVE: u32 = 2; pub const DOF_ENCODE_NONE: u32 = 0; pub const DOF_ENCODE_LSB: u32 = 1; pub const DOF_ENCODE_MSB: u32 = 2; pub const DOF_ENCODE_NATIVE: u32 = 1; pub const DOF_VERSION_1: u32 = 1; pub const DOF_VERSION_2: u32 = 2; pub const DOF_VERSION_3: u32 = 3; #[cfg(target_os = "macos")] pub const DOF_VERSION: u32 = 3; #[cfg(not(target_os = "macos"))] pub const DOF_VERSION: u32 = 2; pub const DOF_FL_VALID: u32 = 0; pub const DOF_SECIDX_NONE: i32 = -1; pub const DOF_STRIDX_NONE: i32 = -1; pub const DOF_SECT_NONE: u32 = 0; pub const DOF_SECT_COMMENTS: u32 = 1; pub const DOF_SECT_SOURCE: u32 = 2; pub const DOF_SECT_ECBDESC: u32 = 3; pub const DOF_SECT_PROBEDESC: u32 = 4; pub const DOF_SECT_ACTDESC: u32 = 5; pub const DOF_SECT_DIFOHDR: u32 = 6; pub const DOF_SECT_DIF: u32 = 7; pub const DOF_SECT_STRTAB: u32 = 8; pub const DOF_SECT_VARTAB: u32 = 9; pub const DOF_SECT_RELTAB: u32 = 10; pub const DOF_SECT_TYPTAB: u32 = 11; pub const DOF_SECT_URELHDR: u32 = 12; pub const DOF_SECT_KRELHDR: u32 = 13; pub const DOF_SECT_OPTDESC: u32 = 14; pub const DOF_SECT_PROVIDER: u32 = 15; pub const DOF_SECT_PROBES: u32 = 16; pub const DOF_SECT_PRARGS: u32 = 17; pub const DOF_SECT_PROFFS: u32 = 18; pub const DOF_SECT_INTTAB: u32 = 19; pub const DOF_SECT_UTSNAME: u32 = 20; pub const DOF_SECT_XLTAB: u32 = 21; pub const DOF_SECT_XLMEMBERS: u32 = 22; pub const DOF_SECT_XLIMPORT: u32 = 23; pub const DOF_SECT_XLEXPORT: u32 = 24; pub const DOF_SECT_PREXPORT: u32 = 25; pub const DOF_SECT_PRENOFFS: u32 = 26; pub const DOF_SECF_LOAD: u32 = 1; pub const DOF_RELO_NONE: u32 = 0; pub const DOF_RELO_SETX: u32 = 1; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dtrace_diftype { pub dtdt_kind: u8, pub dtdt_ckind: u8, pub dtdt_flags: u8, pub dtdt_pad: u8, pub dtdt_size: u32, } pub type dtrace_diftype_t = dtrace_diftype; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_hdr { pub dofh_ident: [u8; 16usize], pub dofh_flags: u32, pub dofh_hdrsize: u32, pub dofh_secsize: u32, pub dofh_secnum: u32, pub dofh_secoff: u64, pub dofh_loadsz: u64, pub dofh_filesz: u64, pub dofh_pad: u64, } pub type dof_hdr_t = dof_hdr; pub type dof_secidx_t = u32; pub type dof_stridx_t = u32; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_sec { pub dofs_type: u32, pub dofs_align: u32, pub dofs_flags: u32, pub dofs_entsize: u32, pub dofs_offset: u64, pub dofs_size: u64, } pub type dof_sec_t = dof_sec; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_ecbdesc { pub dofe_probes: dof_secidx_t, pub dofe_pred: dof_secidx_t, pub dofe_actions: dof_secidx_t, pub dofe_pad: u32, pub dofe_uarg: u64, } pub type dof_ecbdesc_t = dof_ecbdesc; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_probedesc { pub dofp_strtab: dof_secidx_t, pub dofp_provider: dof_stridx_t, pub dofp_mod: dof_stridx_t, pub dofp_func: dof_stridx_t, pub dofp_name: dof_stridx_t, pub dofp_id: u32, } pub type dof_probedesc_t = dof_probedesc; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_actdesc { pub dofa_difo: dof_secidx_t, pub dofa_strtab: dof_secidx_t, pub dofa_kind: u32, pub dofa_ntuple: u32, pub dofa_arg: u64, pub dofa_uarg: u64, } pub type dof_actdesc_t = dof_actdesc; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_difohdr { pub dofd_rtype: dtrace_diftype_t, pub dofd_links: [dof_secidx_t; 1usize], } pub type dof_difohdr_t = dof_difohdr; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_relohdr { pub dofr_strtab: dof_secidx_t, pub dofr_relsec: dof_secidx_t, pub dofr_tgtsec: dof_secidx_t, } pub type dof_relohdr_t = dof_relohdr; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_relodesc { pub dofr_name: dof_stridx_t, pub dofr_type: u32, pub dofr_offset: u64, pub dofr_data: u64, } pub type dof_relodesc_t = dof_relodesc; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_optdesc { pub dofo_option: u32, pub dofo_strtab: dof_secidx_t, pub dofo_value: u64, } pub type dof_optdesc_t = dof_optdesc; pub type dof_attr_t = u32; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_provider { pub dofpv_strtab: dof_secidx_t, pub dofpv_probes: dof_secidx_t, pub dofpv_prargs: dof_secidx_t, pub dofpv_proffs: dof_secidx_t, pub dofpv_name: dof_stridx_t, pub dofpv_provattr: dof_attr_t, pub dofpv_modattr: dof_attr_t, pub dofpv_funcattr: dof_attr_t, pub dofpv_nameattr: dof_attr_t, pub dofpv_argsattr: dof_attr_t, pub dofpv_prenoffs: dof_secidx_t, } pub type dof_provider_t = dof_provider; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_probe { pub dofpr_addr: u64, pub dofpr_func: dof_stridx_t, pub dofpr_name: dof_stridx_t, pub dofpr_nargv: dof_stridx_t, pub dofpr_xargv: dof_stridx_t, pub dofpr_argidx: u32, pub dofpr_offidx: u32, pub dofpr_nargc: u8, pub dofpr_xargc: u8, pub dofpr_noffs: u16, pub dofpr_enoffidx: u32, pub dofpr_nenoffs: u16, pub dofpr_pad1: u16, pub dofpr_pad2: u32, } pub type dof_probe_t = dof_probe; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_xlator { pub dofxl_members: dof_secidx_t, pub dofxl_strtab: dof_secidx_t, pub dofxl_argv: dof_stridx_t, pub dofxl_argc: u32, pub dofxl_type: dof_stridx_t, pub dofxl_attr: dof_attr_t, } pub type dof_xlator_t = dof_xlator; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_xlmember { pub dofxm_difo: dof_secidx_t, pub dofxm_name: dof_stridx_t, pub dofxm_type: dtrace_diftype_t, } pub type dof_xlmember_t = dof_xlmember; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dof_xlref { pub dofxr_xlator: dof_secidx_t, pub dofxr_member: u32, pub dofxr_argn: u32, } pub type dof_xlref_t = dof_xlref; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Copy, Clone)] pub struct dof_helper { pub dofhp_mod: [::std::os::raw::c_char; 64usize], pub dofhp_addr: u64, pub dofhp_dof: u64, #[cfg(target_os = "freebsd")] pub dofhp_pid: i32, #[cfg(target_os = "freebsd")] pub dofhp_gen: ::std::os::raw::c_int, } impl Default for dof_helper { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type dof_helper_t = dof_helper; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Copy, Clone)] pub struct dof_ioctl_data { pub dofiod_count: u64, pub dofiod_helpers: [dof_helper_t; 1usize], } impl Default for dof_ioctl_data { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type dof_ioctl_data_t = dof_ioctl_data; #[repr(C)] #[derive(Immutable, KnownLayout, IntoBytes, FromBytes, Debug, Default, Copy, Clone)] pub struct dt_node { pub _address: u8, }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/dof/src/fmt.rs
dof/src/fmt.rs
//! Functions to format types from DOF. // Copyright 2021 Oxide Computer Company // // 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. use crate::{des::RawSections, Section}; use crate::{dof_bindings::*, Error}; use pretty_hex::PrettyHex; use std::{fmt::Debug, mem::size_of}; use zerocopy::{FromBytes, Immutable, KnownLayout, Ref}; /// Format a DOF section into a pretty-printable string. pub fn fmt_dof_sec(sec: &dof_sec, index: usize) -> String { let mut ret = String::new(); ret.push_str(format!("DOF section {} ({:#x})\n", index, index).as_str()); ret.push_str( format!( " dofs_type: {} {}\n", sec.dofs_type, match sec.dofs_type { DOF_SECT_NONE => "(DOF_SECT_NONE)", DOF_SECT_COMMENTS => "(DOF_SECT_COMMENTS)", DOF_SECT_SOURCE => "(DOF_SECT_SOURCE)", DOF_SECT_ECBDESC => "(DOF_SECT_ECBDESC)", DOF_SECT_PROBEDESC => "(DOF_SECT_PROBEDESC)", DOF_SECT_ACTDESC => "(DOF_SECT_ACTDESC)", DOF_SECT_DIFOHDR => "(DOF_SECT_DIFOHDR)", DOF_SECT_DIF => "(DOF_SECT_DIF)", DOF_SECT_STRTAB => "(DOF_SECT_STRTAB)", DOF_SECT_VARTAB => "(DOF_SECT_VARTAB)", DOF_SECT_RELTAB => "(DOF_SECT_RELTAB)", DOF_SECT_TYPTAB => "(DOF_SECT_TYPTAB)", DOF_SECT_URELHDR => "(DOF_SECT_URELHDR)", DOF_SECT_KRELHDR => "(DOF_SECT_KRELHDR)", DOF_SECT_OPTDESC => "(DOF_SECT_OPTDESC)", DOF_SECT_PROVIDER => "(DOF_SECT_PROVIDER)", DOF_SECT_PROBES => "(DOF_SECT_PROBES)", DOF_SECT_PRARGS => "(DOF_SECT_PRARGS)", DOF_SECT_PROFFS => "(DOF_SECT_PROFFS)", DOF_SECT_INTTAB => "(DOF_SECT_INTTAB)", DOF_SECT_UTSNAME => "(DOF_SECT_UTSNAME)", DOF_SECT_XLTAB => "(DOF_SECT_XLTAB)", DOF_SECT_XLMEMBERS => "(DOF_SECT_XLMEMBERS)", DOF_SECT_XLIMPORT => "(DOF_SECT_XLIMPORT)", DOF_SECT_XLEXPORT => "(DOF_SECT_XLEXPORT)", DOF_SECT_PREXPORT => "(DOF_SECT_PREXPORT)", DOF_SECT_PRENOFFS => "(DOF_SECT_PRENOFFS)", _ => "(unknown)", } ) .as_str(), ); ret.push_str(format!(" dofs_align: {}\n", sec.dofs_align).as_str()); ret.push_str(format!(" dofs_flags: {}\n", sec.dofs_flags).as_str()); ret.push_str(format!(" dofs_entsize: {}\n", sec.dofs_entsize).as_str()); ret.push_str(format!(" dofs_offset: {}\n", sec.dofs_offset).as_str()); ret.push_str(format!(" dofs_size: {}\n", sec.dofs_size).as_str()); ret } /// Format the binary data from a DOF section into a pretty-printable hex string. pub fn fmt_dof_sec_data(sec: &dof_sec, data: &Vec<u8>) -> String { match sec.dofs_type { DOF_SECT_PROBES => fmt_dof_sec_type::<dof_probe>(data), DOF_SECT_RELTAB => fmt_dof_sec_type::<dof_relodesc>(data), DOF_SECT_URELHDR => fmt_dof_sec_type::<dof_relohdr>(data), DOF_SECT_PROVIDER => fmt_dof_sec_type::<dof_provider>(data), _ => format!("{:?}", data.hex_dump()), } } fn fmt_dof_sec_type<T: Debug + KnownLayout + Immutable + FromBytes + Copy>(data: &[u8]) -> String { data.chunks(size_of::<T>()) .map(|chunk| { let item = *Ref::<_, T>::from_bytes(chunk).unwrap(); format!("{:#x?}", item) }) .collect::<Vec<_>>() .join("\n") } /// Controls how DOF data is formatted #[derive(Clone, Copy)] pub enum FormatMode { // Emit Rust types used by the usdt crate Pretty, // Emit Rust types as json for parsing Json, /// Emit underlying DOF C types Raw { /// If true, the DOF section data is included, along with the section headers. /// If false, only the section headers are printed. include_sections: bool, }, } /// Format all DOF data in a collection of DOF sections into a pretty-printable string. /// /// Uses the `FormatMode` to determine how the data is formatted. pub fn fmt_dof(sections: Vec<Section>, format: FormatMode) -> Result<Option<String>, Error> { let mut out = String::new(); match format { FormatMode::Raw { include_sections } => { for section in sections.iter() { let RawSections { header, sections } = crate::des::deserialize_raw_sections(section.as_bytes().as_slice())?; out.push_str(&format!("{:#?}\n", header)); for (index, (section_header, data)) in sections.into_iter().enumerate() { out.push_str(&format!("{}\n", fmt_dof_sec(&section_header, index))); if include_sections { out.push_str(&format!("{}\n", fmt_dof_sec_data(&section_header, &data))); } } } } FormatMode::Json => { for section in sections.iter() { out.push_str(section.to_json().as_str()); } } FormatMode::Pretty => { for section in sections.iter() { out.push_str(&format!("{:#?}\n", section)); } } } if out.is_empty() { Ok(None) } else { Ok(Some(out)) } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/probe-test-attr/src/main.rs
probe-test-attr/src/main.rs
//! Example using the `usdt` crate, defining probes inline in Rust code which accept any //! serializable data type. // Copyright 2022 Oxide Computer Company // // 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. use serde::Serialize; /// By deriving the `serde::Serialize` trait, the `Arg` struct can be used as an argument to a /// DTrace probe. DTrace provides the `json` function, which accepts a JSON-encoded string and a /// (possibly-nested) key, and prints the corresponding value of the JSON object. For example, in /// this case one could use the DTrace snippet: /// /// ```bash /// $ dtrace -n 'stop { printf("arg.x = %s", json(copyinstr(arg1), "ok.x")); }' /// ``` /// /// to print the value of the `x` field. #[derive(Debug, Clone, Serialize)] pub struct Arg { x: u8, buffer: Vec<i32>, } /// Note that not all types are JSON serializable. The most common case is internally-tagged /// enums with a newtype variant, such as this type. Note that this will not break your program, /// but an error message will be transmitted to DTrace rather than a successfully-converted value. #[derive(Debug, Clone, Serialize)] #[serde(tag = "type")] pub enum Whoops { NoBueno(u8), } /// Providers may be defined directly in Rust code using the `usdt::provider` attribute. /// /// The attribute should be attached to a module, whose name becomes the provider name. The module /// can contain `use` statements to import any required items. Probe are defined as `fn`s, whose /// bodies must be empty. The types of the function are the types of the DTrace probe, assuming /// they are supported. /// /// Note that in most cases, writing the provider in Rust or a D script is equivalent. The main /// difference is in the support of serializable types. This can't be conveniently expressed in D, /// as data there is simply a string. So if you want to provide a probe with a more complex Rust /// type as an argument, it must be defined using this macro. #[usdt::provider] mod test { /// The `Arg` type needs to be imported here, just like in any other module. Note that you /// _must_ use an absolute import, such as `crate::Arg` or `::std::net::IpAddr`. Relative /// imports will generate a compiler error. The generated probe macros may be called from /// anywhere, meaning that those relative imports generally can't be resolved in the same way /// at the macro invocation site. use crate::Arg; /// Parameters may be given names, but these are only for documentation purposes. fn start_work(x: u8) {} /// Parameters need not have names, and may be taken by reference... fn stop_work(_: String, arg: &Arg) {} /// ... or by value fn stop_work_by_value(_: String, _: Arg) {} /// Probes usually contain standard path types, such as `u8` or `std::net::IpAddr`. However, /// they may also contain slices, arrays, tuples, and references. In these cases, as in the /// case of any non-native D type, the value will be JSON serialized when sending to DTrace. fn arg_as_tuple(_: (u8, &[i32])) {} /// Some types aren't JSON serializable. These will not break the program, but an error message /// will be seen in DTrace. fn not_json_serializable(_: crate::Whoops) {} /// Constant pointers to integer types are also supported fn work_with_pointer(_buffer: *const u8, _: u64) {} } fn main() { usdt::register_probes().unwrap(); let mut arg = Arg { x: 0, buffer: vec![1; 12], }; let buffer = [2; 4]; loop { test::start_work!(|| arg.x); std::thread::sleep(std::time::Duration::from_secs(1)); arg.x = arg.x.wrapping_add(1); test::stop_work!(|| { (format!("the probe has fired {}", arg.x), &arg) }); test::stop_work_by_value!(|| { let new_arg = Arg { x: arg.x, buffer: vec![arg.x.into()], }; (format!("the probe has fired {}", arg.x), new_arg) }); test::arg_as_tuple!(|| (arg.x, &arg.buffer[..])); test::not_json_serializable!(|| Whoops::NoBueno(0)); test::work_with_pointer!(|| (buffer.as_ptr(), buffer.len() as u64)); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt-attr-macro/src/lib.rs
usdt-attr-macro/src/lib.rs
//! Generate USDT probes from an attribute macro // Copyright 2024 Oxide Computer Company // // 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. use proc_macro2::TokenStream; use quote::quote; use serde_tokenstream::from_tokenstream; use syn::spanned::Spanned; use usdt_impl::{CompileProvidersConfig, DataType, Probe, Provider}; /// Generate a provider from functions defined in a Rust module. #[proc_macro_attribute] pub fn provider( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let attr = TokenStream::from(attr); match from_tokenstream::<CompileProvidersConfig>(&attr) { Ok(config) => { // Renaming the module via the attribute macro isn't supported. if config.module.is_some() { syn::Error::new( attr.span(), "The provider module may not be renamed via the attribute macro", ) .to_compile_error() .into() } else { generate_provider_item(TokenStream::from(item), config) .unwrap_or_else(|e| e.to_compile_error()) .into() } } Err(e) => e.to_compile_error().into(), } } // Generate the actual provider implementation, include the type-checks and probe macros. fn generate_provider_item( item: TokenStream, mut config: CompileProvidersConfig, ) -> Result<TokenStream, syn::Error> { let mod_ = syn::parse2::<syn::ItemMod>(item)?; if mod_.ident == "provider" { return Err(syn::Error::new( mod_.ident.span(), "Provider modules may not be named \"provider\"", )); } let content = &mod_ .content .as_ref() .ok_or_else(|| { syn::Error::new(mod_.span(), "Provider modules must have one or more probes") })? .1; let mut check_fns = Vec::new(); let mut probes = Vec::new(); let mut use_statements = Vec::new(); for (fn_index, item) in content.iter().enumerate() { match item { syn::Item::Fn(ref func) => { check_probe_name(&func.sig.ident)?; let signature = check_probe_function_signature(&func.sig)?; let mut item_check_fns = Vec::new(); let mut item_types = Vec::new(); for (arg_index, arg) in signature.inputs.iter().enumerate() { match arg { syn::FnArg::Receiver(item) => { return Err(syn::Error::new( item.span(), "Probe functions may not take Self", )); } syn::FnArg::Typed(ref item) => { let (maybe_check_fn, item_type) = parse_probe_argument(&item.ty, fn_index, arg_index)?; if let Some(check_fn) = maybe_check_fn { item_check_fns.push(check_fn); } item_types.push(item_type); } } } check_fns.extend(item_check_fns); probes.push(Probe { name: signature.ident.to_string(), types: item_types, }); } syn::Item::Use(ref use_statement) => { verify_use_tree(&use_statement.tree)?; use_statements.push(use_statement.clone()); } _ => { return Err(syn::Error::new( item.span(), "Provider modules may only include empty functions or use statements", )); } } } // We're guaranteed that the module name in the config is None. If the user has set the // provider name there, extract it. If they have _not_ set the provider name there, extract the // module name. In both cases, we don't support renaming the module via this path, so the // module name is passed through. let name = match &config.provider { Some(name) => { let name = name.to_string(); config.module = Some(mod_.ident.to_string()); name } None => { let name = mod_.ident.to_string(); config.provider = Some(name.clone()); config.module = Some(name.clone()); name } }; let provider = Provider { name, probes, use_statements: use_statements.clone(), }; let compiled = usdt_impl::compile_provider(&provider, &config); let type_checks = if check_fns.is_empty() { quote! { const _: fn() = || {}; } } else { quote! { const _: fn() = || { #(#use_statements)* fn usdt_types_must_be_serialize<T: ?Sized + ::serde::Serialize>() {} #(#check_fns)* }; } }; Ok(quote! { #type_checks #compiled }) } fn check_probe_name(ident: &syn::Ident) -> syn::Result<()> { let check = |name| { if ident == name { Err(syn::Error::new( ident.span(), format!("Probe functions may not be named \"{}\"", name), )) } else { Ok(()) } }; check("probe").and(check("start")) } fn parse_probe_argument( item: &syn::Type, fn_index: usize, arg_index: usize, ) -> syn::Result<(Option<TokenStream>, DataType)> { match item { syn::Type::Path(ref path) => { let last_ident = &path .path .segments .last() .ok_or_else(|| { syn::Error::new(path.span(), "Probe arguments should resolve to path types") })? .ident; if is_simple_type(last_ident) { Ok((None, data_type_from_path(&path.path, false))) } else if last_ident == "UniqueId" { Ok((None, DataType::UniqueId)) } else { let check_fn = build_serializable_check_function(item, fn_index, arg_index); Ok((Some(check_fn), DataType::Serializable(item.clone()))) } } syn::Type::Ptr(ref pointer) => { if pointer.mutability.is_some() { return Err(syn::Error::new(item.span(), "Pointer types must be const")); } let ty = &*pointer.elem; if let syn::Type::Path(ref path) = ty { let last_ident = &path .path .segments .last() .ok_or_else(|| { syn::Error::new(path.span(), "Probe arguments should resolve to path types") })? .ident; if !is_integer_type(last_ident) { return Err(syn::Error::new( item.span(), "Only pointers to integer types are supported", )); } Ok((None, data_type_from_path(&path.path, true))) } else { Err(syn::Error::new( item.span(), "Only pointers to path types are supported", )) } } syn::Type::Reference(ref reference) => { match parse_probe_argument(&reference.elem, fn_index, arg_index)? { (None, DataType::UniqueId) => Ok((None, DataType::UniqueId)), (None, DataType::Native(ty)) => Ok((None, DataType::Native(ty))), _ => Ok(( Some(build_serializable_check_function(item, fn_index, arg_index)), DataType::Serializable(item.clone()), )), } } syn::Type::Array(_) | syn::Type::Slice(_) | syn::Type::Tuple(_) => { let check_fn = build_serializable_check_function(item, fn_index, arg_index); Ok((Some(check_fn), DataType::Serializable(item.clone()))) } _ => Err(syn::Error::new( item.span(), concat!( "Probe arguments must be path types, slices, arrays, tuples, ", "references, or const pointers to integers", ), )), } } fn verify_use_tree(tree: &syn::UseTree) -> syn::Result<()> { match tree { syn::UseTree::Path(ref path) => { if path.ident == "super" { return Err(syn::Error::new( path.span(), concat!( "Use-statements in USDT macros cannot contain relative imports (`super`), ", "because the generated macros may be called from anywhere in a crate. ", "Consider using `crate` instead.", ), )); } verify_use_tree(&path.tree) } _ => Ok(()), } } // Create a function that statically asserts the given identifier implements `Serialize`. fn build_serializable_check_function<T>(ident: &T, fn_index: usize, arg_index: usize) -> TokenStream where T: quote::ToTokens, { let fn_name = quote::format_ident!("usdt_types_must_be_serialize_{}_{}", fn_index, arg_index); quote! { fn #fn_name() { // #ident must be in scope here, because this function is defined in the same module as // the actual probe functions, and thus shares any imports the consumer wants. usdt_types_must_be_serialize::<#ident>() } } } // Return `true` if the type is an integer fn is_integer_type(ident: &syn::Ident) -> bool { let ident = format!("{}", ident); matches!( ident.as_str(), "u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" ) } // Return `true` if this type is "simple", a primitive type with an analog in D, i.e., _not_ a // type that implements `Serialize`. fn is_simple_type(ident: &syn::Ident) -> bool { let ident = format!("{}", ident); matches!( ident.as_str(), "u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" | "String" | "str" | "usize" | "isize" ) } // Return the `dtrace_parser::DataType` corresponding to the given `path` fn data_type_from_path(path: &syn::Path, pointer: bool) -> DataType { use dtrace_parser::BitWidth; use dtrace_parser::DataType as DType; use dtrace_parser::Integer; use dtrace_parser::Sign; let variant = if pointer { DType::Pointer } else { DType::Integer }; if path.is_ident("u8") { DataType::Native(variant(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })) } else if path.is_ident("u16") { DataType::Native(variant(Integer { sign: Sign::Unsigned, width: BitWidth::Bit16, })) } else if path.is_ident("u32") { DataType::Native(variant(Integer { sign: Sign::Unsigned, width: BitWidth::Bit32, })) } else if path.is_ident("u64") { DataType::Native(variant(Integer { sign: Sign::Unsigned, width: BitWidth::Bit64, })) } else if path.is_ident("i8") { DataType::Native(variant(Integer { sign: Sign::Signed, width: BitWidth::Bit8, })) } else if path.is_ident("i16") { DataType::Native(variant(Integer { sign: Sign::Signed, width: BitWidth::Bit16, })) } else if path.is_ident("i32") { DataType::Native(variant(Integer { sign: Sign::Signed, width: BitWidth::Bit32, })) } else if path.is_ident("i64") { DataType::Native(variant(Integer { sign: Sign::Signed, width: BitWidth::Bit64, })) } else if path.is_ident("String") || path.is_ident("str") { DataType::Native(DType::String) } else if path.is_ident("isize") { DataType::Native(variant(Integer { sign: Sign::Signed, width: BitWidth::Pointer, })) } else if path.is_ident("usize") { DataType::Native(variant(Integer { sign: Sign::Unsigned, width: BitWidth::Pointer, })) } else { unreachable!("Tried to parse a non-path data type"); } } // Sanity checks on a probe function signature. fn check_probe_function_signature( signature: &syn::Signature, ) -> Result<&syn::Signature, syn::Error> { let to_err = |span, msg| Err(syn::Error::new(span, msg)); if let Some(item) = signature.unsafety { return to_err(item.span(), "Probe functions may not be unsafe"); } if let Some(ref item) = signature.abi { return to_err(item.span(), "Probe functions may not specify an ABI"); } if let Some(ref item) = signature.asyncness { return to_err(item.span(), "Probe functions may not be async"); } if !signature.generics.params.is_empty() { return to_err( signature.generics.span(), "Probe functions may not be generic", ); } if !matches!(signature.output, syn::ReturnType::Default) { return to_err( signature.output.span(), "Probe functions may not specify a return type", ); } Ok(signature) } #[cfg(test)] mod tests { use super::*; use dtrace_parser::BitWidth; use dtrace_parser::DataType as DType; use dtrace_parser::Integer; use dtrace_parser::Sign; use rstest::rstest; #[test] fn test_is_simple_type() { assert!(is_simple_type(&quote::format_ident!("u8"))); assert!(!is_simple_type(&quote::format_ident!("Foo"))); } #[test] fn test_data_type_from_path() { assert_eq!( data_type_from_path(&syn::parse_str("u8").unwrap(), false), DataType::Native(DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), ); assert_eq!( data_type_from_path(&syn::parse_str("u8").unwrap(), true), DataType::Native(DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8, })), ); assert_eq!( data_type_from_path(&syn::parse_str("String").unwrap(), false), DataType::Native(DType::String), ); assert_eq!( data_type_from_path(&syn::parse_str("String").unwrap(), false), DataType::Native(DType::String), ); } #[test] #[should_panic] fn test_data_type_from_path_panics() { data_type_from_path(&syn::parse_str("std::net::IpAddr").unwrap(), false); } #[rstest] #[case("u8", DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8 }))] #[case("*const u8", DType::Pointer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8}))] #[case("&u8", DType::Integer(Integer { sign: Sign::Unsigned, width: BitWidth::Bit8 }))] #[case("&str", DType::String)] #[case("String", DType::String)] #[case("&&str", DType::String)] #[case("&String", DType::String)] fn test_parse_probe_argument_native(#[case] name: &str, #[case] ty: dtrace_parser::DataType) { let arg = syn::parse_str(name).unwrap(); let out = parse_probe_argument(&arg, 0, 0).unwrap(); assert!(out.0.is_none()); assert_eq!(out.1, DataType::Native(ty)); } #[rstest] #[case("usdt::UniqueId")] #[case("&usdt::UniqueId")] fn test_parse_probe_argument_span(#[case] arg: &str) { let ty = syn::parse_str(arg).unwrap(); let out = parse_probe_argument(&ty, 0, 0).unwrap(); assert!(out.0.is_none()); assert_eq!(out.1, DataType::UniqueId) } #[rstest] #[case("std::net::IpAddr")] #[case("&std::net::IpAddr")] #[case("&SomeType")] #[case("&&[u8]")] fn test_parse_probe_argument_serializable(#[case] name: &str) { let ty = syn::parse_str(name).unwrap(); let out = parse_probe_argument(&ty, 0, 0).unwrap(); assert!(out.0.is_some()); assert_eq!(out.1, DataType::Serializable(ty)); if let (Some(chk), DataType::Serializable(ty)) = out { println!("{}", quote! { #chk }); println!("{}", quote! { #ty }); } } #[test] fn test_check_probe_function_signature() { let signature = syn::parse_str::<syn::Signature>("fn foo(_: u8)").unwrap(); assert!(check_probe_function_signature(&signature).is_ok()); let check_is_err = |s| { let signature = syn::parse_str::<syn::Signature>(s).unwrap(); assert!(check_probe_function_signature(&signature).is_err()); }; check_is_err("unsafe fn foo(_: u8)"); check_is_err(r#"extern "C" fn foo(_: u8)"#); check_is_err("fn foo<T: Debug>(_: u8)"); check_is_err("fn foo(_: u8) -> u8"); } #[test] fn test_verify_use_tree() { let tokens = quote! { use std::net::IpAddr; }; let item: syn::ItemUse = syn::parse2(tokens).unwrap(); assert!(verify_use_tree(&item.tree).is_ok()); let tokens = quote! { use super::SomeType; }; let item: syn::ItemUse = syn::parse2(tokens).unwrap(); assert!(verify_use_tree(&item.tree).is_err()); let tokens = quote! { use crate::super::SomeType; }; let item: syn::ItemUse = syn::parse2(tokens).unwrap(); assert!(verify_use_tree(&item.tree).is_err()); } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
oxidecomputer/usdt
https://github.com/oxidecomputer/usdt/blob/709b613326d26ace9168c923b03c752aeef505f2/usdt/src/lib.rs
usdt/src/lib.rs
// Copyright 2022 Oxide Computer Company // // 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. //! Expose USDT probe points from Rust programs. //! //! Overview //! -------- //! //! This crate provides methods for compiling definitions of [DTrace probes][dtrace] into Rust //! code, allowing rich, low-overhead instrumentation of [userland][dtrace-usdt] Rust programs. //! //! DTrace _probes_ are instrumented points in software, usually corresponding to some important //! event such as opening a file, writing to standard output, acquiring a lock, and much more. //! Probes are grouped into _providers_, collections of related probes covering distinct classes //! functionality. The _syscall_ provider, for example, includes probes for the entry and exit of //! certain important system calls, such as `write(2)`. //! //! USDT probes may be defined in the [D language](#defining-probes-in-d) or [inline in Rust //! code](#inline-rust-probes). These definitions are used to create macros, which, when called, //! fire the corresponding DTrace probe. The two methods for defining probes are very similar -- //! one key difference, besides the syntax used to describe them, is that inline probes support any //! Rust type that is JSON serializable. We'll cover each in turn. //! //! Defining probes in D //! -------------------- //! //! Users define a provider, with one or more _probe_ functions in the D language. For example: //! //! ```d //! provider my_provider { //! probe start_work(uint8_t); //! probe start_work(char*, uint8_t); //! }; //! ``` //! //! Providers and probes may be named in any way, as long as they form valid Rust identifiers. The //! names are intended to help understand the behavior of a program, so they should be semantically //! meaningful. Probes accept zero or more arguments, data that is associated with the probe event //! itself (timestamps, file descriptors, filesystem paths, etc.). The arguments may be specified //! as any of the exact bit-width integer types (e.g., `int16_t`), pointers to //! such integers, or strings (`char *`s). See [Data types](#data-types) for a full list of //! supported types. //! //! Assuming the above is in a file called `"test.d"`, the probes may be compiled into Rust code //! with: //! //! ```ignore //! usdt::dtrace_provider!("test.d"); //! ``` //! //! This procedural macro will generate a Rust macro for each probe defined in the provider. Note //! that for versions of rust prior to 1.66 features may be required; see [the //! notes](#features) for a discussion. The invocation of `dtrace_provider` (and any required //! feature directives) **should be at the crate root**, i.e., `src/lib.rs` or `src/main.rs`. //! //! One may then call the `start` probe via: //! //! ```ignore //! let x: u8 = 0; //! my_provider::start_work!(|| x); //! ``` //! //! We can see that the macros are defined in a module named by the provider, with one macro for //! each probe, with the same name. See [below](#configurable-names) for how this naming may be //! configured. //! //! Note that `start_work!` is called with a closure which returns the arguments, rather than the //! actual arguments themselves. See [below](#probe-arguments) for details. Additionally, as the //! probes are exposed as _macros_, they should be included in the crate root, before any other //! module or item which references them. //! //! After declaring probes and converting them into Rust code, they must be _registered_ with the //! DTrace kernel module. Developers should call the function [`register_probes`] as soon as //! possible in the execution of their program to ensure that probes are available. At this point, //! the probes should be visible from the `dtrace(1)` command-line tool, and can be enabled or //! acted upon like any other probe. See [registration](#registration) for a discussion of probe //! registration, especially in the context of library crates. //! //! Inline Rust probes //! ------------------ //! //! Writing probes in the D language is convenient and familiar to those who've previously used //! DTrace. There are a few drawbacks though. Maintaining another file may be annoying or error //! prone, but more importantly, it provides limited support for Rust's rich type system. In //! particular, only those types with a clear C analog are currently supported. (See [the full //! list](#data-types).) //! //! More complex, user-defined types can be supported if one defines the probes in Rust directly. //! In particular, this crate supports any type implementing [`serde::Serialize`][serde], by //! serializing the type to JSON and using DTrace's native [JSON support][dtrace-json]. Providers //! can be defined inline by attaching the [`provider`] attribute macro to a module. //! //! ```rust,ignore //! #[derive(serde::Serialize)] //! pub struct Arg { //! pub x: u8, //! pub buffer: Vec<i32>, //! } //! //! // A module named `test` describes the provider, and each (empty) function definition in the //! // module's body generates a probe macro. //! #[usdt::provider] //! mod test { //! use crate::Arg; //! fn start_work(x: u8) {} //! fn stop_work(arg: &Arg) {} //! } //! ``` //! //! The `arg` parameter to the `stop` probe will be converted into JSON, and its fields may be //! accessed in DTrace with the `json` function. The signature is `json(string, key)`, where `key` //! is used to access the named key of a JSON-encoded string. For example: //! //! ```console //! $ dtrace -n 'stop_work { printf("%s", json(copyinstr(arg0), "ok.buffer[0]")); }' //! ``` //! //! would print the first element of the vector `Arg::buffer`. //! //! > **Important**: Notice that the JSON key used in the above example to access the data inside //! DTrace is `"ok.buffer[0]"`. JSON values serialized to DTrace are always `Result` types, //! because the internal serialization method is _fallible_. So they are always encoded as objects //! like `{"ok": _}` or `{"err": "some error message"}`. In the error case, the message is //! created by formatting the `serde_json::error::Error` that describes why serialization failed. //! //! > **Note**: It's not possible to define probes in D that accept a serializable type, because the //! corresponding C type is just `char *`. There's currently no way to disambiguate such a type //! from an actual string, when generating the Rust probe macros. //! //! See the [probe_test_attr] example for a complete example implementing probes in Rust. //! //! ## Configurable names //! //! When using the attribute macro or build.rs versions of the code-generator, the names of the //! provider and/or probes may be configured. Specifically, the `probe_format` argument to the //! attribute macro or `Builder` method sets a format string used to generate the names of the //! probe macros. This can be any string, and will have the keys `{provider}` and `{probe}` //! interpolated to the actual names of the provider and probe. As an example, consider a provider //! named `foo` with a probe named `bar`, and a format string of `probe_{provider}_{probe}` -- the //! name of the generated probe macro will be `probe_foo_bar`. //! //! In addition, when using the attribute macro version, the name of the _provider_ as seen by //! DTrace can be configured. This defaults to the name of the provider module. For example, //! consider a module like this: //! //! ```ignore //! #[usdt::provider(provider = "foo")] //! mod probes { //! fn bar() {} //! } //! ``` //! //! The probe `bar` will appear in DTrace as `foo:::bar`, and will be accessible in Rust via the //! macro `probes::bar!`. Note that it's not possible to rename the probe module when using the //! attribute macro version. //! //! Conversely, one can change the name of the generated provider _module_ when using the builder //! version, but not the name of the provider as it appears to DTrace. Given a file `"test.d"` that //! names a provider `foo` and a probe `bar`, consider this code: //! //! ```ignore //! usdt::Builder::new("test.d") //! .module("probes") //! .build() //! .unwrap(); //! ``` //! //! This probe `bar` will appear in DTrace as `foo:::bar`, but will now be accessible in Rust via //! the macro `probes::bar!`. Note that it's not possible to rename the provider as it appears in //! DTrace when using the builder version. //! //! Double-underscores //! ------------------ //! //! It's a DTrace convention to name probes with dashes between words, rather than underscores. So //! the probe should be `my-probe` rather than `my_probe`. The former is not a valid Rust //! identifier, but can be achieved by using _two_ underscores in the **probe** name. This crate //! internally translates `__` into `-` in such cases. For example, the provider: //! //! ```ignore //! #[usdt::provider("my__provider")] //! mod probes { //! fn my__probe() {}; //! } //! ``` //! //! will result in a provider and probe name of `my__provider` and `my-probe`. //! **Important:** This translation of double-underscores to dashes only occurs //! in the _probe_ name. Provider names are _not_ modified in any way. This //! matches the behavior of existing DTrace implementations, and guarantees that //! providers are similarly named regardless of the target platform. //! //! Examples //! -------- //! //! See the [probe_test_macro], [probe_test_build], and [probe_test_attr] crates in the github repo //! for detailed working examples showing how the probes may be defined, included, and used. //! //! Probe arguments //! --------------- //! //! Note that the probe macro is called with a closure which returns the actual arguments. There //! are two reasons for this. First, it makes clear that the probe may not be evaluated if it is //! not enabled; the arguments should not include function calls which are relied upon for their //! side-effects, for example. Secondly, it is more efficient. As the lambda is only called if the //! probe is actually enabled, this allows passing arguments to the probe that are potentially //! expensive to construct. However, this cost will only be incurred if the probe is actually //! enabled. //! //! Data types //! ---------- //! //! Probes support any of the integer types which have a specific bit-width, e.g., `uint16_t`, as //! well as strings, which should be specified as `char *`. As described [above](#inline-rust-probes), //! any types implementing `Serialize` may be used, if the probes are defined in Rust directly. //! //! Below is the full list of supported types. //! //! - `(u?)int(8|16|32|64)_t` //! - Pointers to the above integer types //! - `char *` //! - `T: serde::Serialize` (Only when defining probes in Rust) //! //! Currently, up to six (6) arguments are supported, though this limitation may be lifted in the //! future. //! //! Registration //! ------------ //! //! USDT probes must be registered with the DTrace kernel module. This is done via a call to the //! [`register_probes`] function, which must be called before any of the probes become available to //! DTrace. Ideally, this would be done automatically; however, while there are methods by which //! that could be achieved, they all pose significant concerns around safety, clarity, and/or //! explicitness. //! //! At this point, it is incumbent upon the _application_ developer to ensure that //! `register_probes` is called appropriately. This will register all probes in an application, //! including those defined in a library dependency. To avoid foisting an explicit dependency on //! the `usdt` crate on downstream applications, library writers should re-export the //! `register_probes` function with: //! //! ``` //! pub use usdt::register_probes; //! ``` //! //! The library should clearly document that it defines and uses USDT probes, and that this //! function should be called by an application. Alternatively, library developers may call this //! function during some initialization routines required by their library. There is no harm in //! calling this method multiple times, even in concurrent situations. //! //! Unique IDs //! ---------- //! //! A common pattern in DTrace scripts is to use a two or more probes to understand a section or //! span of code. For example, the `syscall:::{entry,return}` probes can be used to time the //! duration of system calls. Doing this with USDT probes requires a unique identifier, so that //! multiple probes can be correlated with one another. The [`UniqueId`] type can be used for this //! purpose. It may be passed as any argument to a probe function, and is guaranteed to be unique //! between different invocations of the same probe. See the type's documentation for details. //! //! About the `asm` feature //! ----------------------- //! //! Previous versions of `usdt` used the `asm` feature to enable inline assembly which used to //! require nightly Rust with old versions of Rust. Currently, all supported versions of Rust //! support inline assembly, and the `asm` feature is a no-op. //! //! The next breaking change to `usdt` will remove the `asm` feature entirely. //! //! [dtrace]: https://illumos.org/books/dtrace/preface.html#preface //! [dtrace-usdt]: https://illumos.org/books/dtrace/chp-usdt.html#chp-usdt //! [dtrace-json]: https://sysmgr.org/blog/2012/11/29/dtrace_and_json_together_at_last/ //! [probe_test_macro]: https://github.com/oxidecomputer/usdt/tree/master/probe-test-macro //! [probe_test_build]: https://github.com/oxidecomputer/usdt/tree/master/probe-test-build //! [probe_test_attr]: https://github.com/oxidecomputer/usdt/tree/master/probe-test-attr //! [serde]: https://serde.rs use dof::{extract_dof_sections, Section}; use goblin::Object; use memmap2::{Mmap, MmapOptions}; use std::fs::{File, OpenOptions}; use std::path::{Path, PathBuf}; use std::{env, fs}; pub use usdt_attr_macro::provider; #[doc(hidden)] pub use usdt_impl::to_json; pub use usdt_impl::{Error, UniqueId}; pub use usdt_macro::dtrace_provider; /// A simple struct used to build DTrace probes into Rust code in a build.rs script. #[derive(Debug)] pub struct Builder { source_file: PathBuf, out_file: PathBuf, config: usdt_impl::CompileProvidersConfig, } impl Builder { /// Construct a new builder from a path to a D provider definition file. pub fn new<P: AsRef<Path>>(file: P) -> Self { let source_file = file.as_ref().to_path_buf(); let mut out_file = source_file.clone(); out_file.set_extension("rs"); Builder { source_file, out_file, config: usdt_impl::CompileProvidersConfig::default(), } } /// Set the output filename of the generated Rust code. The default has the same stem as the /// provider file, with the `".rs"` extension. pub fn out_file<P: AsRef<Path>>(mut self, file: P) -> Self { self.out_file = file.as_ref().to_path_buf(); self.out_file.set_extension("rs"); self } /// Set the format for the name of generated probe macros. /// /// The provided format may include the tokens `{provider}` and `{probe}`, which will be /// substituted with the names of the provider and probe. The default is `"{probe}"`. pub fn probe_format(mut self, format: &str) -> Self { self.config.probe_format = Some(format.to_string()); self } /// Set the name of the module containing the generated probe macros. pub fn module(mut self, module: &str) -> Self { self.config.module = Some(module.to_string()); self } /// Generate the Rust code from the D provider file, writing the result to the output file. pub fn build(self) -> Result<(), Error> { let source = fs::read_to_string(self.source_file)?; let tokens = usdt_impl::compile_provider_source(&source, &self.config)?; let mut out_file = Path::new(&env::var("OUT_DIR")?).to_path_buf(); out_file.push( self.out_file .file_name() .expect("Could not extract filename"), ); fs::write(out_file, tokens.to_string().as_bytes())?; Ok(()) } } /// Register an application's probes with DTrace. /// /// This function collects the probes defined in an application, and forwards them to the DTrace /// kernel module. This _must_ be done for the probes to be visible via the `dtrace(1)` tool. See /// [probe_test_macro] for a detailed example. /// /// Notes /// ----- /// /// This function registers all probes in a process's binary image, regardless of which crate /// actually defines the probes. It's also safe to call this function multiple times, even in /// concurrent situations. Probes will be registered at most once. /// /// [probe_test_macro]: https://github.com/oxidecomputer/usdt/tree/master/probe-test-macro pub fn register_probes() -> Result<(), Error> { usdt_impl::register_probes() } /// Extract embedded USDT probe records from a file. /// /// DTrace in general works by storing metadata about the probes in a special /// section of the resulting binaries. These sections are generated by the /// platform compiler and linker on systems with linker support (macOS), or /// created manually by this crate on other platforms. In either case, this /// method extracts the metadata as a [`Section`] from the object file, if it /// can be found. pub fn probe_records<P: AsRef<Path>>(path: P) -> Result<Vec<Section>, Error> { // Extract DOF section data, which is applicable for an object file built using this crate on // macOS, or generally using the platform's dtrace tool, i.e., `dtrace -G` and compiler. let dof_sections = extract_dof_sections(&path).map_err(|_| Error::InvalidFile)?; if !dof_sections.is_empty() { return Ok(dof_sections); } // File contains no DOF data. Try to parse out the ASM records inserted by the `usdt` crate. let file = OpenOptions::new().read(true).create(false).open(path)?; let (offset, len) = locate_probe_section(&file).ok_or(Error::InvalidFile)?; // Remap only the probe section itself as mutable, using a private // copy-on-write mapping to avoid writing to disk in any circumstance. let mut map = unsafe { MmapOptions::new().offset(offset).len(len).map_copy(&file)? }; usdt_impl::record::process_section(&mut map, /* register = */ false).map(|s| vec![s]) } // Return the offset and size of the file's probe record section, if it exists. fn locate_probe_section(file: &File) -> Option<(u64, usize)> { let map = unsafe { Mmap::map(file) }.ok()?; match Object::parse(&map).ok()? { Object::Elf(object) => { // Try to find our special `set_dtrace_probes` section from the section headers. These // may not exist, e.g., if the file has been stripped. In that case, we look for the // special __start and __stop symbols themselves. if let Some(section) = object.section_headers.iter().find(|header| { if let Some(name) = object.shdr_strtab.get_at(header.sh_name) { name == "set_dtrace_probes" } else { false } }) { Some((section.sh_offset, section.sh_size as usize)) } else { // Failed to look up the section directly, iterate over the symbols. let mut bounds = object.syms.iter().filter(|symbol| { matches!( object.strtab.get_at(symbol.st_name), Some("__start_set_dtrace_probes") | Some("__stop_set_dtrace_probes") ) }); if let (Some(start), Some(stop)) = (bounds.next(), bounds.next()) { Some((start.st_value, (stop.st_value - start.st_value) as usize)) } else { None } } } Object::Mach(goblin::mach::Mach::Binary(object)) => { // Try to find our special `__dtrace_probes` section from the section headers. for (section, _) in object.segments.sections().flatten().flatten() { if section.sectname.starts_with(b"__dtrace_probes") { return Some((section.offset as u64, section.size as usize)); } } // Failed to look up the section directly, iterate over the symbols. if let Some(syms) = object.symbols { let mut bounds = syms.iter().filter_map(|symbol| { if let Ok((name, nlist)) = symbol { if name.contains("__dtrace_probes") { Some(nlist.n_value) } else { None } } else { None } }); if let (Some(start), Some(stop)) = (bounds.next(), bounds.next()) { Some((start, (stop - start) as usize)) } else { None } } else { None } } _ => None, } }
rust
Apache-2.0
709b613326d26ace9168c923b03c752aeef505f2
2026-01-04T20:24:42.431196Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/errors.rs
src/errors.rs
//! All the errors that can be caused by this crate. use std::sync::Arc; use miette::Diagnostic; use thiserror::Error; use tokio::sync::mpsc; use crate::ErrTypeTraits; /// This enum contains all the possible errors that could be returned /// by [`handle_shutdown_requests()`](crate::Toplevel::handle_shutdown_requests). #[derive(Debug, Error, Diagnostic)] pub enum GracefulShutdownError<ErrType: ErrTypeTraits = crate::BoxedError> { /// At least one subsystem caused an error. #[diagnostic(code(graceful_shutdown::failed))] #[error("at least one subsystem returned an error")] SubsystemsFailed(#[related] Box<[SubsystemError<ErrType>]>), /// The shutdown did not finish within the given timeout. #[diagnostic(code(graceful_shutdown::timeout))] #[error("shutdown timed out")] ShutdownTimeout(#[related] Box<[SubsystemError<ErrType>]>), } impl<ErrType: ErrTypeTraits> GracefulShutdownError<ErrType> { /// Converts the error into a list of subsystem errors that occurred. pub fn into_subsystem_errors(self) -> Box<[SubsystemError<ErrType>]> { match self { GracefulShutdownError::SubsystemsFailed(rel) => rel, GracefulShutdownError::ShutdownTimeout(rel) => rel, } } /// Queries the list of subsystem errors that occurred. pub fn get_subsystem_errors(&self) -> &[SubsystemError<ErrType>] { match self { GracefulShutdownError::SubsystemsFailed(rel) => rel, GracefulShutdownError::ShutdownTimeout(rel) => rel, } } } /// This enum contains all the possible errors that joining a subsystem /// could cause. #[derive(Debug, Error, Diagnostic)] pub enum SubsystemJoinError<ErrType: ErrTypeTraits = crate::BoxedError> { /// At least one subsystem caused an error. #[diagnostic(code(graceful_shutdown::subsystem_join::failed))] #[error("at least one subsystem returned an error")] SubsystemsFailed(#[related] Arc<[SubsystemError<ErrType>]>), } /// A wrapper type that carries the errors returned by subsystems. pub struct SubsystemFailure<ErrType>(pub(crate) ErrType); impl<ErrType> std::ops::Deref for SubsystemFailure<ErrType> { type Target = ErrType; fn deref(&self) -> &Self::Target { &self.0 } } impl<ErrType> SubsystemFailure<ErrType> { /// Retrieves the containing error. pub fn get_error(&self) -> &ErrType { &self.0 } /// Converts the object into the containing error. pub fn into_error(self) -> ErrType { self.0 } } impl<ErrType> std::fmt::Debug for SubsystemFailure<ErrType> where ErrType: std::fmt::Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(&self.0, f) } } impl<ErrType> std::fmt::Display for SubsystemFailure<ErrType> where ErrType: std::fmt::Display, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.0, f) } } impl<ErrType> std::error::Error for SubsystemFailure<ErrType> where ErrType: std::fmt::Display + std::fmt::Debug { } /// This enum contains all the possible errors that a subsystem execution /// could cause. /// /// Every error carries the name of the subsystem as the first argument. #[derive(Debug, Error, Diagnostic)] pub enum SubsystemError<ErrType: ErrTypeTraits = crate::BoxedError> { /// The subsystem returned an error value. Carries the actual error as the second argument. #[diagnostic(code(graceful_shutdown::subsystem::failed))] #[error("Error in subsystem '{0}'")] Failed(Arc<str>, #[source] SubsystemFailure<ErrType>), /// The subsystem panicked. #[diagnostic(code(graceful_shutdown::subsystem::panicked))] #[error("Subsystem '{0}' panicked")] Panicked(Arc<str>), } impl<ErrType: ErrTypeTraits> SubsystemError<ErrType> { /// Retrieves the name of the subsystem that caused the error. /// /// # Returns /// /// The name of the subsystem pub fn name(&self) -> &str { match self { SubsystemError::Failed(name, _) => name, SubsystemError::Panicked(name) => name, } } } /// The error that happens when a task gets cancelled through /// [`cancel_on_shutdown()`](crate::FutureExt::cancel_on_shutdown). #[derive(Error, Debug, Diagnostic)] #[error("A shutdown request caused this task to be cancelled")] #[diagnostic(code(graceful_shutdown::future::cancelled_by_shutdown))] pub struct CancelledByShutdown; // This function contains code that stems from the principle // of defensive coding - meaning, handle potential errors // gracefully, even if they should not happen. // Therefore it is in this special function, so we don't // get coverage problems. pub(crate) fn handle_dropped_error<ErrType: ErrTypeTraits>( result: Result<(), mpsc::error::SendError<ErrType>>, ) { if let Err(mpsc::error::SendError(e)) = result { tracing::warn!("An error got dropped: {e:?}"); } } // This function contains code that stems from the principle // of defensive coding - meaning, handle potential errors // gracefully, even if they should not happen. // Therefore it is in this special function, so we don't // get coverage problems. pub(crate) fn handle_unhandled_stopreason<ErrType: ErrTypeTraits>( maybe_stop_reason: Option<SubsystemError<ErrType>>, ) { if let Some(stop_reason) = maybe_stop_reason { tracing::warn!("Unhandled stop reason: {:?}", stop_reason); } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/signal_handling.rs
src/signal_handling.rs
use std::io; /// Creates a future that waits for a signal that requests a graceful shutdown, like SIGTERM or SIGINT. #[cfg(unix)] fn register_signals_impl() -> io::Result<impl Future<Output = ()>> { use tokio::signal::unix::{SignalKind, signal}; // Infos here: // https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html let mut signal_terminate = signal(SignalKind::terminate())?; let mut signal_interrupt = signal(SignalKind::interrupt())?; Ok(async move { tokio::select! { _ = signal_terminate.recv() => tracing::debug!("Received SIGTERM."), _ = signal_interrupt.recv() => tracing::debug!("Received SIGINT."), } }) } /// Creates a future that waits for a signal that requests a graceful shutdown, like Ctrl-C (SIGINT). #[cfg(windows)] fn register_signals_impl() -> io::Result<impl Future<Output = ()>> { use tokio::signal::windows; // Infos here: // https://learn.microsoft.com/en-us/windows/console/handlerroutine let mut signal_c = windows::ctrl_c()?; let mut signal_break = windows::ctrl_break()?; let mut signal_close = windows::ctrl_close()?; let mut signal_shutdown = windows::ctrl_shutdown()?; Ok(async move { tokio::select! { _ = signal_c.recv() => tracing::debug!("Received CTRL_C."), _ = signal_break.recv() => tracing::debug!("Received CTRL_BREAK."), _ = signal_close.recv() => tracing::debug!("Received CTRL_CLOSE."), _ = signal_shutdown.recv() => tracing::debug!("Received CTRL_SHUTDOWN."), } }) } /// Registers signal handlers and returns a future that indicates a shutdown request /// upon completion. pub(crate) fn register_signals() -> io::Result<impl Future<Output = ()>> { register_signals_impl() }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/future_ext.rs
src/future_ext.rs
use crate::{SubsystemHandle, errors::CancelledByShutdown}; use pin_project_lite::pin_project; use tokio_util::sync::WaitForCancellationFuture; pin_project! { /// A future that is resolved once the corresponding task is finished /// or a shutdown is initiated. #[must_use = "futures do nothing unless polled"] pub struct CancelOnShutdownFuture<'a, T: std::future::Future>{ #[pin] future: T, #[pin] cancellation: WaitForCancellationFuture<'a>, } } impl<T: std::future::Future> std::future::Future for CancelOnShutdownFuture<'_, T> { type Output = Result<T::Output, CancelledByShutdown>; fn poll( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { use std::task::Poll; let mut this = self.project(); // Abort if there is a shutdown match this.cancellation.as_mut().poll(cx) { Poll::Ready(()) => return Poll::Ready(Err(CancelledByShutdown)), Poll::Pending => (), } // If there is no shutdown, see if the task is finished match this.future.as_mut().poll(cx) { Poll::Ready(res) => Poll::Ready(Ok(res)), Poll::Pending => Poll::Pending, } } } /// Extends the [std::future::Future] trait with useful utility functions. pub trait FutureExt { /// The type of the future. type Future: std::future::Future; /// Cancels the future when a shutdown is initiated. /// /// ## Returns /// /// A future that resolves to either the return value of the original future, or to /// [CancelledByShutdown] when a shutdown happened. /// /// # Arguments /// /// * `subsys` - The [SubsystemHandle] to receive the shutdown request from. /// /// # Examples /// ``` /// use miette::Result; /// use tokio_graceful_shutdown::{errors::CancelledByShutdown, FutureExt, SubsystemHandle}; /// use tokio::time::{sleep, Duration}; /// /// async fn my_subsystem(subsys: SubsystemHandle) -> Result<()> { /// match sleep(Duration::from_secs(9001)) /// .cancel_on_shutdown(&subsys) /// .await /// { /// Ok(()) => { /// println!("Sleep finished."); /// } /// Err(CancelledByShutdown) => { /// println!("Sleep got cancelled by shutdown."); /// } /// } /// /// Ok(()) /// } /// ``` fn cancel_on_shutdown( self, subsys: &SubsystemHandle, ) -> CancelOnShutdownFuture<'_, Self::Future>; } impl<T: std::future::Future> FutureExt for T { type Future = T; fn cancel_on_shutdown(self, subsys: &SubsystemHandle) -> CancelOnShutdownFuture<'_, T> { let cancellation = subsys.get_cancellation_token().cancelled(); CancelOnShutdownFuture { future: self, cancellation, } } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/lib.rs
src/lib.rs
//! This crate provides utility functions to perform a graceful shutdown on tokio-rs based services. //! //! Specifically, it provides: //! //! - Listening for shutdown requests from within subsystems //! - Manual shutdown initiation from within subsystems //! - Automatic shutdown on //! - SIGINT/SIGTERM/Ctrl+C //! - Subsystem failure //! - Subsystem panic //! - Clean shutdown procedure with timeout and error propagation //! - Subsystem nesting //! - Partial shutdown of a selected subsystem tree //! //! # Example //! //! This example shows a minimal example of how to launch an asynchronous subsystem with the help of this crate. //! //! It contains a countdown subsystem that will end the program after 5 seconds. //! During the countdown, the program will react to Ctrl-C/SIGINT/SIGTERM and will cancel the countdown task accordingly. //! //! ``` //! use miette::Result; //! use tokio_graceful_shutdown::{SubsystemBuilder, SubsystemHandle, Toplevel}; //! use tokio::time::{sleep, Duration}; //! //! async fn countdown() { //! for i in (1..=5).rev() { //! tracing::info!("Shutting down in: {}", i); //! sleep(Duration::from_millis(1000)).await; //! } //! } //! //! async fn countdown_subsystem(subsys: &mut SubsystemHandle) -> Result<()> { //! tokio::select! { //! _ = subsys.on_shutdown_requested() => { //! tracing::info!("Countdown cancelled."); //! }, //! _ = countdown() => { //! subsys.request_shutdown(); //! } //! }; //! //! Ok(()) //! } //! //! #[tokio::main] //! async fn main() -> Result<()> { //! // Init logging //! tracing_subscriber::fmt() //! .with_max_level(tracing::Level::TRACE) //! .init(); //! //! // Setup and execute subsystem tree //! Toplevel::new(async |s: &mut SubsystemHandle| { //! s.start(SubsystemBuilder::new("Countdown", countdown_subsystem)); //! }) //! .catch_signals() //! .handle_shutdown_requests(Duration::from_millis(1000)) //! .await //! .map_err(Into::into) //! } //! ``` //! //! //! The [`Toplevel`] object represents the root object of the subsystem tree //! and is the main entry point of how to interact with this crate. //! Creating a [`Toplevel`] object initially spawns a simple subsystem, which can then //! spawn further subsystems recursively. //! //! The [`catch_signals()`](Toplevel::catch_signals) method signals the `Toplevel` object to listen for SIGINT/SIGTERM/Ctrl+C and initiate a shutdown thereafter. //! //! [`handle_shutdown_requests()`](Toplevel::handle_shutdown_requests) is the final and most important method of `Toplevel`. It idles until the program enters the shutdown mode. Then, it collects all the return values of the subsystems, determines the global error state and makes sure the shutdown happens within the given timeout. //! Lastly, it returns an error value that can be directly used as a return code for `main()`. //! //! Further, the way to register and start a new submodule is to provide //! a submodule function/lambda to [`SubsystemHandle::start`]. //! If additional arguments shall to be provided to the submodule, it is necessary to create //! a submodule `struct`. Further details can be seen in the `examples` directory of the repository. //! //! Finally, you can see the [`SubsystemHandle`] object that gets provided to the subsystem. //! It is the main way of the subsystem to communicate with this crate. //! It enables the subsystem to start nested subsystems, to react to shutdown requests or //! to initiate a shutdown. //! #![deny(unreachable_pub)] #![deny(missing_docs)] #![doc( issue_tracker_base_url = "https://github.com/Finomnis/tokio-graceful-shutdown/issues", test(no_crate_inject, attr(deny(warnings))), test(attr(allow(dead_code))) )] type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>; /// A collection of traits a custom error has to fulfill in order to be /// usable as the `ErrType` of [Toplevel]. pub trait ErrTypeTraits: std::fmt::Debug + std::fmt::Display + 'static + Send + Sync + Sized { } impl<T> ErrTypeTraits for T where T: std::fmt::Debug + std::fmt::Display + 'static + Send + Sync + Sized { } /// An async function that can be used as a subsystem. /// /// Note: External users should not implement this trait directly. /// Prefer passing `async fn` or async closures; this trait exists to /// model those in the public API and may evolve. pub trait AsyncSubsysFn<A, O>: Send + FnOnce(A) -> Self::Fut { /// The produced subsystem future type Fut: Future<Output = O> + Send; } // This trick allows us to generate a “FnOnce”-like bound with only one lifetime parameter, // so that functions which capture the input argument’s lifetime in their output // (i.e., async functions) can meet the bound. impl<A, O, Out, F> AsyncSubsysFn<A, O> for F where Out: Future<Output = O> + Send, F: Send + FnOnce(A) -> Out, { type Fut = Out; } pub mod errors; mod error_action; mod future_ext; mod into_subsystem; mod runner; mod signal_handling; mod subsystem; mod tokio_task; mod toplevel; mod utils; pub use error_action::ErrorAction; pub use future_ext::FutureExt; pub use into_subsystem::IntoSubsystem; pub use subsystem::NestedSubsystem; pub use subsystem::SubsystemBuilder; pub use subsystem::SubsystemFinishedFuture; pub use subsystem::SubsystemHandle; pub use toplevel::Toplevel;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/toplevel.rs
src/toplevel.rs
use std::{sync::Arc, time::Duration}; use atomic::Atomic; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; use crate::{ AsyncSubsysFn, BoxedError, ErrTypeTraits, ErrorAction, NestedSubsystem, SubsystemHandle, errors::{GracefulShutdownError, SubsystemError, handle_dropped_error}, signal_handling::register_signals, subsystem::{self, ErrorActions}, }; /// Acts as the root of the subsystem tree and forms the entry point for /// any interaction with this crate. /// /// Every project that uses this crate has to create a [`Toplevel`] object somewhere. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::Duration; /// use tokio_graceful_shutdown::{SubsystemBuilder, SubsystemHandle, Toplevel}; /// /// async fn my_subsystem(subsys: &mut SubsystemHandle) -> Result<()> { /// subsys.request_shutdown(); /// Ok(()) /// } /// /// #[tokio::main] /// async fn main() -> Result<()> { /// Toplevel::new(async |s: &mut SubsystemHandle| { /// s.start(SubsystemBuilder::new("MySubsystem", my_subsystem)); /// }) /// .catch_signals() /// .handle_shutdown_requests(Duration::from_millis(1000)) /// .await /// .map_err(Into::into) /// } /// ``` /// #[must_use = "This toplevel must be consumed by calling `handle_shutdown_requests` on it."] pub struct Toplevel<ErrType: ErrTypeTraits = BoxedError> { root_handle: SubsystemHandle<ErrType>, toplevel_subsys: NestedSubsystem<ErrType>, errors: mpsc::UnboundedReceiver<SubsystemError<ErrType>>, } impl<ErrType: ErrTypeTraits> Toplevel<ErrType> { /// Creates a new Toplevel object. /// /// The Toplevel object is the base for everything else in this crate. /// /// # Arguments /// /// * `subsystem` - The subsystem that should be spawned as the root node. /// Usually the job of this subsystem is to spawn further subsystems. #[track_caller] pub fn new<Subsys>(subsystem: Subsys) -> Self where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, ()>, { Self::new_with_shutdown_token(subsystem, CancellationToken::new()) } /// Creates a new Toplevel object. /// /// Takes an existing [`CancellationToken`] that can be used to trigger /// a shutdown from an external thread. /// /// The Toplevel object is the base for everything else in this crate. /// /// # Arguments /// /// * `subsystem` - The subsystem that should be spawned as the root node. /// Usually the job of this subsystem is to spawn further subsystems. /// * `shutdown_token` - A token that can be used to trigger a shutdown. #[track_caller] pub fn new_with_shutdown_token<Subsys>( subsystem: Subsys, shutdown_token: CancellationToken, ) -> Self where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, ()>, { let (error_sender, errors) = mpsc::unbounded_channel(); let root_handle = subsystem::root_handle(shutdown_token, move |e| { match &e { SubsystemError::Panicked(name) => { tracing::error!("Uncaught panic from subsystem '{name}'.") } SubsystemError::Failed(name, e) => { tracing::error!("Uncaught error from subsystem '{name}': {e}",) } }; handle_dropped_error(error_sender.send(e)); }); let toplevel_subsys = root_handle.start_with_abs_name( Arc::from("/"), async move |s: &mut SubsystemHandle<ErrType>| { subsystem(s).await; Result::<(), ErrType>::Ok(()) }, ErrorActions { on_failure: Atomic::new(ErrorAction::Forward), on_panic: Atomic::new(ErrorAction::Forward), }, false, ); Self { root_handle, toplevel_subsys, errors, } } /// Registers signal handlers to initiate a program shutdown when certain operating system /// signals get received. /// /// The following signals will be handled: /// /// - On Windows: /// - `CTRL_C` /// - `CTRL_BREAK` /// - `CTRL_CLOSE` /// - `CTRL_SHUTDOWN` /// /// - On Unix: /// - `SIGINT` /// - `SIGTERM` /// /// # Caveats /// /// This function internally uses [tokio::signal] with all of its caveats. /// /// Especially the caveats from [tokio::signal::unix::Signal] are important for Unix targets. /// #[track_caller] pub fn catch_signals(self) -> Self { let shutdown_token = self.root_handle.get_cancellation_token().clone(); match register_signals() { Ok(signals) => { crate::tokio_task::spawn( async move { signals.await; shutdown_token.cancel(); }, "catch_signals", ); } Err(e) => { tracing::error!("Failed to register OS signal handlers: {e}"); tracing::error!( "Be aware that this means OS signals like SIGINT will kill the program instead of triggering a graceful shutdown." ); } }; self } /// Performs a clean program shutdown, once a shutdown is requested or all subsystems have /// finished. /// /// In most cases, this will be the final method of `main()`, as it blocks until program /// shutdown and returns an appropriate `Result` that can be directly returned by `main()`. /// /// When a program shutdown happens, this function collects the return values of all subsystems /// to determine the return code of the entire program. /// /// When the shutdown takes longer than the given timeout, an error will be returned and remaining subsystems /// will be cancelled. /// /// # Arguments /// /// * `shutdown_timeout` - The maximum time that is allowed to pass after a shutdown was initiated. /// /// # Returns /// /// An error of type [`GracefulShutdownError`] if an error occurred. /// pub async fn handle_shutdown_requests( mut self, shutdown_timeout: Duration, ) -> Result<(), GracefulShutdownError<ErrType>> { let collect_errors = move || { let mut errors = vec![]; self.errors.close(); while let Ok(e) = self.errors.try_recv() { errors.push(e); } drop(self.errors); errors.into_boxed_slice() }; tokio::select!( _ = self.toplevel_subsys.join() => { tracing::info!("All subsystems finished."); // Not really necessary, but for good measure. self.root_handle.request_shutdown(); let errors = collect_errors(); let result = if errors.is_empty() { Ok(()) } else { Err(GracefulShutdownError::SubsystemsFailed(errors)) }; return result; }, _ = self.root_handle.on_shutdown_requested() => { tracing::info!("Shutting down ..."); } ); match tokio::time::timeout(shutdown_timeout, self.toplevel_subsys.join()).await { Ok(result) => { // An `Err` here would indicate a programming error, // because the toplevel subsys doesn't catch any errors; // it only forwards them. assert!(result.is_ok()); let errors = collect_errors(); if errors.is_empty() { tracing::info!("Shutdown finished."); Ok(()) } else { tracing::warn!("Shutdown finished with errors."); Err(GracefulShutdownError::SubsystemsFailed(errors)) } } Err(_) => { tracing::error!("Shutdown timed out!"); Err(GracefulShutdownError::ShutdownTimeout(collect_errors())) } } } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/into_subsystem.rs
src/into_subsystem.rs
use core::future::Future; use std::pin::Pin; use crate::{BoxedError, ErrTypeTraits, SubsystemHandle}; type IntoSubsystemFuture<'a, Err> = Pin<Box<dyn Future<Output = Result<(), Err>> + 'a + Send>>; /// Allows a struct to be used as a subsystem. /// /// Using a struct that does not implement this trait as a subsystem is possible /// by wrapping it in an async closure. This trait exists primarily /// for convenience. /// /// The template parameter of the trait is the error type /// that the subsytem returns. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::Duration; /// use tokio_graceful_shutdown::{IntoSubsystem, SubsystemBuilder, SubsystemHandle, Toplevel}; /// /// struct MySubsystem; /// /// impl IntoSubsystem<miette::Report> for MySubsystem { /// async fn run(self, subsys: &mut SubsystemHandle) -> Result<()> { /// subsys.request_shutdown(); /// Ok(()) /// } /// } /// /// #[tokio::main] /// async fn main() -> Result<()> { /// // Create toplevel /// Toplevel::new(async |s: &mut SubsystemHandle| { /// s.start(SubsystemBuilder::new( /// "Subsys1", MySubsystem{}.into_subsystem() /// )); /// }) /// .catch_signals() /// .handle_shutdown_requests(Duration::from_millis(500)) /// .await /// .map_err(Into::into) /// } /// ``` /// pub trait IntoSubsystem<Err, ErrWrapper = BoxedError> where Self: Sized + Send + Sync + 'static, Err: Into<ErrWrapper>, ErrWrapper: ErrTypeTraits, { /// The logic of the subsystem. /// /// Will be called as soon as the subsystem gets started. /// /// Returning an error automatically initiates a shutdown. /// /// For more information about subsystem functions, see /// [`SubsystemHandle::start()`](crate::SubsystemHandle::start). fn run( self, subsys: &mut SubsystemHandle<ErrWrapper>, ) -> impl Future<Output = Result<(), Err>> + Send; /// Converts the object into a type that can be passed into /// [`SubsystemHandle::start()`](crate::SubsystemHandle::start). fn into_subsystem( self, ) -> impl FnOnce(&mut SubsystemHandle<ErrWrapper>) -> IntoSubsystemFuture<'_, Err> { |handle: &mut SubsystemHandle<ErrWrapper>| Box::pin(async move { self.run(handle).await }) } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/runner.rs
src/runner.rs
//! The SubsystemRunner is a little tricky, so here some explanation. //! //! A two-layer `tokio::spawn` is required to make this work reliably; the inner `spawn` is the actual subsystem, //! and the outer `spawn` carries out the duty of propagating the `StopReason` and cleaning up. //! //! Further, everything in here reacts properly to being dropped, including //! the runner itself, who cancels the subsystem on drop. use std::{future::Future, sync::Arc}; use crate::{ AsyncSubsysFn, ErrTypeTraits, SubsystemHandle, errors::{SubsystemError, SubsystemFailure}, }; mod alive_guard; pub(crate) use self::alive_guard::AliveGuard; pub(crate) struct SubsystemRunner { aborthandle: tokio::task::AbortHandle, } impl SubsystemRunner { #[track_caller] pub(crate) fn new<Subsys, ErrType: ErrTypeTraits, Err>( name: Arc<str>, subsystem: Subsys, subsystem_handle: SubsystemHandle<ErrType>, guard: AliveGuard, ) -> Self where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, Result<(), Err>>, Err: Into<ErrType>, { let future = run_subsystem(name, subsystem, subsystem_handle, guard); let aborthandle = crate::tokio_task::spawn(future, "subsystem_runner").abort_handle(); SubsystemRunner { aborthandle } } pub(crate) fn abort_handle(&self) -> tokio::task::AbortHandle { self.aborthandle.clone() } } impl Drop for SubsystemRunner { fn drop(&mut self) { self.aborthandle.abort() } } #[track_caller] fn run_subsystem<Subsys, ErrType: ErrTypeTraits, Err>( name: Arc<str>, subsystem: Subsys, mut subsystem_handle: SubsystemHandle<ErrType>, guard: AliveGuard, ) -> impl Future<Output = ()> + 'static where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, Result<(), Err>>, Err: Into<ErrType>, { let mut redirected_subsystem_handle = subsystem_handle.delayed_clone(); let future = async move { subsystem(&mut subsystem_handle).await.map_err(|e| e.into()) }; let join_handle = crate::tokio_task::spawn(future, &name); // Abort on drop guard.on_cancel({ let abort_handle = join_handle.abort_handle(); let name = Arc::clone(&name); move || { if !abort_handle.is_finished() { tracing::warn!("Subsystem cancelled: '{}'", name); } abort_handle.abort(); } }); async move { // Move guard into here, to tie it to the scope of the async let _guard = guard; let failure = match join_handle.await { Ok(Ok(())) => None, Ok(Err(e)) => Some(SubsystemError::Failed(name, SubsystemFailure(e))), Err(e) => { // We can assume that this is a panic, because a cancellation // can never happen as long as we still hold `guard`. if !e.is_panic() { tracing::warn!("Subsystem task for '{name}' was cancelled unexpectedly: {e}"); } Some(SubsystemError::Panicked(name)) } }; // Retrieve the handle that was passed into the subsystem. // Originally it was intended to pass the handle as reference, but // references do not work well with tokio::spawn. // // It is still important that the handle does not leak out of the subsystem. let subsystem_handle = redirected_subsystem_handle.try_recv().expect( "Internal error, please report at https://github.com/Finomnis/tokio-graceful-shutdown/issues!" ); // Raise potential errors let joiner_token = subsystem_handle.joiner_token; if let Some(failure) = failure { joiner_token.raise_failure(failure); } // Wait for children to finish before we destroy the `SubsystemHandle` object. // Otherwise the children would be cancelled immediately. // // This is the main mechanism that forwards a cancellation to all the children. joiner_token.downgrade().join().await; } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/tokio_task.rs
src/tokio_task.rs
use std::future::Future; use tokio::task::JoinHandle; #[cfg(not(all(tokio_unstable, feature = "tracing")))] #[track_caller] pub(crate) fn spawn<F>(f: F, _name: &str) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { tokio::spawn(f) } #[cfg(all(tokio_unstable, feature = "tracing"))] #[track_caller] pub(crate) fn spawn<F>(f: F, name: &str) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'static, { tokio::task::Builder::new() .name(name) .spawn(f) .expect("a task should be spawned") }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/error_action.rs
src/error_action.rs
use bytemuck::NoUninit; /// Possible ways a subsystem can react to errors. /// /// An error will propagate upwards in the subsystem tree until /// it reaches a subsystem that won't forward it to its parent. /// /// If an error reaches the [`Toplevel`](crate::Toplevel), a global shutdown will be initiated. /// /// Also see: /// - [`SubsystemBuilder::on_failure`](crate::SubsystemBuilder::on_failure) /// - [`SubsystemBuilder::on_panic`](crate::SubsystemBuilder::on_panic) /// - [`NestedSubsystem::change_failure_action`](crate::NestedSubsystem::change_failure_action) /// - [`NestedSubsystem::change_panic_action`](crate::NestedSubsystem::change_panic_action) /// #[derive(Clone, Copy, Debug, Eq, PartialEq, NoUninit)] #[repr(u8)] pub enum ErrorAction { /// Pass the error on to the parent subsystem, but don't react to it. Forward, /// Store the error so it can be retrieved through /// [`NestedSubsystem::join`](crate::NestedSubsystem::join), /// then initiate a shutdown of the subsystem and its children. /// Do not forward the error to the parent subsystem. CatchAndLocalShutdown, } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/errors/tests.rs
src/errors/tests.rs
use tracing_test::traced_test; use crate::BoxedError; use super::*; #[allow(clippy::uninlined_format_args)] fn examine_report(error: impl miette::Diagnostic + Sync + Send + 'static) { println!("{}", error); println!("{:?}", error); println!("{:?}", error.source()); println!("{}", error.code().unwrap()); // Convert to report let report: miette::Report = error.into(); println!("{}", report); println!("{:?}", report); // Convert to std::error::Error let boxed_error: BoxedError = report.into(); println!("{}", boxed_error); println!("{:?}", boxed_error); } #[test] fn errors_can_be_converted_to_diagnostic() { examine_report(GracefulShutdownError::ShutdownTimeout::<BoxedError>( Box::new([]), )); examine_report(GracefulShutdownError::SubsystemsFailed::<BoxedError>( Box::new([SubsystemError::Panicked("".into())]), )); examine_report(SubsystemJoinError::SubsystemsFailed::<BoxedError>( Arc::new([SubsystemError::Panicked("".into())]), )); examine_report(SubsystemError::Panicked::<BoxedError>("".into())); examine_report(SubsystemError::Failed::<BoxedError>( "".into(), SubsystemFailure("".into()), )); examine_report(CancelledByShutdown); } #[test] fn extract_related_from_graceful_shutdown_error() { let related = || { Box::new([ SubsystemError::Failed("a".into(), SubsystemFailure(String::from("A").into())), SubsystemError::Panicked("b".into()), ]) }; let matches_related = |data: &[SubsystemError<BoxedError>]| { let mut iter = data.iter(); let elem = iter.next().unwrap(); assert_eq!(elem.name(), "a"); assert!(matches!(elem, SubsystemError::Failed(_, _))); let elem = iter.next().unwrap(); assert_eq!(elem.name(), "b"); assert!(matches!(elem, SubsystemError::Panicked(_))); assert!(iter.next().is_none()); }; matches_related(GracefulShutdownError::ShutdownTimeout(related()).get_subsystem_errors()); matches_related(GracefulShutdownError::SubsystemsFailed(related()).get_subsystem_errors()); matches_related(&GracefulShutdownError::ShutdownTimeout(related()).into_subsystem_errors()); matches_related(&GracefulShutdownError::SubsystemsFailed(related()).into_subsystem_errors()); } #[test] fn extract_contained_error_from_convert_subsystem_failure() { let msg = "MyFailure".to_string(); let failure = SubsystemFailure(msg.clone()); assert_eq!(&msg, failure.get_error()); assert_eq!(msg, *failure); assert_eq!(msg, failure.into_error()); } #[test] #[traced_test] fn handle_dropped_errors() { handle_dropped_error(Err(mpsc::error::SendError(BoxedError::from(String::from( "ABC", ))))); assert!(logs_contain("An error got dropped: \"ABC\"")); } #[test] #[traced_test] fn handle_unhandled_stopreasons() { handle_unhandled_stopreason(Some(SubsystemError::<BoxedError>::Panicked(Arc::from( "def", )))); assert!(logs_contain("Unhandled stop reason: Panicked(\"def\")")); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/utils/mod.rs
src/utils/mod.rs
mod joiner_token; pub(crate) use joiner_token::JoinerToken; pub(crate) use joiner_token::JoinerTokenRef; pub(crate) mod remote_drop_collection;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/utils/remote_drop_collection.rs
src/utils/remote_drop_collection.rs
use std::sync::{ Arc, Mutex, Weak, atomic::{AtomicUsize, Ordering}, }; struct RemotelyDroppableItem<T> { _item: T, offset: Arc<AtomicUsize>, } /// A vector that owns a bunch of objects. /// Every object is connected to a guard token. /// Once the token is dropped, the object gets dropped as well. /// /// Note that the token does not keep the object alive, it is only responsible /// for triggering a drop. /// /// The important part here is that the token is sendable to other context/threads, /// so it's basically a 'remote drop guard' concept. pub(crate) struct RemotelyDroppableItems<T> { items: Arc<Mutex<Vec<RemotelyDroppableItem<T>>>>, } impl<T> RemotelyDroppableItems<T> { pub(crate) fn new() -> Self { Self { items: Default::default(), } } pub(crate) fn insert(&self, item: T) -> RemoteDrop<T> { let mut items = self.items.lock().unwrap(); let offset = Arc::new(AtomicUsize::new(items.len())); let weak_offset = Arc::downgrade(&offset); items.push(RemotelyDroppableItem { _item: item, offset, }); RemoteDrop { data: Arc::downgrade(&self.items), offset: weak_offset, } } } /// Drops its referenced item when dropped pub(crate) struct RemoteDrop<T> { // Both weak. // If data is gone, then our item collection dropped. data: Weak<Mutex<Vec<RemotelyDroppableItem<T>>>>, // If offset is gone, then the item itself got removed // while the dropguard still exists. offset: Weak<AtomicUsize>, } impl<T> Drop for RemoteDrop<T> { fn drop(&mut self) { if let Some(data) = self.data.upgrade() { // Important: lock first, then read the offset. let mut data = data.lock().unwrap(); let offset = self .offset .upgrade() .expect("Trying to delete non-existent item! Please report this.") .load(Ordering::Acquire); let last_item = data .pop() .expect("Trying to delete non-existent item! Please report this."); if offset != data.len() { // There must have been at least two items, and we are not at the end. // So swap first before dropping. last_item.offset.store(offset, Ordering::Release); data[offset] = last_item; } } } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/utils/joiner_token.rs
src/utils/joiner_token.rs
use std::{fmt::Debug, sync::Arc}; use tokio::sync::watch; use crate::{ ErrTypeTraits, errors::{SubsystemError, handle_unhandled_stopreason}, }; struct Inner<ErrType: ErrTypeTraits> { counter: watch::Sender<(bool, u32)>, parent: Option<Arc<Inner<ErrType>>>, on_error: Box<dyn Fn(SubsystemError<ErrType>) -> Option<SubsystemError<ErrType>> + Sync + Send>, } /// A token that keeps reference of its existance and its children. pub(crate) struct JoinerToken<ErrType: ErrTypeTraits> { inner: Arc<Inner<ErrType>>, } /// A reference version that does not keep the content alive; purely for /// joining the subtree. #[derive(Clone)] pub(crate) struct JoinerTokenRef { counter: watch::Receiver<(bool, u32)>, } impl<ErrType: ErrTypeTraits> Debug for JoinerToken<ErrType> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "JoinerToken(children = {})", self.inner.counter.borrow().1 ) } } impl Debug for JoinerTokenRef { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let counter = self.counter.borrow(); write!( f, "JoinerTokenRef(alive = {}, children = {})", counter.0, counter.1 ) } } impl<ErrType: ErrTypeTraits> JoinerToken<ErrType> { /// Creates a new joiner token. /// /// The `on_error` callback will receive errors/panics and has to decide /// how to handle them. It can also not handle them and instead pass them on. /// If it returns `Some`, the error will get passed on to its parent. pub(crate) fn new( on_error: impl Fn(SubsystemError<ErrType>) -> Option<SubsystemError<ErrType>> + Sync + Send + 'static, ) -> (Self, JoinerTokenRef) { let inner = Arc::new(Inner { counter: watch::channel((true, 0)).0, parent: None, on_error: Box::new(on_error), }); let weak_ref = JoinerTokenRef { counter: inner.counter.subscribe(), }; (Self { inner }, weak_ref) } pub(crate) async fn join_children(&self) { let mut subscriber = self.inner.counter.subscribe(); // Ignore errors; if the channel got closed, that definitely means // no more children exist. let _ = subscriber .wait_for(|(_alive, children)| *children == 0) .await; } pub(crate) fn child_token( &self, on_error: impl Fn(SubsystemError<ErrType>) -> Option<SubsystemError<ErrType>> + Sync + Send + 'static, ) -> (Self, JoinerTokenRef) { let mut maybe_parent = Some(&self.inner); while let Some(parent) = maybe_parent { parent .counter .send_modify(|(_alive, children)| *children += 1); maybe_parent = parent.parent.as_ref(); } let inner = Arc::new(Inner { counter: watch::channel((true, 0)).0, parent: Some(Arc::clone(&self.inner)), on_error: Box::new(on_error), }); let weak_ref = JoinerTokenRef { counter: inner.counter.subscribe(), }; (Self { inner }, weak_ref) } #[cfg(test)] pub(crate) fn count(&self) -> u32 { self.inner.counter.borrow().1 } pub(crate) fn raise_failure(&self, stop_reason: SubsystemError<ErrType>) { let mut maybe_stop_reason = Some(stop_reason); let mut maybe_parent = Some(&self.inner); while let Some(parent) = maybe_parent { if let Some(stop_reason) = maybe_stop_reason { maybe_stop_reason = (parent.on_error)(stop_reason); } else { break; } maybe_parent = parent.parent.as_ref(); } handle_unhandled_stopreason(maybe_stop_reason); } pub(crate) fn downgrade(self) -> JoinerTokenRef { JoinerTokenRef { counter: self.inner.counter.subscribe(), } } } impl JoinerTokenRef { pub(crate) async fn join(&self) { // Ignore errors; if the channel got closed, that definitely means // the token and all its children got dropped. let _ = self .counter .clone() .wait_for(|&(alive, children)| !alive && children == 0) .await; } #[cfg(test)] pub(crate) fn count(&self) -> u32 { self.counter.borrow().1 } /// Returns true if this subsystem is alive, ignoring children. pub(crate) fn alive(&self) -> bool { self.counter.borrow().0 } /// Returns true if this subsystem or any of its children are alive. pub(crate) fn recursive_alive(&self) -> bool { let (alive, children) = *self.counter.borrow(); alive || children > 0 } } impl<ErrType: ErrTypeTraits> Drop for JoinerToken<ErrType> { fn drop(&mut self) { self.inner .counter .send_modify(|(alive, _children)| *alive = false); let mut maybe_parent = self.inner.parent.as_ref(); while let Some(parent) = maybe_parent { parent .counter .send_modify(|(_alive, children)| *children -= 1); maybe_parent = parent.parent.as_ref(); } } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/utils/remote_drop_collection/tests.rs
src/utils/remote_drop_collection/tests.rs
use super::*; use crate::{BoxedError, utils::JoinerToken}; #[test] fn single_item() { let items = RemotelyDroppableItems::new(); let (count1, _) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!(0, count1.count()); let token1 = items.insert(count1.child_token(|_| None)); assert_eq!(1, count1.count()); drop(token1); assert_eq!(0, count1.count()); } #[test] fn insert_and_drop() { let items = RemotelyDroppableItems::new(); let (count1, _) = JoinerToken::<BoxedError>::new(|_| None); let (count2, _) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!(0, count1.count()); assert_eq!(0, count2.count()); let _token1 = items.insert(count1.child_token(|_| None)); assert_eq!(1, count1.count()); assert_eq!(0, count2.count()); let _token2 = items.insert(count2.child_token(|_| None)); assert_eq!(1, count1.count()); assert_eq!(1, count2.count()); drop(items); assert_eq!(0, count1.count()); assert_eq!(0, count2.count()); } #[test] fn drop_token() { let items = RemotelyDroppableItems::new(); let (count1, _) = JoinerToken::<BoxedError>::new(|_| None); let (count2, _) = JoinerToken::<BoxedError>::new(|_| None); let (count3, _) = JoinerToken::<BoxedError>::new(|_| None); let (count4, _) = JoinerToken::<BoxedError>::new(|_| None); let token1 = items.insert(count1.child_token(|_| None)); let token2 = items.insert(count2.child_token(|_| None)); let token3 = items.insert(count3.child_token(|_| None)); let token4 = items.insert(count4.child_token(|_| None)); assert_eq!(1, count1.count()); assert_eq!(1, count2.count()); assert_eq!(1, count3.count()); assert_eq!(1, count4.count()); // Last item drop(token4); assert_eq!(1, count1.count()); assert_eq!(1, count2.count()); assert_eq!(1, count3.count()); assert_eq!(0, count4.count()); // Middle item drop(token2); assert_eq!(1, count1.count()); assert_eq!(0, count2.count()); assert_eq!(1, count3.count()); assert_eq!(0, count4.count()); // First item drop(token1); assert_eq!(0, count1.count()); assert_eq!(0, count2.count()); assert_eq!(1, count3.count()); assert_eq!(0, count4.count()); // Only item drop(token3); assert_eq!(0, count1.count()); assert_eq!(0, count2.count()); assert_eq!(0, count3.count()); assert_eq!(0, count4.count()); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/utils/joiner_token/tests.rs
src/utils/joiner_token/tests.rs
use tokio::time::{Duration, sleep, timeout}; use tracing_test::traced_test; use crate::BoxedError; use super::*; #[test] #[traced_test] fn counters() { let (root, _) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!(0, root.count()); let (child1, _) = root.child_token(|_| None); assert_eq!(1, root.count()); assert_eq!(0, child1.count()); let (child2, _) = child1.child_token(|_| None); assert_eq!(2, root.count()); assert_eq!(1, child1.count()); assert_eq!(0, child2.count()); let (child3, _) = child1.child_token(|_| None); assert_eq!(3, root.count()); assert_eq!(2, child1.count()); assert_eq!(0, child2.count()); assert_eq!(0, child3.count()); drop(child1); assert_eq!(2, root.count()); assert_eq!(0, child2.count()); assert_eq!(0, child3.count()); drop(child2); assert_eq!(1, root.count()); assert_eq!(0, child3.count()); drop(child3); assert_eq!(0, root.count()); } #[test] #[traced_test] fn counters_weak() { let (root, weak_root) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!(0, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); let (child1, weak_child1) = root.child_token(|_| None); // root // \ // child1 assert_eq!(1, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(0, weak_child1.count()); assert!(weak_child1.alive()); assert!(weak_child1.recursive_alive()); let (child2, weak_child2) = child1.child_token(|_| None); // root // \ // child1 // \ // child2 assert_eq!(2, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(1, weak_child1.count()); assert!(weak_child1.alive()); assert!(weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(weak_child2.alive()); assert!(weak_child2.recursive_alive()); let (child3, weak_child3) = child1.child_token(|_| None); // root // \ // child1 // / \ // child2 child3 assert_eq!(3, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(2, weak_child1.count()); assert!(weak_child1.alive()); assert!(weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(weak_child2.alive()); assert!(weak_child2.recursive_alive()); assert_eq!(0, weak_child3.count()); assert!(weak_child3.alive()); assert!(weak_child3.recursive_alive()); drop(child1); // root // \ // child1 (X) // / \ // child2 child3 assert_eq!(2, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(2, weak_child1.count()); assert!(!weak_child1.alive()); assert!(weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(weak_child2.alive()); assert!(weak_child2.recursive_alive()); assert_eq!(0, weak_child3.count()); assert!(weak_child3.alive()); assert!(weak_child3.recursive_alive()); drop(child2); // root // \ // child1 (X) // / \ // child2 (X) child3 assert_eq!(1, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(1, weak_child1.count()); assert!(!weak_child1.alive()); assert!(weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(!weak_child2.alive()); assert!(!weak_child2.recursive_alive()); assert_eq!(0, weak_child3.count()); assert!(weak_child3.alive()); assert!(weak_child3.recursive_alive()); drop(child3); // root // \ // child1 (X) // / \ // child2 (X) child3 (X) assert_eq!(0, weak_root.count()); assert!(weak_root.alive()); assert!(weak_root.recursive_alive()); assert_eq!(0, weak_child1.count()); assert!(!weak_child1.alive()); assert!(!weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(!weak_child2.alive()); assert!(!weak_child2.recursive_alive()); assert_eq!(0, weak_child3.count()); assert!(!weak_child3.alive()); assert!(!weak_child3.recursive_alive()); drop(root); // root (X) // \ // child1 (X) // / \ // child2 (X) child3 (X) assert_eq!(0, weak_root.count()); assert!(!weak_root.alive()); assert!(!weak_root.recursive_alive()); assert_eq!(0, weak_child1.count()); assert!(!weak_child1.alive()); assert!(!weak_child1.recursive_alive()); assert_eq!(0, weak_child2.count()); assert!(!weak_child2.alive()); assert!(!weak_child2.recursive_alive()); assert_eq!(0, weak_child3.count()); assert!(!weak_child3.alive()); assert!(!weak_child3.recursive_alive()); } #[tokio::test(start_paused = true)] #[traced_test] async fn join() { let (superroot, _) = JoinerToken::<BoxedError>::new(|_| None); let (root, _) = superroot.child_token(|_| None); let (child1, _) = root.child_token(|_| None); let (child2, _) = child1.child_token(|_| None); let (child3, _) = child1.child_token(|_| None); let (set_finished, mut finished) = tokio::sync::oneshot::channel(); tokio::join!( async { timeout(Duration::from_millis(500), root.join_children()) .await .unwrap(); set_finished.send(root.count()).unwrap(); }, async { sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child1); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child2); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child3); sleep(Duration::from_millis(50)).await; let count = timeout(Duration::from_millis(50), finished) .await .unwrap() .unwrap(); assert_eq!(count, 0); } ); } #[tokio::test(start_paused = true)] #[traced_test] async fn join_through_ref() { let (root, joiner) = JoinerToken::<BoxedError>::new(|_| None); let (child1, _) = root.child_token(|_| None); let (child2, _) = child1.child_token(|_| None); let (set_finished, mut finished) = tokio::sync::oneshot::channel(); tokio::join!( async { timeout(Duration::from_millis(500), joiner.join()) .await .unwrap(); set_finished.send(()).unwrap(); }, async { sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child1); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(root); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child2); sleep(Duration::from_millis(50)).await; timeout(Duration::from_millis(50), finished) .await .unwrap() .unwrap(); } ); } #[tokio::test(start_paused = true)] #[traced_test] async fn recursive_finished() { let (root, joiner) = JoinerToken::<BoxedError>::new(|_| None); let (child1, _) = root.child_token(|_| None); let (child2, _) = child1.child_token(|_| None); let (set_finished, mut finished) = tokio::sync::oneshot::channel(); tokio::join!( async { timeout(Duration::from_millis(500), joiner.join()) .await .unwrap(); set_finished.send(()).unwrap(); }, async { sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child1); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(root); sleep(Duration::from_millis(50)).await; assert!(finished.try_recv().is_err()); drop(child2); sleep(Duration::from_millis(50)).await; timeout(Duration::from_millis(50), finished) .await .unwrap() .unwrap(); } ); } #[test] fn debug_print() { let (root, _) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!(format!("{root:?}"), "JoinerToken(children = 0)"); let (child1, _) = root.child_token(|_| None); assert_eq!(format!("{root:?}"), "JoinerToken(children = 1)"); let (_child2, _) = child1.child_token(|_| None); assert_eq!(format!("{root:?}"), "JoinerToken(children = 2)"); } #[test] fn debug_print_ref() { let (root, root_ref) = JoinerToken::<BoxedError>::new(|_| None); assert_eq!( format!("{root_ref:?}"), "JoinerTokenRef(alive = true, children = 0)" ); let (child1, _) = root.child_token(|_| None); assert_eq!( format!("{root_ref:?}"), "JoinerTokenRef(alive = true, children = 1)" ); drop(root); assert_eq!( format!("{root_ref:?}"), "JoinerTokenRef(alive = false, children = 1)" ); drop(child1); assert_eq!( format!("{root_ref:?}"), "JoinerTokenRef(alive = false, children = 0)" ); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/runner/alive_guard.rs
src/runner/alive_guard.rs
use std::sync::{Arc, Mutex}; struct Inner { finished_callback: Option<Box<dyn FnOnce() + Send>>, cancelled_callback: Option<Box<dyn FnOnce() + Send>>, } /// Allows registering callback functions that will get called on destruction. /// /// This struct is the mechanism that manages lifetime of parents and children /// in the subsystem tree. It allows for cancellation of the subsytem on drop, /// and for automatic deregistering in the parent when the child is finished. pub(crate) struct AliveGuard { inner: Arc<Mutex<Inner>>, } impl Clone for AliveGuard { fn clone(&self) -> Self { Self { inner: Arc::clone(&self.inner), } } } impl AliveGuard { pub(crate) fn new() -> Self { Self { inner: Arc::new(Mutex::new(Inner { finished_callback: None, cancelled_callback: None, })), } } pub(crate) fn on_cancel(&self, cancelled_callback: impl FnOnce() + 'static + Send) { let mut inner = self.inner.lock().unwrap(); assert!(inner.cancelled_callback.is_none()); inner.cancelled_callback = Some(Box::new(cancelled_callback)); } pub(crate) fn on_finished(&self, finished_callback: impl FnOnce() + 'static + Send) { let mut inner = self.inner.lock().unwrap(); assert!(inner.finished_callback.is_none()); inner.finished_callback = Some(Box::new(finished_callback)); } } impl Drop for Inner { fn drop(&mut self) { if let Some(finished_callback) = self.finished_callback.take() { finished_callback(); } else { tracing::error!( "No `finished` callback was registered in AliveGuard! This should not happen, please report this at https://github.com/Finomnis/tokio-graceful-shutdown/issues." ); } if let Some(cancelled_callback) = self.cancelled_callback.take() { cancelled_callback() } } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/runner/alive_guard/tests.rs
src/runner/alive_guard/tests.rs
use std::sync::atomic::{AtomicU32, Ordering}; use tracing_test::traced_test; use super::*; #[test] #[traced_test] fn finished_callback() { let alive_guard = AliveGuard::new(); let counter = Arc::new(AtomicU32::new(0)); let counter2 = Arc::clone(&counter); alive_guard.on_finished(move || { counter2.fetch_add(1, Ordering::Relaxed); }); drop(alive_guard); assert_eq!(counter.load(Ordering::Relaxed), 1); } #[test] #[traced_test] fn cancel_callback() { let alive_guard = AliveGuard::new(); let counter = Arc::new(AtomicU32::new(0)); let counter2 = Arc::clone(&counter); alive_guard.on_finished(|| {}); alive_guard.on_cancel(move || { counter2.fetch_add(1, Ordering::Relaxed); }); drop(alive_guard); assert_eq!(counter.load(Ordering::Relaxed), 1); } #[test] #[traced_test] fn both_callbacks() { let alive_guard = AliveGuard::new(); let counter = Arc::new(AtomicU32::new(0)); let counter2 = Arc::clone(&counter); let counter3 = Arc::clone(&counter); alive_guard.on_finished(move || { counter2.fetch_add(1, Ordering::Relaxed); }); alive_guard.on_cancel(move || { counter3.fetch_add(1, Ordering::Relaxed); }); drop(alive_guard); assert_eq!(counter.load(Ordering::Relaxed), 2); } #[test] #[traced_test] fn no_callback() { let alive_guard = AliveGuard::new(); drop(alive_guard); assert!(logs_contain( "No `finished` callback was registered in AliveGuard! This should not happen, please report this at https://github.com/Finomnis/tokio-graceful-shutdown/issues." )); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/nested_subsystem.rs
src/subsystem/nested_subsystem.rs
use std::sync::atomic::Ordering; use crate::{ErrTypeTraits, ErrorAction, errors::SubsystemJoinError}; use super::{NestedSubsystem, SubsystemFinishedFuture}; impl<ErrType: ErrTypeTraits> NestedSubsystem<ErrType> { /// Wait for the subsystem and all of its children to be finished. /// /// If its failure/panic action is set to [`ErrorAction::CatchAndLocalShutdown`], /// this function will return the list of errors caught by the subsystem. /// /// # Returns /// /// A [`SubsystemJoinError`] on failure. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::{sleep, Duration}; /// use tokio_graceful_shutdown::{ErrorAction, SubsystemBuilder, SubsystemHandle}; /// /// async fn nested_subsystem(subsys: &mut SubsystemHandle) -> Result<()> { /// // This subsystem does nothing but wait for the shutdown to happen /// subsys.on_shutdown_requested().await; /// Ok(()) /// } /// /// async fn subsystem(subsys: &mut SubsystemHandle) -> Result<()> { /// // This subsystem waits for one second and then performs a partial shutdown /// /// // Spawn nested subsystem. /// // Make sure to catch errors, so that they are properly /// // returned at `.join()`. /// let nested = subsys.start( /// SubsystemBuilder::new("nested", nested_subsystem) /// .on_failure(ErrorAction::CatchAndLocalShutdown) /// .on_panic(ErrorAction::CatchAndLocalShutdown) /// ); /// /// // Wait for a second /// sleep(Duration::from_millis(1000)).await; /// /// // Perform a partial shutdown of the nested subsystem /// nested.initiate_shutdown(); /// nested.join().await?; /// /// Ok(()) /// } /// ``` pub async fn join(&self) -> Result<(), SubsystemJoinError<ErrType>> { self.joiner.join().await; let errors = self.errors.lock().unwrap().finish(); if errors.is_empty() { Ok(()) } else { Err(SubsystemJoinError::SubsystemsFailed(errors)) } } /// Signals the subsystem and all of its children to shut down. pub fn initiate_shutdown(&self) { self.cancellation_token.cancel() } /// Changes the way this subsystem should react to failures, /// meaning if it or one of its children returns an `Err` value. /// /// For more information, see [`ErrorAction`]. pub fn change_failure_action(&self, action: ErrorAction) { self.error_actions .on_failure .store(action, Ordering::Relaxed); } /// Changes the way this subsystem should react if it or one /// of its children panic. /// /// For more information, see [`ErrorAction`]. pub fn change_panic_action(&self, action: ErrorAction) { self.error_actions.on_panic.store(action, Ordering::Relaxed); } /// Returns a future that resolves once the subsystem and its children are finished. /// /// Similar to [`join`](NestedSubsystem::join), but more light-weight /// as it does not return any information about subsystem errors. pub fn finished(&self) -> SubsystemFinishedFuture { SubsystemFinishedFuture::new(self.joiner.clone()) } /// Returns whether this subsystem and all of its children are finished. pub fn is_finished(&self) -> bool { !self.joiner.recursive_alive() } /// Returns whether this subsystem, and this subsystem only, is finished. /// /// NOTE: This ignores whether children are alive or not. This can return `true` /// while its children are still running! Usually, you probably want [`NestedSubsystem::is_finished`]. pub fn is_finished_shallow(&self) -> bool { !self.joiner.alive() } /// Signals to the subsystem and all of its children that they should abort. /// /// Important: This action is performed on a best-effort base. It is not guaranteed /// that aborting a task is performed right away, or ever. /// /// This comes with the same restrictions as [`tokio::task::AbortHandle::abort`], /// with the additional restriction that this action will get queued and is not /// executed synchronously. pub fn abort(&self) { self.abort_handle.abort(); } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/error_collector.rs
src/subsystem/error_collector.rs
use std::sync::Arc; use tokio::sync::mpsc; use crate::{ErrTypeTraits, errors::SubsystemError}; pub(crate) enum ErrorCollector<ErrType: ErrTypeTraits> { Collecting(mpsc::UnboundedReceiver<SubsystemError<ErrType>>), Finished(Arc<[SubsystemError<ErrType>]>), } impl<ErrType: ErrTypeTraits> ErrorCollector<ErrType> { pub(crate) fn new(receiver: mpsc::UnboundedReceiver<SubsystemError<ErrType>>) -> Self { Self::Collecting(receiver) } pub(crate) fn finish(&mut self) -> Arc<[SubsystemError<ErrType>]> { match self { ErrorCollector::Collecting(receiver) => { let mut errors = vec![]; receiver.close(); while let Ok(e) = receiver.try_recv() { errors.push(e); } let errors = errors.into_boxed_slice().into(); *self = ErrorCollector::Finished(Arc::clone(&errors)); errors } ErrorCollector::Finished(errors) => Arc::clone(errors), } } } impl<ErrType: ErrTypeTraits> Drop for ErrorCollector<ErrType> { fn drop(&mut self) { if let Self::Collecting(receiver) = self { receiver.close(); while let Ok(e) = receiver.try_recv() { tracing::warn!("An error got dropped: {e:?}"); } } } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/subsystem_handle.rs
src/subsystem/subsystem_handle.rs
use std::{ mem::ManuallyDrop, sync::{Arc, Mutex, atomic::Ordering}, }; use atomic::Atomic; use tokio::sync::{mpsc, oneshot}; use tokio_util::sync::CancellationToken; use crate::{ AsyncSubsysFn, BoxedError, ErrTypeTraits, ErrorAction, NestedSubsystem, SubsystemBuilder, errors::{SubsystemError, handle_dropped_error}, runner::{AliveGuard, SubsystemRunner}, utils::{JoinerToken, remote_drop_collection::RemotelyDroppableItems}, }; use super::{ErrorActions, error_collector::ErrorCollector}; struct Inner<ErrType: ErrTypeTraits> { name: Arc<str>, cancellation_token: CancellationToken, toplevel_cancellation_token: CancellationToken, joiner_token: JoinerToken<ErrType>, children: RemotelyDroppableItems<SubsystemRunner>, } /// The handle given to each subsystem through which the subsystem can interact with this crate. pub struct SubsystemHandle<ErrType: ErrTypeTraits = BoxedError> { inner: ManuallyDrop<Inner<ErrType>>, // When dropped, redirect Self into this channel. // Required to pass the handle back out of `tokio::spawn`. drop_redirect: Option<oneshot::Sender<WeakSubsystemHandle<ErrType>>>, } pub(crate) struct WeakSubsystemHandle<ErrType: ErrTypeTraits> { pub(crate) joiner_token: JoinerToken<ErrType>, // Children are stored here to keep them alive _children: RemotelyDroppableItems<SubsystemRunner>, } impl<ErrType: ErrTypeTraits> SubsystemHandle<ErrType> { /// Start a nested subsystem. /// /// Once called, the subsystem will be started immediately, similar to [`tokio::spawn`]. /// /// # Arguments /// /// * `builder` - The [`SubsystemBuilder`] that contains all the information /// about the subsystem that should be spawned. /// /// # Returns /// /// A [`NestedSubsystem`] that can be used to control or join the subsystem. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio_graceful_shutdown::{SubsystemBuilder, SubsystemHandle}; /// /// async fn nested_subsystem(subsys: &mut SubsystemHandle) -> Result<()> { /// subsys.on_shutdown_requested().await; /// Ok(()) /// } /// /// async fn my_subsystem(subsys: &mut SubsystemHandle) -> Result<()> { /// // start a nested subsystem /// subsys.start(SubsystemBuilder::new("Nested", nested_subsystem)); /// /// subsys.on_shutdown_requested().await; /// Ok(()) /// } /// ``` #[track_caller] pub fn start<Err, Subsys>(&self, builder: SubsystemBuilder<Subsys>) -> NestedSubsystem<ErrType> where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, Result<(), Err>>, Err: Into<ErrType>, { self.start_with_abs_name( if self.inner.name.as_ref() == "/" { Arc::from(format!("/{}", builder.name)) } else { Arc::from(format!("{}/{}", self.inner.name, builder.name)) }, builder.subsystem, ErrorActions { on_failure: Atomic::new(builder.failure_action), on_panic: Atomic::new(builder.panic_action), }, builder.detached, ) } #[track_caller] pub(crate) fn start_with_abs_name<Err, Subsys>( &self, name: Arc<str>, subsystem: Subsys, error_actions: ErrorActions, detached: bool, ) -> NestedSubsystem<ErrType> where Subsys: 'static + for<'a> AsyncSubsysFn<&'a mut SubsystemHandle<ErrType>, Result<(), Err>>, Err: Into<ErrType>, { let alive_guard = AliveGuard::new(); let (error_sender, errors) = mpsc::unbounded_channel(); let cancellation_token = if detached { CancellationToken::new() } else { self.inner.cancellation_token.child_token() }; let error_actions = Arc::new(error_actions); let (joiner_token, joiner_token_ref) = self.inner.joiner_token.child_token({ let cancellation_token = cancellation_token.clone(); let error_actions = Arc::clone(&error_actions); move |e| { let error_action = match &e { SubsystemError::Failed(_, _) => { error_actions.on_failure.load(Ordering::Relaxed) } SubsystemError::Panicked(_) => error_actions.on_panic.load(Ordering::Relaxed), }; match error_action { ErrorAction::Forward => Some(e), ErrorAction::CatchAndLocalShutdown => { handle_dropped_error(error_sender.send(e)); cancellation_token.cancel(); None } } } }); let child_handle = SubsystemHandle { inner: ManuallyDrop::new(Inner { name: Arc::clone(&name), cancellation_token: cancellation_token.clone(), toplevel_cancellation_token: self.inner.toplevel_cancellation_token.clone(), joiner_token, children: RemotelyDroppableItems::new(), }), drop_redirect: None, }; let runner = SubsystemRunner::new(name, subsystem, child_handle, alive_guard.clone()); let abort_handle = runner.abort_handle(); // Shenanigans to juggle child ownership // // RACE CONDITION SAFETY: // If the subsystem ends before `on_finished` was able to be called, nothing bad happens. // alive_guard will keep the guard alive and the callback will only be called inside of // the guard's drop() implementation. let child_dropper = self.inner.children.insert(runner); alive_guard.on_finished(|| { drop(child_dropper); }); NestedSubsystem { joiner: joiner_token_ref, cancellation_token, errors: Mutex::new(ErrorCollector::new(errors)), error_actions, abort_handle, } } /// Waits until all the children of this subsystem are finished. /// /// Be aware that this does not prevent further children from being /// spawned afterwards, this only waits until there are no children /// any more right now. pub async fn wait_for_children(&self) { self.inner.joiner_token.join_children().await } // For internal use only - should never be used by users. // Required as a short-lived second reference inside of `runner`. pub(crate) fn delayed_clone(&mut self) -> oneshot::Receiver<WeakSubsystemHandle<ErrType>> { let (sender, receiver) = oneshot::channel(); let previous = self.drop_redirect.replace(sender); assert!(previous.is_none()); receiver } /// Wait for the shutdown mode to be triggered. /// /// Once the shutdown mode is entered, all existing calls to this /// method will be released and future calls to this method will /// return immediately. /// /// This is the primary method of subsystems to react to /// the shutdown requests. Most often, it will be used in [`tokio::select`] /// statements to cancel other code as soon as the shutdown is requested. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::{sleep, Duration}; /// use tokio_graceful_shutdown::SubsystemHandle; /// /// async fn countdown() { /// for i in (1..10).rev() { /// tracing::info!("Countdown: {}", i); /// sleep(Duration::from_millis(1000)).await; /// } /// } /// /// async fn countdown_subsystem(subsys: SubsystemHandle) -> Result<()> { /// tracing::info!("Starting countdown ..."); /// /// // This cancels the countdown as soon as shutdown /// // mode was entered /// tokio::select! { /// _ = subsys.on_shutdown_requested() => { /// tracing::info!("Countdown cancelled."); /// }, /// _ = countdown() => { /// tracing::info!("Countdown finished."); /// } /// }; /// /// Ok(()) /// } /// ``` pub async fn on_shutdown_requested(&self) { self.inner.cancellation_token.cancelled().await } /// Returns whether a shutdown should be performed now. /// /// This method is provided for subsystems that need to query the shutdown /// request state repeatedly. /// /// This can be useful in scenarios where a subsystem depends on the graceful /// shutdown of its nested coroutines before it can run final cleanup steps itself. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::{sleep, Duration}; /// use tokio_graceful_shutdown::SubsystemHandle; /// /// async fn uncancellable_action(subsys: &SubsystemHandle) { /// tokio::select! { /// // Execute an action. A dummy `sleep` in this case. /// _ = sleep(Duration::from_millis(1000)) => { /// tracing::info!("Action finished."); /// } /// // Perform a shutdown if requested /// _ = subsys.on_shutdown_requested() => { /// tracing::info!("Action aborted."); /// }, /// } /// } /// /// async fn my_subsystem(subsys: SubsystemHandle) -> Result<()> { /// tracing::info!("Starting subsystem ..."); /// /// // We cannot do a `tokio::select` with `on_shutdown_requested` /// // here, because a shutdown would cancel the action without giving /// // it the chance to react first. /// while !subsys.is_shutdown_requested() { /// uncancellable_action(&subsys).await; /// } /// /// tracing::info!("Subsystem stopped."); /// /// Ok(()) /// } /// ``` pub fn is_shutdown_requested(&self) -> bool { self.inner.cancellation_token.is_cancelled() } /// Triggers a shutdown of the entire subsystem tree. /// /// # Examples /// /// ``` /// use miette::Result; /// use tokio::time::{sleep, Duration}; /// use tokio_graceful_shutdown::SubsystemHandle; /// /// async fn stop_subsystem(subsys: SubsystemHandle) -> Result<()> { /// // This subsystem wait for one second and then stops the program. /// sleep(Duration::from_millis(1000)).await; /// /// // Shut down the entire subsystem tree /// subsys.request_shutdown(); /// /// Ok(()) /// } /// ``` pub fn request_shutdown(&self) { self.inner.toplevel_cancellation_token.cancel(); } /// Triggers a shutdown of the current subsystem and all /// of its children. pub fn request_local_shutdown(&self) { self.inner.cancellation_token.cancel(); } pub(crate) fn get_cancellation_token(&self) -> &CancellationToken { &self.inner.cancellation_token } /// Creates a cancellation token that will get triggered once the /// subsystem shuts down. /// /// This is intended for more lightweight situations where /// creating full-blown subsystems would be too much overhead, /// like spawning connection handlers of a webserver. /// /// For more information, see the [hyper example](https://github.com/Finomnis/tokio-graceful-shutdown/blob/main/examples/hyper.rs). pub fn create_cancellation_token(&self) -> CancellationToken { self.inner.cancellation_token.child_token() } /// Get the name associated with this subsystem. /// /// Note that the names of nested subsystems are built unix-path alike, /// starting and delimited by slashes (e.g. `/a/b/c`). /// /// See [`SubsystemBuilder::new()`] how to set this name. pub fn name(&self) -> &str { &self.inner.name } } impl<ErrType: ErrTypeTraits> Drop for SubsystemHandle<ErrType> { fn drop(&mut self) { // SAFETY: This is how ManuallyDrop is meant to be used. // `self.inner` won't ever be used again because `self` will be gone after this // function is finished. // This takes the `self.inner` object and makes it droppable again. // // This workaround is required to take ownership for the `self.drop_redirect` channel. let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; if let Some(redirect) = self.drop_redirect.take() { let redirected_self = WeakSubsystemHandle { joiner_token: inner.joiner_token, _children: inner.children, }; // ignore error; an error would indicate that there is no receiver. // in that case, do nothing. let _ = redirect.send(redirected_self); } } } pub(crate) fn root_handle<ErrType: ErrTypeTraits>( cancellation_token: CancellationToken, on_error: impl Fn(SubsystemError<ErrType>) + Sync + Send + 'static, ) -> SubsystemHandle<ErrType> { SubsystemHandle { inner: ManuallyDrop::new(Inner { name: Arc::from(""), cancellation_token: cancellation_token.clone(), toplevel_cancellation_token: cancellation_token.clone(), joiner_token: JoinerToken::new(move |e| { on_error(e); cancellation_token.cancel(); None }) .0, children: RemotelyDroppableItems::new(), }), drop_redirect: None, } } #[cfg(test)] mod tests;
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/subsystem_builder.rs
src/subsystem/subsystem_builder.rs
use std::borrow::Cow; use crate::ErrorAction; /// Configures a subsystem before it gets spawned through /// [`SubsystemHandle::start`](crate::SubsystemHandle::start). #[must_use] pub struct SubsystemBuilder<'a, Subsys> { pub(crate) name: Cow<'a, str>, pub(crate) subsystem: Subsys, pub(crate) failure_action: ErrorAction, pub(crate) panic_action: ErrorAction, pub(crate) detached: bool, } impl<'a, Subsys> SubsystemBuilder<'a, Subsys> { /// Creates a new SubsystemBuilder from a given subsystem /// function. /// /// # Arguments /// /// * `name` - The name of the subsystem. Primarily to identify the /// subsystem in error messages. /// * `subsystem` - The subsystem function that the subsystem will execute. pub fn new(name: impl Into<Cow<'a, str>>, subsystem: Subsys) -> Self { Self { name: name.into(), subsystem, failure_action: ErrorAction::Forward, panic_action: ErrorAction::Forward, detached: false, } } /// Sets the way this subsystem should react to failures, /// meaning if it or one of its children return an `Err` value. /// /// The default is [`ErrorAction::Forward`]. /// /// For more information, see [`ErrorAction`]. pub fn on_failure(mut self, action: ErrorAction) -> Self { self.failure_action = action; self } /// Sets the way this subsystem should react if it or one /// of its children panic. /// /// The default is [`ErrorAction::Forward`]. /// /// For more information, see [`ErrorAction`]. pub fn on_panic(mut self, action: ErrorAction) -> Self { self.panic_action = action; self } /// Detaches the subsystem from the parent, causing a shutdown request to not /// be propagated from the parent to the child automatically. /// /// If this option is set, the parent needs to call [`initiate_shutdown()`](crate::NestedSubsystem::initiate_shutdown) /// on the child during shutdown, otherwise the child will not /// react to the shutdown request. So use this option with care. pub fn detached(mut self) -> Self { self.detached = true; self } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/subsystem_finished_future.rs
src/subsystem/subsystem_finished_future.rs
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use crate::utils::JoinerTokenRef; use super::SubsystemFinishedFuture; impl SubsystemFinishedFuture { pub(crate) fn new(joiner: JoinerTokenRef) -> Self { Self { future: Box::pin(async move { joiner.join().await }), } } } impl Future for SubsystemFinishedFuture { type Output = (); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { self.future.as_mut().poll(cx) } }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/mod.rs
src/subsystem/mod.rs
mod error_collector; mod nested_subsystem; mod subsystem_builder; mod subsystem_finished_future; mod subsystem_handle; use std::{ future::Future, pin::Pin, sync::{Arc, Mutex}, }; pub use subsystem_builder::SubsystemBuilder; pub use subsystem_handle::SubsystemHandle; pub(crate) use subsystem_handle::root_handle; use crate::{BoxedError, ErrTypeTraits, ErrorAction, utils::JoinerTokenRef}; use atomic::Atomic; use tokio_util::sync::CancellationToken; /// A nested subsystem. /// /// Can be used to control the subsystem or wait for it to finish. /// /// Dropping this value does not perform any action - the subsystem /// will be neither cancelled, shut down or detached. /// /// For more information, look through the examples directory in /// the source code. pub struct NestedSubsystem<ErrType: ErrTypeTraits = BoxedError> { joiner: JoinerTokenRef, cancellation_token: CancellationToken, errors: Mutex<error_collector::ErrorCollector<ErrType>>, error_actions: Arc<ErrorActions>, abort_handle: tokio::task::AbortHandle, } pub(crate) struct ErrorActions { pub(crate) on_failure: Atomic<ErrorAction>, pub(crate) on_panic: Atomic<ErrorAction>, } /// A future that is resolved once the corresponding subsystem is finished. /// /// Returned by [`NestedSubsystem::finished`]. #[must_use = "futures do nothing unless polled"] pub struct SubsystemFinishedFuture { future: Pin<Box<dyn Future<Output = ()> + Send + Sync>>, }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/subsystem_handle/tests.rs
src/subsystem/subsystem_handle/tests.rs
use tokio::time::{Duration, sleep, timeout}; use tracing_test::traced_test; use super::*; #[tokio::test(start_paused = true)] #[traced_test] async fn recursive_cancellation() { let root_handle = root_handle::<BoxedError>(CancellationToken::new(), |_| {}); let (drop_sender, mut drop_receiver) = tokio::sync::mpsc::channel::<()>(1); root_handle.start(SubsystemBuilder::new( "", async move |_: &mut SubsystemHandle<BoxedError>| { drop_sender.send(()).await.unwrap(); std::future::pending::<Result<(), BoxedError>>().await }, )); // Make sure we are executing the subsystem let recv_result = timeout(Duration::from_millis(100), drop_receiver.recv()) .await .unwrap(); assert!(recv_result.is_some()); drop(root_handle); // Make sure the subsystem got cancelled let recv_result = timeout(Duration::from_millis(100), drop_receiver.recv()) .await .unwrap(); assert!(recv_result.is_none()); } #[tokio::test(start_paused = true)] #[traced_test] async fn recursive_cancellation_2() { let root_handle = root_handle(CancellationToken::new(), |_| {}); let (drop_sender, mut drop_receiver) = tokio::sync::mpsc::channel::<()>(1); let subsys2 = async move |_: &mut SubsystemHandle| { drop_sender.send(()).await.unwrap(); std::future::pending::<Result<(), BoxedError>>().await }; let subsys = async |x: &mut SubsystemHandle| { x.start(SubsystemBuilder::new("", subsys2)); Result::<(), BoxedError>::Ok(()) }; root_handle.start(SubsystemBuilder::new("", subsys)); // Make sure we are executing the subsystem let recv_result = timeout(Duration::from_millis(100), drop_receiver.recv()) .await .unwrap(); assert!(recv_result.is_some()); // Make sure the grandchild is still running sleep(Duration::from_millis(100)).await; assert!(matches!( drop_receiver.try_recv(), Err(tokio::sync::mpsc::error::TryRecvError::Empty) )); drop(root_handle); // Make sure the subsystem got cancelled let recv_result = timeout(Duration::from_millis(100), drop_receiver.recv()) .await .unwrap(); assert!(recv_result.is_none()); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/subsystem/error_collector/tests.rs
src/subsystem/error_collector/tests.rs
use tracing_test::traced_test; use super::*; #[test] #[traced_test] fn normal() { let (sender, receiver) = mpsc::unbounded_channel(); let mut error_collector = ErrorCollector::<String>::new(receiver); sender .send(SubsystemError::Panicked(Arc::from("ABC"))) .unwrap(); sender .send(SubsystemError::Panicked(Arc::from("def"))) .unwrap(); let received = error_collector.finish(); assert_eq!( received.iter().map(|e| e.name()).collect::<Vec<_>>(), vec!["ABC", "def"] ); } #[test] #[traced_test] fn double_finish() { let (sender, receiver) = mpsc::unbounded_channel(); let mut error_collector = ErrorCollector::<String>::new(receiver); sender .send(SubsystemError::Panicked(Arc::from("ABC"))) .unwrap(); sender .send(SubsystemError::Panicked(Arc::from("def"))) .unwrap(); let received = error_collector.finish(); assert_eq!( received.iter().map(|e| e.name()).collect::<Vec<_>>(), vec!["ABC", "def"] ); let received = error_collector.finish(); assert_eq!( received.iter().map(|e| e.name()).collect::<Vec<_>>(), vec!["ABC", "def"] ); } #[test] #[traced_test] fn no_finish() { let (sender, receiver) = mpsc::unbounded_channel(); let error_collector = ErrorCollector::<String>::new(receiver); sender .send(SubsystemError::Panicked(Arc::from("ABC"))) .unwrap(); sender .send(SubsystemError::Panicked(Arc::from("def"))) .unwrap(); drop(error_collector); assert!(logs_contain("An error got dropped: Panicked(\"ABC\")")); assert!(logs_contain("An error got dropped: Panicked(\"def\")")); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/src/error_action/tests.rs
src/error_action/tests.rs
//Clone, Copy, Debug, Eq, PartialEq use super::*; #[test] fn derives() { let a = ErrorAction::Forward; let b = ErrorAction::CatchAndLocalShutdown; assert_ne!(a, b.clone()); assert_ne!(format!("{a:?}"), format!("{b:?}")); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/tests/integration_test.rs
tests/integration_test.rs
use anyhow::anyhow; use tokio::time::{Duration, sleep, timeout}; use tokio_graceful_shutdown::{ ErrorAction, IntoSubsystem, SubsystemBuilder, SubsystemHandle, Toplevel, errors::{GracefulShutdownError, SubsystemError, SubsystemJoinError}, }; use tokio_util::sync::CancellationToken; use tracing_test::traced_test; pub mod common; use common::Event; use common::{BoxedError, BoxedResult}; #[tokio::test(start_paused = true)] #[traced_test] async fn normal_shutdown() { let subsystem = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(200)).await; BoxedResult::Ok(()) }; let toplevel = Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); sleep(Duration::from_millis(100)).await; s.request_shutdown(); }); let result = toplevel .handle_shutdown_requests(Duration::from_millis(400)) .await; assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn use_subsystem_struct() { struct MySubsystem; impl IntoSubsystem<BoxedError> for MySubsystem { async fn run(self, subsys: &mut SubsystemHandle) -> BoxedResult { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(200)).await; BoxedResult::Ok(()) } } let toplevel = Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new( "subsys", MySubsystem {}.into_subsystem(), )); sleep(Duration::from_millis(100)).await; s.request_shutdown(); }); let result = toplevel .handle_shutdown_requests(Duration::from_millis(400)) .await; assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn shutdown_timeout_causes_error() { let subsystem = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(400)).await; BoxedResult::Ok(()) }; let toplevel = Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); sleep(Duration::from_millis(100)).await; s.request_shutdown(); }); let result = toplevel .handle_shutdown_requests(Duration::from_millis(200)) .await; assert!(result.is_err()); assert!(matches!( result, Err(GracefulShutdownError::ShutdownTimeout(_)) )); } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_finishes_with_success() { let subsystem = async |_: &mut SubsystemHandle| BoxedResult::Ok(()); let subsystem2 = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::<BoxedError>::new_with_shutdown_token( async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); s.start(SubsystemBuilder::new("subsys2", subsystem2)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(100)) .await; set_toplevel_finished(); // Assert Ok(()) returncode properly propagates to Toplevel assert!(result.is_ok()); }, async { sleep(Duration::from_millis(200)).await; // Assert Ok(()) doesn't cause a shutdown assert!(!toplevel_finished.get()); shutdown_token.cancel(); sleep(Duration::from_millis(200)).await; // Assert toplevel sucessfully gets stopped, nothing hangs assert!(toplevel_finished.get()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_finishes_with_error() { let subsystem = async |_: &mut SubsystemHandle| Err(anyhow!("Error!")); let subsystem2 = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::<BoxedError>::new_with_shutdown_token( async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); s.start(SubsystemBuilder::new("subsys2", subsystem2)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(100)) .await; set_toplevel_finished(); // Assert Err(()) returncode properly propagates to Toplevel assert!(result.is_err()); }, async { sleep(Duration::from_millis(200)).await; // Assert Err(()) causes a shutdown assert!(toplevel_finished.get()); assert!(shutdown_token.is_cancelled()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_receives_shutdown() { let (subsys_finished, set_subsys_finished) = Event::create(); let subsys = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; set_subsys_finished(); BoxedResult::Ok(()) }; let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::<BoxedError>::new_with_shutdown_token( async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys)); }, shutdown_token.clone(), ); let result = tokio::spawn(toplevel.handle_shutdown_requests(Duration::from_millis(100))); sleep(Duration::from_millis(100)).await; assert!(!subsys_finished.get()); shutdown_token.cancel(); timeout(Duration::from_millis(100), subsys_finished.wait()) .await .unwrap(); let result = timeout(Duration::from_millis(100), result) .await .unwrap() .unwrap(); assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn nested_subsystem_receives_shutdown() { let (subsys_finished, set_subsys_finished) = Event::create(); let nested_subsystem = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; set_subsys_finished(); BoxedResult::Ok(()) }; let subsystem = async |subsys: &mut SubsystemHandle| { subsys.start(SubsystemBuilder::new("nested", nested_subsystem)); subsys.on_shutdown_requested().await; BoxedResult::Ok(()) }; let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); let result = tokio::spawn(toplevel.handle_shutdown_requests(Duration::from_millis(100))); sleep(Duration::from_millis(100)).await; assert!(!subsys_finished.get()); shutdown_token.cancel(); timeout(Duration::from_millis(100), subsys_finished.wait()) .await .unwrap(); let result = timeout(Duration::from_millis(100), result) .await .unwrap() .unwrap(); assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn nested_subsystem_error_propagates() { let nested_subsystem = async |_subsys: &mut SubsystemHandle| Err(anyhow!("Error!")); let subsystem = async move |subsys: &mut SubsystemHandle| { subsys.start(SubsystemBuilder::new("nested", nested_subsystem)); subsys.on_shutdown_requested().await; BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(100)) .await; set_toplevel_finished(); // Assert Err(()) returncode properly propagates to Toplevel assert!(result.is_err()); }, async { sleep(Duration::from_millis(200)).await; // Assert Err(()) causes a shutdown assert!(toplevel_finished.get()); assert!(shutdown_token.is_cancelled()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn panic_gets_handled_correctly() { let nested_subsystem = async |_subsys: &mut SubsystemHandle| { panic!("Error!"); }; let subsystem = async move |subsys: &mut SubsystemHandle| { subsys.start::<anyhow::Error, _>(SubsystemBuilder::new("nested", nested_subsystem)); subsys.on_shutdown_requested().await; BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(100)) .await; set_toplevel_finished(); // Assert panic causes Error propagation to Toplevel assert!(result.is_err()); }, async { sleep(Duration::from_millis(200)).await; // Assert panic causes a shutdown assert!(toplevel_finished.get()); assert!(shutdown_token.is_cancelled()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_can_request_shutdown() { let (subsystem_should_stop, stop_subsystem) = Event::create(); let (subsys_finished, set_subsys_finished) = Event::create(); let subsystem = async move |subsys: &mut SubsystemHandle| { subsystem_should_stop.wait().await; subsys.request_shutdown(); subsys.on_shutdown_requested().await; set_subsys_finished(); BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(100)) .await; set_toplevel_finished(); // Assert graceful shutdown does not cause an Error code assert!(result.is_ok()); }, async { sleep(Duration::from_millis(200)).await; assert!(!toplevel_finished.get()); assert!(!subsys_finished.get()); assert!(!shutdown_token.is_cancelled()); stop_subsystem(); sleep(Duration::from_millis(200)).await; // Assert request_shutdown() causes a shutdown assert!(toplevel_finished.get()); assert!(subsys_finished.get()); assert!(shutdown_token.is_cancelled()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn shutdown_timeout_causes_cancellation() { let (subsys_finished, set_subsys_finished) = Event::create(); let subsystem = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(300)).await; set_subsys_finished(); BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(200)) .await; set_toplevel_finished(); // Assert graceful shutdown does not cause an Error code assert!(result.is_err()); }, async { sleep(Duration::from_millis(200)).await; assert!(!toplevel_finished.get()); assert!(!subsys_finished.get()); assert!(!shutdown_token.is_cancelled()); shutdown_token.cancel(); timeout(Duration::from_millis(300), toplevel_finished.wait()) .await .unwrap(); // Assert shutdown timed out causes a shutdown assert!(toplevel_finished.get()); assert!(!subsys_finished.get()); // Assert subsystem was canceled and didn't continue running in the background sleep(Duration::from_millis(500)).await; assert!(!subsys_finished.get()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn spawning_task_during_shutdown_causes_task_to_be_cancelled() { let (subsys_finished, set_subsys_finished) = Event::create(); let (nested_finished, set_nested_finished) = Event::create(); let nested = async |subsys: &mut SubsystemHandle| { sleep(Duration::from_millis(100)).await; subsys.on_shutdown_requested().await; set_nested_finished(); BoxedResult::Ok(()) }; let subsystem = async move |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(100)).await; subsys.start(SubsystemBuilder::new("Nested", nested)); set_subsys_finished(); BoxedResult::Ok(()) }; let (toplevel_finished, set_toplevel_finished) = Event::create(); let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(500)) .await; set_toplevel_finished(); // Assert graceful shutdown does not cause an Error code assert!(result.is_ok()); }, async { sleep(Duration::from_millis(200)).await; assert!(!toplevel_finished.get()); assert!(!subsys_finished.get()); assert!(!shutdown_token.is_cancelled()); assert!(!nested_finished.get()); shutdown_token.cancel(); timeout(Duration::from_millis(300), toplevel_finished.wait()) .await .unwrap(); assert!(subsys_finished.get()); assert!(nested_finished.get()); }, ); } #[tokio::test(flavor = "multi_thread", worker_threads = 3)] async fn double_panic_does_not_stop_graceful_shutdown() { let (subsys_finished, set_subsys_finished) = Event::create(); let subsys3 = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(40)).await; set_subsys_finished(); BoxedResult::Ok(()) }; let subsys2 = async |_subsys: &mut SubsystemHandle| { sleep(Duration::from_millis(10)).await; panic!("Subsystem2 panicked!") }; let subsys1 = async move |subsys: &mut SubsystemHandle| { subsys.start::<BoxedError, _>(SubsystemBuilder::new("Subsys2", subsys2)); subsys.start::<BoxedError, _>(SubsystemBuilder::new("Subsys3", subsys3)); subsys.on_shutdown_requested().await; sleep(Duration::from_millis(10)).await; panic!("Subsystem1 panicked!") }; let result = Toplevel::new(async |s: &mut SubsystemHandle| { s.start::<BoxedError, _>(SubsystemBuilder::new("subsys", subsys1)); }) .handle_shutdown_requests(Duration::from_millis(50)) .await; assert!(result.is_err()); assert!(subsys_finished.get()); } #[tokio::test(start_paused = true)] #[traced_test] async fn destroying_toplevel_cancels_subsystems() { let (subsys_started, set_subsys_started) = Event::create(); let (subsys_finished, set_subsys_finished) = Event::create(); let subsys1 = async move |_subsys: &mut SubsystemHandle| { set_subsys_started(); sleep(Duration::from_millis(200)).await; set_subsys_finished(); BoxedResult::Ok(()) }; { let _result = Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }); sleep(Duration::from_millis(100)).await; } sleep(Duration::from_millis(300)).await; assert!(subsys_started.get()); assert!(!subsys_finished.get()); } #[tokio::test(start_paused = true)] #[traced_test] async fn shutdown_triggers_if_all_tasks_ended() { let nested_subsys = async move |_subsys: &mut SubsystemHandle| BoxedResult::Ok(()); let subsys = async move |subsys: &mut SubsystemHandle| { subsys.start(SubsystemBuilder::new("nested", nested_subsys)); BoxedResult::Ok(()) }; tokio::time::timeout( Duration::from_millis(100), Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys1", subsys)); s.start(SubsystemBuilder::new("subsys2", subsys)); }) .handle_shutdown_requests(Duration::from_millis(100)), ) .await .unwrap() .unwrap(); } #[tokio::test(start_paused = true)] #[traced_test] async fn shutdown_triggers_if_no_task_exists() { tokio::time::timeout( Duration::from_millis(100), Toplevel::<BoxedError>::new(async |_: &mut SubsystemHandle| {}) .handle_shutdown_requests(Duration::from_millis(100)), ) .await .unwrap() .unwrap(); } #[tokio::test(start_paused = true)] #[traced_test] async fn destroying_toplevel_cancels_nested_toplevel_subsystems() { let (subsys_started, set_subsys_started) = Event::create(); let (subsys_finished, set_subsys_finished) = Event::create(); let subsys2 = async move |_subsys: &mut SubsystemHandle| { set_subsys_started(); sleep(Duration::from_millis(100)).await; set_subsys_finished(); BoxedResult::Ok(()) }; let subsys1 = async move |_subsys: &mut SubsystemHandle| { Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys2", subsys2)); }) .handle_shutdown_requests(Duration::from_millis(100)) .await }; { let _result = Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }); sleep(Duration::from_millis(50)).await; } sleep(Duration::from_millis(300)).await; assert!(subsys_started.get()); assert!(!subsys_finished.get()); } #[tokio::test(start_paused = true)] #[traced_test] async fn partial_shutdown_request_stops_nested_subsystems() { let (subsys1_started, set_subsys1_started) = Event::create(); let (subsys1_finished, set_subsys1_finished) = Event::create(); let (subsys2_started, set_subsys2_started) = Event::create(); let (subsys2_finished, set_subsys2_finished) = Event::create(); let (subsys3_started, set_subsys3_started) = Event::create(); let (subsys3_finished, set_subsys3_finished) = Event::create(); let (subsys1_shutdown_performed, set_subsys1_shutdown_performed) = Event::create(); let subsys3 = async move |subsys: &mut SubsystemHandle| { set_subsys3_started(); subsys.on_shutdown_requested().await; set_subsys3_finished(); BoxedResult::Ok(()) }; let subsys2 = async move |subsys: &mut SubsystemHandle| { set_subsys2_started(); subsys.start(SubsystemBuilder::new("subsys3", subsys3)); subsys.on_shutdown_requested().await; set_subsys2_finished(); BoxedResult::Ok(()) }; let subsys1 = async move |subsys: &mut SubsystemHandle| { set_subsys1_started(); let nested_subsys = subsys.start(SubsystemBuilder::new("subsys2", subsys2)); sleep(Duration::from_millis(200)).await; nested_subsys.change_failure_action(ErrorAction::CatchAndLocalShutdown); nested_subsys.change_panic_action(ErrorAction::CatchAndLocalShutdown); nested_subsys.initiate_shutdown(); nested_subsys.join().await.unwrap(); set_subsys1_shutdown_performed(); subsys.on_shutdown_requested().await; set_subsys1_finished(); BoxedResult::Ok(()) }; let shutdown_token = CancellationToken::new(); let toplevel = Toplevel::new_with_shutdown_token( async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }, shutdown_token.clone(), ); tokio::join!( async { let result = toplevel .handle_shutdown_requests(Duration::from_millis(500)) .await; assert!(result.is_ok()); }, async { sleep(Duration::from_millis(300)).await; assert!(subsys1_started.get()); assert!(subsys2_started.get()); assert!(subsys3_started.get()); assert!(!subsys1_finished.get()); assert!(subsys2_finished.get()); assert!(subsys3_finished.get()); assert!(subsys1_shutdown_performed.get()); shutdown_token.cancel(); } ); } #[tokio::test(start_paused = true)] #[traced_test] async fn partial_shutdown_panic_gets_propagated_correctly() { let (nested_started, set_nested_started) = Event::create(); let (nested_finished, set_nested_finished) = Event::create(); let nested_subsys = async move |subsys: &mut SubsystemHandle| { set_nested_started(); subsys.on_shutdown_requested().await; set_nested_finished(); panic!("Nested panicked."); }; let subsys1 = async move |subsys: &mut SubsystemHandle| { let handle = subsys.start::<anyhow::Error, _>( SubsystemBuilder::new("nested", nested_subsys) .on_failure(ErrorAction::CatchAndLocalShutdown) .on_panic(ErrorAction::CatchAndLocalShutdown), ); sleep(Duration::from_millis(100)).await; handle.initiate_shutdown(); let result = handle.join().await; assert!(matches!( result.err(), Some(SubsystemJoinError::SubsystemsFailed(_)) )); assert!(nested_started.get()); assert!(nested_finished.get()); assert!(!subsys.is_shutdown_requested()); subsys.request_shutdown(); BoxedResult::Ok(()) }; let result = Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }) .handle_shutdown_requests(Duration::from_millis(500)) .await; assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn partial_shutdown_error_gets_propagated_correctly() { let (nested_started, set_nested_started) = Event::create(); let (nested_finished, set_nested_finished) = Event::create(); let nested_subsys = async move |subsys: &mut SubsystemHandle| { set_nested_started(); subsys.on_shutdown_requested().await; set_nested_finished(); Err(anyhow!("nested failed.")) }; let subsys1 = async move |subsys: &mut SubsystemHandle| { let handle = subsys.start( SubsystemBuilder::new("nested", nested_subsys) .on_failure(ErrorAction::CatchAndLocalShutdown) .on_panic(ErrorAction::CatchAndLocalShutdown), ); sleep(Duration::from_millis(100)).await; handle.initiate_shutdown(); let result = handle.join().await; assert!(matches!( result.err(), Some(SubsystemJoinError::SubsystemsFailed(_)) )); assert!(nested_started.get()); assert!(nested_finished.get()); assert!(!subsys.is_shutdown_requested()); subsys.request_shutdown(); BoxedResult::Ok(()) }; let result = Toplevel::new(async |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }) .handle_shutdown_requests(Duration::from_millis(500)) .await; assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_errors_get_propagated_to_user() { let nested_subsystem1 = async |_: &mut SubsystemHandle| { sleep(Duration::from_millis(100)).await; panic!("Subsystem panicked!"); }; let nested_subsystem2 = async |_: &mut SubsystemHandle| { sleep(Duration::from_millis(100)).await; BoxedResult::Err("MyGreatError".into()) }; let subsystem = async move |subsys: &mut SubsystemHandle| { subsys.start::<anyhow::Error, _>(SubsystemBuilder::new("nested1", nested_subsystem1)); subsys.start(SubsystemBuilder::new("nested2", nested_subsystem2)); sleep(Duration::from_millis(100)).await; subsys.request_shutdown(); BoxedResult::Ok(()) }; let toplevel = Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }); let result = toplevel .handle_shutdown_requests(Duration::from_millis(200)) .await; if let Err(GracefulShutdownError::SubsystemsFailed(mut errors)) = result { assert_eq!(2, errors.len()); errors.sort_by_key(|el| el.name().to_string()); let mut iter = errors.iter(); let el = iter.next().unwrap(); assert!(matches!(el, SubsystemError::Panicked(_))); assert_eq!("/subsys/nested1", el.name()); let el = iter.next().unwrap(); if let SubsystemError::Failed(name, e) = &el { assert_eq!("/subsys/nested2", name.as_ref()); assert_eq!("MyGreatError", format!("{e}")); } else { panic!("Incorrect error type!"); } assert!(matches!(el, SubsystemError::Failed(_, _))); assert_eq!("/subsys/nested2", el.name()); } else { panic!("Incorrect return value!"); } } #[tokio::test(start_paused = true)] #[traced_test] async fn subsystem_errors_get_propagated_to_user_when_timeout() { let nested_subsystem1 = async |_: &mut SubsystemHandle| { sleep(Duration::from_millis(100)).await; panic!("Subsystem panicked!"); }; let nested_subsystem2 = async |_: &mut SubsystemHandle| { sleep(Duration::from_millis(100)).await; BoxedResult::Err("MyGreatError".into()) }; let nested_subsystem3 = async |_: &mut SubsystemHandle| { sleep(Duration::from_millis(10000)).await; Ok(()) }; let subsystem = async move |subsys: &mut SubsystemHandle| { subsys.start::<anyhow::Error, _>(SubsystemBuilder::new("nested1", nested_subsystem1)); subsys.start(SubsystemBuilder::new("nested2", nested_subsystem2)); subsys.start::<anyhow::Error, _>(SubsystemBuilder::new("nested3", nested_subsystem3)); sleep(Duration::from_millis(100)).await; subsys.request_shutdown(); BoxedResult::Ok(()) }; let toplevel = Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }); let result = toplevel .handle_shutdown_requests(Duration::from_millis(200)) .await; if let Err(GracefulShutdownError::ShutdownTimeout(mut errors)) = result { assert_eq!(2, errors.len()); errors.sort_by_key(|el| el.name().to_string()); let mut iter = errors.iter(); let el = iter.next().unwrap(); assert!(matches!(el, SubsystemError::Panicked(_))); assert_eq!("/subsys/nested1", el.name()); let el = iter.next().unwrap(); if let SubsystemError::Failed(name, e) = &el { assert_eq!("/subsys/nested2", name.as_ref()); assert_eq!("MyGreatError", format!("{e}")); } else { panic!("Incorrect error type!"); } assert!(matches!(el, SubsystemError::Failed(_, _))); assert_eq!("/subsys/nested2", el.name()); assert!(iter.next().is_none()); } else { panic!("Incorrect return value!"); } } #[tokio::test(start_paused = true)] #[traced_test] async fn is_shutdown_requested_works_as_intended() { let subsys1 = async move |subsys: &mut SubsystemHandle| { assert!(!subsys.is_shutdown_requested()); subsys.request_shutdown(); assert!(subsys.is_shutdown_requested()); BoxedResult::Ok(()) }; Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsys1)); }) .handle_shutdown_requests(Duration::from_millis(100)) .await .unwrap(); } #[cfg(unix)] #[tokio::test] #[traced_test] async fn shutdown_through_signal() { use nix::sys::signal::{self, Signal}; use nix::unistd::Pid; use tokio_graceful_shutdown::FutureExt; let subsystem = async |subsys: &mut SubsystemHandle| { subsys.on_shutdown_requested().await; sleep(Duration::from_millis(200)).await; BoxedResult::Ok(()) }; tokio::join!( async { sleep(Duration::from_millis(100)).await; // Send SIGINT to ourselves. signal::kill(Pid::this(), Signal::SIGINT).unwrap(); }, async { let result = Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); assert!( sleep(Duration::from_millis(1000)) .cancel_on_shutdown(s) .await .is_err() ); assert!(s.is_shutdown_requested()); }) .catch_signals() .handle_shutdown_requests(Duration::from_millis(400)) .await; assert!(result.is_ok()); }, ); } #[tokio::test(start_paused = true)] #[traced_test] async fn access_name_from_within_subsystem() { let subsys_nested = async move |subsys: &mut SubsystemHandle| { assert_eq!("/subsys_top/subsys_nested", subsys.name()); BoxedResult::Ok(()) }; let subsys_top = async move |subsys: &mut SubsystemHandle| { assert_eq!("/subsys_top", subsys.name()); subsys.start(SubsystemBuilder::new("subsys_nested", subsys_nested)); BoxedResult::Ok(()) }; Toplevel::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys_top", subsys_top)); }) .handle_shutdown_requests(Duration::from_millis(100)) .await .unwrap(); } #[tokio::test(start_paused = true)] #[traced_test] async fn query_subsystem_alive() { // Diagram: // // top (2.5s lifetime) // \ // nested (1s lifetime) let subsys_nested = async move |_: &mut SubsystemHandle| { tokio::time::sleep(Duration::from_millis(1000)).await; BoxedResult::Ok(()) }; let subsys_top = async move |subsys: &mut SubsystemHandle| { let nested = subsys.start(SubsystemBuilder::new("subsys_nested", subsys_nested)); assert!(!nested.is_finished_shallow()); assert!(!nested.is_finished()); tokio::time::sleep(Duration::from_millis(500)).await; assert!(!nested.is_finished_shallow()); assert!(!nested.is_finished()); tokio::time::sleep(Duration::from_millis(2000)).await; assert!(nested.is_finished_shallow()); assert!(nested.is_finished()); BoxedResult::Ok(()) }; Toplevel::new(async move |s: &mut SubsystemHandle| {
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
true
Finomnis/tokio-graceful-shutdown
https://github.com/Finomnis/tokio-graceful-shutdown/blob/21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3/tests/cancel_on_shutdown.rs
tests/cancel_on_shutdown.rs
mod common; use tokio::time::{Duration, sleep}; use tokio_graceful_shutdown::{ FutureExt, SubsystemBuilder, SubsystemHandle, Toplevel, errors::CancelledByShutdown, }; use tracing_test::traced_test; use common::{BoxedError, BoxedResult}; #[tokio::test(start_paused = true)] #[traced_test] async fn cancel_on_shutdown_propagates_result() { let subsystem1 = async |subsys: &mut SubsystemHandle| { let compute_value = async { sleep(Duration::from_millis(10)).await; 42 }; let value = compute_value.cancel_on_shutdown(subsys).await; assert_eq!(value.ok(), Some(42)); BoxedResult::Ok(()) }; let subsystem2 = async |subsys: &mut SubsystemHandle| { async fn compute_value() -> i32 { sleep(Duration::from_millis(10)).await; 42 } let value = compute_value().cancel_on_shutdown(subsys).await; assert_eq!(value.ok(), Some(42)); BoxedResult::Ok(()) }; let result = Toplevel::<BoxedError>::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys1", subsystem1)); s.start(SubsystemBuilder::new("subsys2", subsystem2)); }) .handle_shutdown_requests(Duration::from_millis(200)) .await; assert!(result.is_ok()); } #[tokio::test(start_paused = true)] #[traced_test] async fn cancel_on_shutdown_cancels_on_shutdown() { let subsystem = async |subsys: &mut SubsystemHandle| { async fn compute_value(subsys: &SubsystemHandle) -> i32 { sleep(Duration::from_millis(100)).await; subsys.request_shutdown(); sleep(Duration::from_millis(100)).await; 42 } let value = compute_value(subsys).cancel_on_shutdown(subsys).await; assert!(matches!(value, Err(CancelledByShutdown))); BoxedResult::Ok(()) }; let result = Toplevel::<BoxedError>::new(async move |s: &mut SubsystemHandle| { s.start(SubsystemBuilder::new("subsys", subsystem)); }) .handle_shutdown_requests(Duration::from_millis(200)) .await; assert!(result.is_ok()); }
rust
Apache-2.0
21f915e6cd39cd139c5ab4fa8199b9d87dc5aaa3
2026-01-04T20:24:42.405407Z
false