servoshell/lib.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use cfg_if::cfg_if;
6
7#[cfg(test)]
8mod test;
9
10#[cfg(not(target_os = "android"))]
11mod backtrace;
12#[cfg(not(target_env = "ohos"))]
13mod crash_handler;
14#[cfg(not(any(target_os = "android", target_env = "ohos")))]
15pub(crate) mod desktop;
16#[cfg(any(target_os = "android", target_env = "ohos"))]
17mod egl;
18#[cfg(not(any(target_os = "android", target_env = "ohos")))]
19mod panic_hook;
20mod parser;
21mod prefs;
22#[cfg(not(any(target_os = "android", target_env = "ohos")))]
23mod resources;
24mod running_app_state;
25
26pub mod platform {
27 #[cfg(target_os = "macos")]
28 pub use crate::platform::macos::deinit;
29
30 #[cfg(target_os = "macos")]
31 pub mod macos;
32
33 #[cfg(not(target_os = "macos"))]
34 pub fn deinit(_clean_shutdown: bool) {}
35}
36
37#[cfg(not(any(target_os = "android", target_env = "ohos")))]
38pub fn main() {
39 desktop::cli::main()
40}
41
42pub fn init_crypto() {
43 rustls::crypto::aws_lc_rs::default_provider()
44 .install_default()
45 .expect("Error initializing crypto provider");
46}
47
48pub fn init_tracing(filter_directives: Option<&str>) {
49 #[cfg(not(feature = "tracing"))]
50 {
51 if filter_directives.is_some() {
52 log::debug!("The tracing feature was not selected - ignoring trace filter directives");
53 }
54 }
55 #[cfg(feature = "tracing")]
56 {
57 use tracing_subscriber::layer::SubscriberExt;
58 let subscriber = tracing_subscriber::registry();
59
60 #[cfg(feature = "tracing-perfetto")]
61 let subscriber = {
62 // Set up a PerfettoLayer for performance tracing.
63 // The servo.pftrace file can be uploaded to https://ui.perfetto.dev for analysis.
64 let file = std::fs::File::create("servo.pftrace").unwrap();
65 let perfetto_layer = tracing_perfetto::PerfettoLayer::new(std::sync::Mutex::new(file))
66 .with_filter_by_marker(|field_name| field_name == "servo_profiling")
67 .with_debug_annotations(true);
68 subscriber.with(perfetto_layer)
69 };
70
71 #[cfg(feature = "tracing-hitrace")]
72 let subscriber = {
73 // Set up a HitraceLayer for performance tracing.
74 subscriber.with(HitraceLayer::default())
75 };
76
77 // Filter events and spans by the directives in SERVO_TRACING, using EnvFilter as a global filter.
78 // <https://docs.rs/tracing-subscriber/0.3.18/tracing_subscriber/layer/index.html#global-filtering>
79 let filter_builder = tracing_subscriber::EnvFilter::builder()
80 .with_default_directive(tracing::level_filters::LevelFilter::OFF.into());
81 let filter = if let Some(filters) = &filter_directives {
82 filter_builder.parse_lossy(filters)
83 } else {
84 filter_builder
85 .with_env_var("SERVO_TRACING")
86 .from_env_lossy()
87 };
88
89 let subscriber = subscriber.with(filter);
90
91 // Same as SubscriberInitExt::init, but avoids initialising the tracing-log compat layer,
92 // since it would break Servo’s FromScriptLogger and FromEmbederLogger.
93 // <https://docs.rs/tracing-subscriber/0.3.18/tracing_subscriber/util/trait.SubscriberInitExt.html#method.init>
94 // <https://docs.rs/tracing/0.1.40/tracing/#consuming-log-records>
95 tracing::subscriber::set_global_default(subscriber)
96 .expect("Failed to set tracing subscriber");
97 }
98}
99
100pub const VERSION: &str = concat!("Servo ", env!("CARGO_PKG_VERSION"), "-", env!("GIT_SHA"));
101
102/// Plumbs tracing spans into HiTrace, with the following caveats:
103///
104/// - We ignore spans unless they have a `servo_profiling` field.
105/// - We map span entry ([`Layer::on_enter`]) to `OH_HiTrace_StartTrace(metadata.name())`.
106/// - We map span exit ([`Layer::on_exit`]) to `OH_HiTrace_FinishTrace()`.
107///
108/// As a result, within each thread, spans must exit in reverse order of their entry, otherwise the
109/// resultant profiling data will be incorrect (see the section below). This is not necessarily the
110/// case for tracing spans, since there can be multiple [trace trees], so we check that this
111/// invariant is upheld when debug assertions are enabled, logging errors if it is violated.
112///
113/// [trace trees]: https://docs.rs/tracing/0.1.40/tracing/span/index.html#span-relationships
114///
115/// # Uniquely identifying spans
116///
117/// We need to ensure that the start and end points of one span are not mixed up with other spans.
118/// For now, we use the HiTrace [synchronous API], which restricts how spans must behave.
119///
120/// In the HiTrace [synchronous API], spans must have stack-like behaviour, because spans are keyed
121/// entirely on their *name* string, and OH_HiTrace_FinishTrace always ends the most recent span.
122/// While synchronous API spans are thread-local, callers could still violate this invariant with
123/// reentrant or asynchronous code.
124///
125/// In the [asynchronous API], spans are keyed on a (*name*,*taskId*) pair, where *name* is again
126/// a string, and *taskId* is an arbitrary [`i32`]. This makes *taskId* a good place for a unique
127/// identifier, but asynchronous spans can cross thread boundaries, so the identifier needs to be
128/// temporally unique in the whole process.
129///
130/// Tracing spans have such an identifier ([`Id`]), but they’re [`u64`]-based, and their format
131/// is an internal implementation detail of the [`Subscriber`]. For [`Registry`], those values
132/// [come from] a [packed representation] of a generation number, thread number, page number, and
133/// variable-length index. This makes them hard to compress robustly into an [`i32`].
134///
135/// If we move to the asynchronous API, we will need to generate our own *taskId* values, perhaps
136/// by combining some sort of thread id with a thread-local atomic counter. [`ThreadId`] is opaque
137/// in stable Rust, and converts to a [`u64`] in unstable Rust, so we would also need to make our
138/// own thread ids, perhaps by having a global atomic counter cached in a thread-local.
139///
140/// [synchronous API]: https://docs.rs/hitrace-sys/0.1.2/hitrace_sys/fn.OH_HiTrace_StartTrace.html
141/// [asynchronous API]: https://docs.rs/hitrace-sys/0.1.2/hitrace_sys/fn.OH_HiTrace_StartAsyncTrace.html
142/// [`Registry`]: tracing_subscriber::Registry
143/// [come from]: https://docs.rs/tracing-subscriber/0.3.18/src/tracing_subscriber/registry/sharded.rs.html#237-269
144/// [packed representation]: https://docs.rs/sharded-slab/0.1.7/sharded_slab/trait.Config.html
145/// [`ThreadId`]: std::thread::ThreadId
146#[cfg(feature = "tracing-hitrace")]
147#[derive(Default)]
148struct HitraceLayer {}
149
150cfg_if! {
151 if #[cfg(feature = "tracing-hitrace")] {
152 use std::cell::RefCell;
153
154 use tracing::span::Id;
155 use tracing::Subscriber;
156 use tracing_subscriber::Layer;
157
158 #[cfg(debug_assertions)]
159 thread_local! {
160 /// Stack of span names, to ensure the HiTrace synchronous API is not misused.
161 static HITRACE_NAME_STACK: RefCell<Vec<String>> = RefCell::default();
162 }
163
164 impl<S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>>
165 Layer<S> for HitraceLayer
166 {
167 fn on_enter(&self, id: &Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
168 if let Some(metadata) = ctx.metadata(id) {
169 // TODO: is this expensive? Would extensions be faster?
170 // <https://docs.rs/tracing-subscriber/0.3.18/tracing_subscriber/registry/struct.ExtensionsMut.html>
171 if metadata.fields().field("servo_profiling").is_some() {
172 #[cfg(debug_assertions)]
173 HITRACE_NAME_STACK.with_borrow_mut(|stack|
174 stack.push(metadata.name().to_owned()));
175
176 hitrace::start_trace(
177 &std::ffi::CString::new(metadata.name())
178 .expect("Failed to convert str to CString"),
179 );
180 }
181 }
182 }
183
184 fn on_exit(&self, id: &Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
185 if let Some(metadata) = ctx.metadata(id) {
186 if metadata.fields().field("servo_profiling").is_some() {
187 hitrace::finish_trace();
188
189 #[cfg(debug_assertions)]
190 HITRACE_NAME_STACK.with_borrow_mut(|stack| {
191 if stack.last().map(|name| &**name) != Some(metadata.name()) {
192 log::error!(
193 "Tracing span out of order: {} (stack: {:?})",
194 metadata.name(),
195 stack
196 );
197 }
198 if !stack.is_empty() {
199 stack.pop();
200 }
201 });
202 }
203 }
204 }
205 }
206 }
207}