servo_config/opts.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
5//! Configuration options for a single run of the servo application. Created
6//! from command line arguments.
7
8use std::default::Default;
9use std::path::PathBuf;
10use std::process;
11use std::sync::OnceLock;
12
13use serde::{Deserialize, Serialize};
14
15/// Global flags for Servo, currently set on the command line.
16#[derive(Clone, Debug, Deserialize, Serialize)]
17pub struct Opts {
18 /// `None` to disable the time profiler or `Some` to enable it with:
19 ///
20 /// - an interval in seconds to cause it to produce output on that interval.
21 /// (`i.e. -p 5`).
22 /// - a file path to write profiling info to a TSV file upon Servo's termination.
23 /// (`i.e. -p out.tsv`).
24 pub time_profiling: Option<OutputOptions>,
25
26 /// When the profiler is enabled, this is an optional path to dump a self-contained HTML file
27 /// visualizing the traces as a timeline.
28 pub time_profiler_trace_path: Option<String>,
29
30 /// True to exit on thread failure instead of displaying about:failure.
31 pub hard_fail: bool,
32
33 /// Debug options that are used by developers to control Servo
34 /// behavior for debugging purposes.
35 pub debug: DiagnosticsLogging,
36
37 /// Whether we're running in multiprocess mode.
38 pub multiprocess: bool,
39
40 /// Whether to force using ipc_channel instead of crossbeam_channel in singleprocess mode. Does
41 /// nothing in multiprocess mode.
42 pub force_ipc: bool,
43
44 /// Whether we want background hang monitor enabled or not
45 pub background_hang_monitor: bool,
46
47 /// Whether we're running inside the sandbox.
48 pub sandbox: bool,
49
50 /// Probability of randomly closing a pipeline,
51 /// used for testing the hardening of the constellation.
52 pub random_pipeline_closure_probability: Option<f32>,
53
54 /// The seed for the RNG used to randomly close pipelines,
55 /// used for testing the hardening of the constellation.
56 pub random_pipeline_closure_seed: Option<usize>,
57
58 /// Load shaders from disk.
59 pub shaders_path: Option<PathBuf>,
60
61 /// Directory for a default config directory
62 pub config_dir: Option<PathBuf>,
63
64 /// Path to PEM encoded SSL CA certificate store.
65 pub certificate_path: Option<String>,
66
67 /// Whether or not to completely ignore SSL certificate validation errors.
68 /// TODO: We should see if we can eliminate the need for this by fixing
69 /// <https://github.com/servo/servo/issues/30080>.
70 pub ignore_certificate_errors: bool,
71
72 /// Unminify Javascript.
73 pub unminify_js: bool,
74
75 /// Directory path that was created with "unminify-js"
76 pub local_script_source: Option<String>,
77
78 /// Unminify Css.
79 pub unminify_css: bool,
80
81 /// Print Progressive Web Metrics to console.
82 pub print_pwm: bool,
83}
84
85/// Debug options for Servo, currently set on the command line with -Z
86#[derive(Clone, Debug, Default, Deserialize, Serialize)]
87pub struct DiagnosticsLogging {
88 /// List all the debug options.
89 pub help: bool,
90
91 /// Print the DOM after each restyle.
92 pub style_tree: bool,
93
94 /// Log the rule tree.
95 pub rule_tree: bool,
96
97 /// Log the fragment tree after each layout.
98 pub flow_tree: bool,
99
100 /// Log the stacking context tree after each layout.
101 pub stacking_context_tree: bool,
102
103 /// Log the scroll tree after each layout.
104 ///
105 /// Displays the hierarchy of scrollable areas and their properties.
106 pub scroll_tree: bool,
107
108 /// Log the display list after each layout.
109 pub display_list: bool,
110
111 /// Log notifications when a relayout occurs.
112 pub relayout_event: bool,
113
114 /// Periodically log on which events script threads spend their processing time.
115 pub profile_script_events: bool,
116
117 /// Log style sharing cache statistics to after each restyle.
118 ///
119 /// Shows hit/miss statistics for the style sharing cache
120 pub style_statistics: bool,
121
122 /// Log garbage collection passes and their durations.
123 pub gc_profile: bool,
124}
125
126impl DiagnosticsLogging {
127 /// Create a new DiagnosticsLogging configuration.
128 ///
129 /// In non-production builds, this will automatically read and parse the
130 /// SERVO_DIAGNOSTICS environment variable if it is set.
131 pub fn new() -> Self {
132 let mut config: DiagnosticsLogging = Default::default();
133
134 // Disabled for production builds
135 #[cfg(debug_assertions)]
136 {
137 if let Ok(diagnostics_var) = std::env::var("SERVO_DIAGNOSTICS") {
138 if let Err(error) = config.extend_from_string(&diagnostics_var) {
139 eprintln!("Could not parse debug logging option: {error}");
140 }
141 }
142 }
143
144 config
145 }
146
147 /// Print available diagnostic logging options and their descriptions.
148 fn print_debug_options_usage(app: &str) {
149 fn print_option(name: &str, description: &str) {
150 println!("\t{:<35} {}", name, description);
151 }
152
153 println!(
154 "Usage: {} debug option,[options,...]\n\twhere options include\n\nOptions:",
155 app
156 );
157 print_option("help", "Show this help message");
158 print_option("style-tree", "Log the style tree after each restyle");
159 print_option("rule-tree", "Log the rule tree");
160 print_option("flow-tree", "Log the fragment tree after each layout");
161 print_option(
162 "stacking-context-tree",
163 "Log the stacking context tree after each layout",
164 );
165 print_option("scroll-tree", "Log the scroll tree after each layout");
166 print_option("display-list", "Log the display list after each layout");
167 print_option("style-stats", "Log style sharing cache statistics");
168 print_option("relayout-event", "Log when relayout occurs");
169 print_option("profile-script-events", "Log script event processing time");
170 print_option("gc-profile", "Log garbage collection statistics");
171 println!();
172
173 process::exit(0);
174 }
175
176 /// Extend the current configuration with additional options.
177 ///
178 /// Parses the string and merges any enabled options into the current configuration.
179 pub fn extend_from_string(&mut self, option_string: &str) -> Result<(), String> {
180 for option in option_string.split(',') {
181 let option = option.trim();
182 match option {
183 "help" => Self::print_debug_options_usage("servo"),
184 "display-list" => self.display_list = true,
185 "stacking-context-tree" => self.stacking_context_tree = true,
186 "flow-tree" => self.flow_tree = true,
187 "rule-tree" => self.rule_tree = true,
188 "style-tree" => self.style_tree = true,
189 "style-stats" => self.style_statistics = true,
190 "scroll-tree" => self.scroll_tree = true,
191 "gc-profile" => self.gc_profile = true,
192 "profile-script-events" => self.profile_script_events = true,
193 "relayout-event" => self.relayout_event = true,
194 "" => {},
195 _ => return Err(format!("Unknown diagnostic option: {option}")),
196 };
197 }
198
199 Ok(())
200 }
201}
202
203#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
204pub enum OutputOptions {
205 /// Database connection config (hostname, name, user, pass)
206 FileName(String),
207 Stdout(f64),
208}
209
210impl Default for Opts {
211 fn default() -> Self {
212 Self {
213 time_profiling: None,
214 time_profiler_trace_path: None,
215 hard_fail: true,
216 multiprocess: false,
217 force_ipc: false,
218 background_hang_monitor: false,
219 random_pipeline_closure_probability: None,
220 random_pipeline_closure_seed: None,
221 sandbox: false,
222 debug: Default::default(),
223 config_dir: None,
224 shaders_path: None,
225 certificate_path: None,
226 ignore_certificate_errors: false,
227 unminify_js: false,
228 local_script_source: None,
229 unminify_css: false,
230 print_pwm: false,
231 }
232 }
233}
234
235// Make Opts available globally. This saves having to clone and pass
236// opts everywhere it is used, which gets particularly cumbersome
237// when passing through the DOM structures.
238static OPTIONS: OnceLock<Opts> = OnceLock::new();
239
240/// Initialize options.
241///
242/// Should only be called once at process startup.
243/// Must be called before the first call to [get].
244pub fn initialize_options(opts: Opts) {
245 OPTIONS.set(opts).expect("Already initialized");
246}
247
248/// Get the servo options
249///
250/// If the servo options have not been initialized by calling [initialize_options], then the
251/// options will be initialized to default values. Outside of tests the options should
252/// be explicitly initialized.
253#[inline]
254pub fn get() -> &'static Opts {
255 // In unit-tests using default options reduces boilerplate.
256 // We can't use `cfg(test)` since that only is enabled when this crate
257 // is compiled in test mode.
258 // We rely on the `expect` in `initialize_options` to inform us if refactoring
259 // causes a `get` call to move before `initialize_options`.
260 OPTIONS.get_or_init(Default::default)
261}