log_decoder_c_bindings/
lib.rs1use bumpalo::Bump;
5use diagnostics_log_encoding;
6use diagnostics_log_encoding::parse::ParseError;
7use diagnostics_message::error::MessageError;
8use diagnostics_message::ffi::{CPPMessageFormatter, CppArray, LogMessage};
9use diagnostics_message::{self as message, MonikerWithUrl};
10use std::ffi::CString;
11use std::ops::{Deref, DerefMut};
12use std::os::raw::c_char;
13use std::ptr::NonNull;
14use thiserror::Error;
15
16#[unsafe(no_mangle)]
26pub unsafe extern "C" fn fuchsia_decode_log_message_to_json(
27 msg: *const u8,
28 size: usize,
29) -> *mut c_char {
30 let managed_ptr = unsafe { std::slice::from_raw_parts(msg, size) };
31 let data = &message::from_structured(
32 MonikerWithUrl { moniker: "test_moniker".try_into().unwrap(), url: "".into() },
33 managed_ptr,
34 )
35 .unwrap();
36 let item = serde_json::to_string(&data).unwrap();
37 CString::new(format!("[{}]", item)).unwrap().into_raw()
38}
39
40#[repr(C)]
48pub struct LogMessages<'a> {
49 messages: CppArray<'a, &'a LogMessage<'a>>,
50 error_str: *const c_char,
51 allocator: AliasableBox<Bump>,
52}
53
54#[derive(Error, Debug)]
55pub enum DecodeError {
56 #[error(transparent)]
57 Message(#[from] MessageError),
58 #[error(transparent)]
59 ParserError(#[from] ParseError),
60}
61
62pub type MessageParser = message::MessageParser;
63
64#[unsafe(no_mangle)]
65pub extern "C" fn fuchsia_new_message_parser() -> *mut MessageParser {
66 Box::into_raw(Box::new(MessageParser::default()))
67}
68
69#[unsafe(no_mangle)]
74pub unsafe extern "C" fn fuchsia_free_message_parser(parser: *mut MessageParser) {
75 if !parser.is_null() {
76 unsafe { drop(Box::from_raw(parser)) };
79 }
80}
81
82#[unsafe(no_mangle)]
99pub unsafe extern "C" fn fuchsia_decode_log_messages_to_struct<'a>(
100 msg: *const u8,
101 size: usize,
102 expect_extended_attribution: bool,
103 parser: *mut MessageParser,
104) -> LogMessages<'a> {
105 let allocator = AliasableBox::new(Bump::new());
106
107 let allocator_ref: &'a Bump = unsafe { allocator.get_ref() };
112
113 let maybe_parser = unsafe { parser.as_mut() };
116
117 let buf: &'a [u8] = unsafe { std::slice::from_raw_parts(msg, size) };
120
121 let messages = if let Some(parser) = maybe_parser {
122 fuchsia_decode_log_messages_to_struct_internal(buf, parser, allocator_ref)
123 } else {
124 fuchsia_decode_log_messages_to_struct_internal_legacy(
125 buf,
126 expect_extended_attribution,
127 allocator_ref,
128 )
129 };
130
131 match messages {
132 Ok(messages) => {
133 let messages: &[_] =
134 allocator_ref.alloc_slice_fill_iter(messages.into_iter().map(|m| &*m));
135 LogMessages { messages: messages.into(), error_str: std::ptr::null(), allocator }
136 }
137 Err(err) => LogMessages {
138 messages: CppArray::default(),
139 error_str: allocator_ref
140 .alloc_slice_copy(CString::new(err.to_string()).unwrap().as_bytes_with_nul())
141 .as_ptr() as *const c_char,
142 allocator,
143 },
144 }
145}
146
147fn fuchsia_decode_log_messages_to_struct_internal<'a>(
149 buf: &'a [u8],
150 parser: &mut MessageParser,
151 allocator: &'a Bump,
152) -> Result<Vec<&'a mut LogMessage<'a>>, DecodeError> {
153 let mut messages = vec![];
154 let mut current_slice = buf.as_ref();
155 let formatter = CPPMessageFormatter(allocator);
156 loop {
157 let (data, remaining) = parser.parse_next(current_slice, &formatter)?;
158
159 if let Some(data) = data {
160 messages.push(data);
161 }
162 if remaining.is_empty() {
163 break;
164 }
165 current_slice = remaining;
166 }
167
168 Ok(messages)
169}
170
171fn fuchsia_decode_log_messages_to_struct_internal_legacy<'a>(
173 buf: &'a [u8],
174 expect_extended_attribution: bool,
175 allocator: &'a Bump,
176) -> Result<Vec<&'a mut LogMessage<'a>>, DecodeError> {
177 let mut messages = vec![];
178 let mut current_slice = buf.as_ref();
179 loop {
180 let (data, remaining) = if expect_extended_attribution {
181 message::ffi::ffi_from_extended_record(current_slice, allocator)?
182 } else {
183 let (_, remaining_after_parse) =
184 diagnostics_log_encoding::parse::parse_record(current_slice)?;
185 let record_len = current_slice.len() - remaining_after_parse.len();
186 let record_slice = ¤t_slice[..record_len];
187 let (data, _) = message::ffi::ffi_from_extended_record(record_slice, allocator)?;
188 (data, remaining_after_parse)
189 };
190 messages.push(data);
191 if remaining.is_empty() {
192 break;
193 }
194 current_slice = remaining;
195 }
196
197 Ok(messages)
198}
199
200#[unsafe(no_mangle)]
205pub unsafe extern "C" fn fuchsia_free_decoded_log_message(msg: *mut c_char) {
206 let str_to_free = unsafe { CString::from_raw(msg) };
207 let _freer = str_to_free;
208}
209
210#[unsafe(no_mangle)]
215pub unsafe extern "C" fn fuchsia_free_log_messages(input: LogMessages<'_>) {
216 drop(input);
217}
218
219#[repr(C)]
221struct AliasableBox<T>(NonNull<T>);
222
223impl<T> AliasableBox<T> {
224 unsafe fn get_ref<'a>(&self) -> &'a T {
226 unsafe { self.0.as_ref() }
228 }
229}
230
231impl<T> AliasableBox<T> {
232 fn new(value: T) -> Self {
233 Self(unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(value))) })
235 }
236}
237
238impl<T> Drop for AliasableBox<T> {
239 fn drop(&mut self) {
240 unsafe {
242 let _ = Box::from_raw(self.0.as_ptr());
243 }
244 }
245}
246
247impl<T> Deref for AliasableBox<T> {
248 type Target = T;
249 fn deref(&self) -> &Self::Target {
250 unsafe { self.0.as_ref() }
252 }
253}
254
255impl<T> DerefMut for AliasableBox<T> {
256 fn deref_mut(&mut self) -> &mut Self::Target {
257 unsafe { self.0.as_mut() }
259 }
260}