Skip to main content

log_decoder_c_bindings/
lib.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3
4use 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/// # Safety
17///
18/// Same as for `std::slice::from_raw_parts`. Summarizing in terms of this API:
19///
20/// - `msg` must be valid for reads for `size`, and it must be properly aligned.
21/// - `msg` must point to `size` consecutive u8 values.
22/// - The `size` of the slice must be no larger than `isize::MAX`, and adding
23///   that size to data must not "wrap around" the address space. See the safety
24///   documentation of pointer::offset.
25#[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/// LogMessages struct containing log messages
41/// It is created by calling fuchsia_decode_log_messages_to_struct,
42/// and freed by calling fuchsia_free_log_messages.
43/// Log messages contain embedded pointers to the bytes from
44/// which they were created, so the memory referred to
45/// by the LogMessages must not be modified or free'd until
46/// the LogMessages are free'd.
47#[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/// # Safety
70///
71/// This should only be called with a pointer obtained through
72/// `fuchsia_new_message_parser`.
73#[unsafe(no_mangle)]
74pub unsafe extern "C" fn fuchsia_free_message_parser(parser: *mut MessageParser) {
75    if !parser.is_null() {
76        // SAFETY: parser must be a valid MessageParser constructed from
77        // fuchsia_new_message_parser.
78        unsafe { drop(Box::from_raw(parser)) };
79    }
80}
81
82/// # Safety
83///
84/// - This function is NOT thread-safe. The caller must ensure that it is not called
85///   concurrently with the same `parser` pointer.
86///
87/// Same as for `std::slice::from_raw_parts`. Summarizing in terms of this API:
88///
89/// - `msg` must be valid for reads for `size`, and it must be properly aligned.
90/// - `msg` must point to `size` consecutive u8 values.
91/// - The `size` of the slice must be no larger than `isize::MAX`, and adding
92///   that size to data must not "wrap around" the address space. See the safety
93///   documentation of pointer::offset.
94/// If identity is provided, it must contain a valid moniker and URL.
95///
96/// The returned LogMessages must be free'd with fuchsia_free_log_messages(log_messages).  Free'ing
97/// the LogMessages struct frees the bump allocator itself (and everything allocated from it).
98#[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    // SAFETY: The C++ side is responsible for managing the lifetime.  We want to return
108    // `LogMessages<'a>`, so we create a reference to the allocator here with a 'a lifetime.  We are
109    // using `AliasableBox` which allows us to move `allocator` without invalidating any of the
110    // data.
111    let allocator_ref: &'a Bump = unsafe { allocator.get_ref() };
112
113    // SAFETY: If `parser` is non-null, it must be valid and the caller guarantees exclusive access
114    // to it.
115    let maybe_parser = unsafe { parser.as_mut() };
116
117    // SAFETY: The caller guarantees that `msg` is valid for reads for `size` bytes.
118    // The returned `LogMessages<'a>` borrows from `msg` for lifetime `'a`.
119    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
147/// Decodes log messages from a FXT stream.
148fn 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
171/// Decodes log messages from a legacy FXT stream.
172fn 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 = &current_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/// # Safety
201///
202/// This should only be called with a pointer obtained through
203/// `fuchsia_decode_log_message_to_json`.
204#[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/// # Safety
211///
212/// This should only be called with `input` obtained through
213/// `fuchsia_decode_log_messages_to_struct`.
214#[unsafe(no_mangle)]
215pub unsafe extern "C" fn fuchsia_free_log_messages(input: LogMessages<'_>) {
216    drop(input);
217}
218
219/// Like `Box` except that it can be moved when there are live pointers.
220#[repr(C)]
221struct AliasableBox<T>(NonNull<T>);
222
223impl<T> AliasableBox<T> {
224    /// Returns a reference with an arbitrary lifetime.
225    unsafe fn get_ref<'a>(&self) -> &'a T {
226        // SAFETY: The caller must make this safe.
227        unsafe { self.0.as_ref() }
228    }
229}
230
231impl<T> AliasableBox<T> {
232    fn new(value: T) -> Self {
233        // SAFETY: `Box::into_raw` won't return null.
234        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        // SAFETY: We own the pointer.
241        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        // SAFETY: We own the pointer.
251        unsafe { self.0.as_ref() }
252    }
253}
254
255impl<T> DerefMut for AliasableBox<T> {
256    fn deref_mut(&mut self) -> &mut Self::Target {
257        // SAFETY: We own the pointer.
258        unsafe { self.0.as_mut() }
259    }
260}