-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathdriver.rs
2210 lines (1885 loc) · 80.7 KB
/
driver.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2022 the Tectonic Project
// Licensed under the MIT License.
#![deny(missing_docs)]
//! The high-level Tectonic document processing interface.
//!
//! The main struct in this module is [`ProcessingSession`], which knows how to
//! run (and re-run if necessary) the various engines in the right order. Such a
//! session can be created with a [`ProcessingSessionBuilder`], which you might
//! obtain from a [`tectonic_docmodel::document::Document`] using the
//! [`crate::docmodel::DocumentExt::setup_session`] extension method, if you’re
//! using the Tectonic document model. You can set one up manually if not.
//!
//! For an example of how to use this module, see `src/bin/tectonic/main.rs`,
//! which contains tectonic's main CLI program.
use byte_unit::Byte;
use quick_xml::{events::Event, NsReader};
use std::{
collections::{HashMap, HashSet},
fs::File,
io::{Cursor, Read, Write},
path::{Path, PathBuf},
process::Command,
rc::Rc,
result::Result as StdResult,
str::FromStr,
time::{Duration, SystemTime},
};
use tectonic_bridge_core::{CoreBridgeLauncher, DriverHooks, SecuritySettings, SystemRequestError};
use tectonic_bundles::Bundle;
use tectonic_engine_spx2html::AssetSpecification;
use tectonic_io_base::{
digest::DigestData,
filesystem::{FilesystemIo, FilesystemPrimaryInputIo},
stdstreams::{BufferedPrimaryIo, GenuineStdoutIo},
InputHandle, IoProvider, OpenResult, OutputHandle,
};
use crate::{
ctry, errmsg,
errors::{ChainErrCompatExt, ErrorKind, Result},
io::{
format_cache::FormatCache,
memory::{MemoryFileCollection, MemoryIo},
InputOrigin,
},
status::StatusBackend,
tt_error, tt_note, tt_warning,
unstable_opts::UnstableOptions,
BibtexEngine, Spx2HtmlEngine, TexEngine, TexOutcome, XdvipdfmxEngine,
};
/// Different patterns with which files may have been accessed by the
/// underlying engines. Once a file is marked as ReadThenWritten or
/// WrittenThenRead, its pattern does not evolve further.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AccessPattern {
/// This file is only ever read.
Read,
/// This file is only ever written. This suggests that it is
/// a final output of the processing session.
Written,
/// This file is read, then written. We call this a "circular" access
/// pattern. Multiple passes of an engine will result in outputs that
/// change if this file's contents change, or if the file did not exist at
/// the time of the first pass.
ReadThenWritten,
/// This file is written, then read. We call this a "temporary" access
/// pattern. This file is likely a temporary buffer that is not of
/// interest to the user.
WrittenThenRead,
}
/// A summary of the I/O that happened on a file. We record its access
/// pattern; where it came from, if it was used as an input; the cryptographic
/// digest of the file when it was last read; and the cryptographic digest of
/// the file as it was last written.
#[derive(Clone, Debug, Eq, PartialEq)]
struct FileSummary {
access_pattern: AccessPattern,
/// If this file was read, where did it come from?
pub input_origin: InputOrigin,
/// If this file was read, this is the digest of its contents at the time it was *first* read.
/// The "first" is significant for files that were read and then written (for example, `.aux`
/// files).
///
/// There's some chance that this will be `None` even if the file was read. Tectonic makes an
/// effort to compute the digest as the data is being read from the file, but this can fail if
/// tex decides to seek in the file as it is being written.
pub read_digest: Option<DigestData>,
/// If this file was written, this is the digest of its contents at the time it was last
/// written.
pub write_digest: Option<DigestData>,
got_written_to_disk: bool,
}
impl FileSummary {
fn new(access_pattern: AccessPattern, input_origin: InputOrigin) -> FileSummary {
FileSummary {
access_pattern,
input_origin,
read_digest: None,
write_digest: None,
got_written_to_disk: false,
}
}
}
/// The different types of output files that tectonic knows how to produce.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum OutputFormat {
/// A '.aux' file.
Aux,
/// A '.html' file.
Html,
/// An extended DVI file.
Xdv,
/// A '.pdf' file.
#[default]
Pdf,
/// A '.fmt' file, for initializing the TeX engine.
Format,
}
impl FromStr for OutputFormat {
type Err = &'static str;
fn from_str(a_str: &str) -> StdResult<Self, Self::Err> {
match a_str {
"aux" => Ok(OutputFormat::Aux),
"html" => Ok(OutputFormat::Html),
"xdv" => Ok(OutputFormat::Xdv),
"pdf" => Ok(OutputFormat::Pdf),
"fmt" => Ok(OutputFormat::Format),
_ => Err("unsupported or unknown format"),
}
}
}
/// The different types of "passes" that [`ProcessingSession`] knows how to run. See
/// [`ProcessingSession::run`] for more details.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum PassSetting {
/// The default pass, which repeatedly runs TeX and BibTeX until it doesn't need to any more.
#[default]
Default,
/// Just run the TeX engine once.
Tex,
/// Like the default pass, but runs BibTeX once first, before doing anything else.
BibtexFirst,
}
impl FromStr for PassSetting {
type Err = &'static str;
fn from_str(a_str: &str) -> StdResult<Self, Self::Err> {
match a_str {
"default" => Ok(PassSetting::Default),
"bibtex_first" => Ok(PassSetting::BibtexFirst),
"tex" => Ok(PassSetting::Tex),
_ => Err("unsupported or unknown pass setting"),
}
}
}
/// Different places from which the "primary input" might originate.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
enum PrimaryInputMode {
/// This process's standard input.
#[default]
Stdin,
/// A path on the filesystem.
Path(PathBuf),
/// An in-memory buffer.
Buffer(Vec<u8>),
}
/// Different places where the output files might land.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
enum OutputDestination {
/// The "sensible" default. Files will land in the same directory as the
/// input file, or the current working directory if the input is something
/// without a path (such as standard input).
#[default]
Default,
/// Files should land in this particular directory.
Path(PathBuf),
/// Files will not be written to disk. The code running the engine should
/// examine the memory layer of the I/O stack to obtain the output files.
Nowhere,
}
/// The subset of the driver state that is captured when running a C/C++ engine.
///
/// The main purpose of this type is to implement the [`DriverHooks`] trait,
/// which is defined by the `tectonic_core_bridge` crate and defines that
/// interface that the C/C++ processing engines can use to access the outside
/// world. While these engines are running, they hold a mutable reference to
/// these data, so it is helpful to separate them out into a sub-structure of
/// the larger [`ProcessingSession`] type.
///
/// Due to the needs of the C/C++ engines, this means that [`BridgeState`] must
/// hold the fully-prepared I/O stack information as well as the "event"
/// information that helps the driver implement the rerun logic.
struct BridgeState {
/// I/O for the primary input source. This is boxed since it can come
/// from different sources: maybe a file, maybe an in-memory buffer, etc.
primary_input: Box<dyn IoProvider>,
/// I/O for the main backing bundle. This is boxed since there are several
/// different bundle implementations that might be used at runtime.
bundle: Box<dyn Bundle>,
/// Memory buffering for files written during processing.
mem: MemoryIo,
/// The main filesystem backing for input files in the project.
filesystem: FilesystemIo,
/// Extra paths we search through for files.
extra_search_paths: Vec<FilesystemIo>,
/// Additional filesystem backing used if "shell escape" functionality is
/// activated. If None, we take that to mean that shell-escape is
/// disallowed. We have to use a persistent filesystem directory for this
/// since some packages perform a whole series of shell-escape operations
/// that assume continuity from one to the next.
shell_escape_work: Option<FilesystemIo>,
/// I/O for saving any generated format files.
format_cache: FormatCache,
/// Possible redirection of "standard output" writes to actual standard
/// output.
genuine_stdout: Option<GenuineStdoutIo>,
/// A possible alternative "primary input" when generating format files. If
/// Some(), we're in format-file generation mode; in most cases this is
/// None.
format_primary: Option<BufferedPrimaryIo>,
/// The I/O events that occurred while processing.
events: HashMap<String, FileSummary>,
}
impl BridgeState {
/// Tell the IoProvider implementation of the bridge state to enter "format
/// mode", in which the "primary input" is fixed, based on the requested
/// format file name, and filesystem I/O is bypassed.
fn enter_format_mode(&mut self, format_file_name: &str) {
self.format_primary = Some(BufferedPrimaryIo::from_text(format!(
"\\input {format_file_name}"
)));
}
/// Leave "format mode".
fn leave_format_mode(&mut self) {
self.format_primary = None;
}
/// Invoke an external tool as a pass in the processing pipeline.
fn external_tool_pass(
&mut self,
tool: &ExternalToolPass,
status: &mut dyn StatusBackend,
) -> Result<()> {
status.note_highlighted("Running external tool ", &tool.argv[0], " ...");
// Process the command arguments. Filenames appearing in the arguments
// are treated as "requirements" that will be placed in the tool's
// working directory.
let mut cmd = Command::new(&tool.argv[0]);
let mut read_files = tool.extra_requires.clone();
{
let mem_files = &*self.mem.files.borrow();
for arg in &tool.argv[1..] {
cmd.arg(arg);
if mem_files.contains_key(arg) {
read_files.insert(arg.to_owned());
}
}
}
// Now that we're validated, write those files to disk so that the tool
// can actually use them.
let tempdir = ctry!(
tempfile::Builder::new().tempdir();
"can't create temporary directory for external tool"
);
{
for name in &read_files {
// If a relative parent is found in the file to open, this fn
// does not properly handle that. Thus, throw an error.
if name.contains("../") {
return Err(errmsg!(
"relative parent paths are not supported for the \
external tool. Got path `{}`.",
name
));
}
let mut ih = ctry!(
self.input_open_name(name, status).must_exist();
"can't open path `{}`", name
);
// If the input path is absolute, we don't need to create a
// version in the tempdir, and in fact the current
// implementation below will blow away the input file. However,
// we do want to try to open the input so that it gets
// registered with the I/O tracking system.
let path = Path::new(name);
if path.is_absolute() {
continue;
}
let tool_path = tempdir.path().join(name);
let tool_parent = tool_path.parent().unwrap();
if tool_parent != tempdir.path() {
ctry!(
std::fs::create_dir_all(tool_parent);
"failed to create sub directory `{}`", tool_parent.display()
);
}
let mut f = ctry!(
File::create(&tool_path);
"failed to create file `{}`", tool_path.display()
);
ctry!(
std::io::copy(&mut ih, &mut f);
"failed to write file `{}`", tool_path.display()
);
}
}
// Now we can actually run the command.
let output = cmd.current_dir(tempdir.path()).output()?;
if let Some(0) = output.status.code() {
} else {
tt_error!(
status,
"the external tool exited with an error code; its stdout was:\n"
);
status.dump_error_logs(&output.stdout[..]);
tt_error!(status, "its stderr was:\n");
status.dump_error_logs(&output.stderr[..]);
return if let Some(n) = output.status.code() {
Err(errmsg!("the external tool exited with error code {}", n))
} else {
Err(errmsg!("the external tool was terminated by a signal"))
};
}
// Search for any files that the tool created, and import them into the
// memory layer.
for entry in std::fs::read_dir(tempdir.path())? {
let entry = entry?;
if !entry.file_type()?.is_file() {
continue;
}
if let Some(basename) = entry.file_name().to_str() {
if !self.mem.files.borrow().contains_key(basename) {
let path = entry.path();
let mut data = Vec::new();
let mut f = ctry!(
File::open(&path);
"failed to open tool-created file `{}`", path.display()
);
ctry!(
f.read_to_end(&mut data);
"failed to read tool-created file `{}`", path.display()
);
self.mem.create_entry(basename, data);
self.events.insert(
basename.to_owned(),
FileSummary::new(AccessPattern::Written, InputOrigin::NotInput),
);
}
}
}
// Mark the input files as having been read, and we're done.
for name in &read_files {
let summ = self.events.get_mut(name).unwrap();
summ.access_pattern = match summ.access_pattern {
AccessPattern::Written => AccessPattern::WrittenThenRead,
c => c, // identity mapping makes sense for remaining options
};
}
Ok(())
}
// Get the names of all intermediate files which are generated from
// previous passes.
fn get_intermediate_file_names(&self) -> Vec<String> {
// Currently, we only consider files in memory as intermediate files.
return self.mem.files.borrow().keys().cloned().collect();
}
}
macro_rules! bridgestate_ioprovider_try {
($provider:expr, $($inner:tt)+) => {
let r = $provider.$($inner)+;
match r {
OpenResult::NotAvailable => {},
_ => return r,
};
}
}
macro_rules! bridgestate_ioprovider_cascade {
($self:ident, $($inner:tt)+) => {
if let Some(ref mut p) = $self.genuine_stdout {
bridgestate_ioprovider_try!(p, $($inner)+);
}
// See enter_format_mode above. If creating a format file, disable local
// filesystem I/O.
let use_fs = if let Some(ref mut p) = $self.format_primary {
bridgestate_ioprovider_try!(p, $($inner)+);
false
} else {
bridgestate_ioprovider_try!($self.primary_input, $($inner)+);
true
};
bridgestate_ioprovider_try!($self.mem, $($inner)+);
if use_fs {
bridgestate_ioprovider_try!($self.filesystem, $($inner)+);
// With this ordering, we are preventing files created by
// shell-escape commands from overwriting/replacing source files.
// This seems very much like the behavior we want, unless there are
// some freaky shell-escape uses that depend on this behavior.
if let Some(ref mut p) = $self.shell_escape_work {
bridgestate_ioprovider_try!(p, $($inner)+);
}
// Extra search paths. This has higher priority than bundles but lower than current
// working dir to support the use case of overriding broken bundles (see issue #816).
for fsio in $self.extra_search_paths.iter_mut() {
bridgestate_ioprovider_try!(fsio, $($inner)+);
}
}
bridgestate_ioprovider_try!($self.bundle.as_ioprovider_mut(), $($inner)+);
bridgestate_ioprovider_try!($self.format_cache, $($inner)+);
return OpenResult::NotAvailable;
}
}
impl IoProvider for BridgeState {
fn output_open_name(&mut self, name: &str) -> OpenResult<OutputHandle> {
let r = (|| {
bridgestate_ioprovider_cascade!(self, output_open_name(name));
})();
if let OpenResult::Ok(_) = r {
if let Some(summ) = self.events.get_mut(name) {
summ.access_pattern = match summ.access_pattern {
AccessPattern::Read => AccessPattern::ReadThenWritten,
c => c, // identity mapping makes sense for remaining options
};
} else {
self.events.insert(
name.to_owned(),
FileSummary::new(AccessPattern::Written, InputOrigin::NotInput),
);
}
}
r
}
fn output_open_stdout(&mut self) -> OpenResult<OutputHandle> {
let r = (|| {
bridgestate_ioprovider_cascade!(self, output_open_stdout());
})();
// Life is easier if we track stdout in the same way that we do other
// output files.
if let OpenResult::Ok(_) = r {
if let Some(summ) = self.events.get_mut("") {
summ.access_pattern = match summ.access_pattern {
AccessPattern::Read => AccessPattern::ReadThenWritten,
c => c, // identity mapping makes sense for remaining options
};
} else {
self.events.insert(
String::from(""),
FileSummary::new(AccessPattern::Written, InputOrigin::NotInput),
);
}
}
r
}
fn input_open_name(
&mut self,
name: &str,
status: &mut dyn StatusBackend,
) -> OpenResult<InputHandle> {
match self.input_open_name_with_abspath(name, status) {
OpenResult::Ok((ih, _path)) => OpenResult::Ok(ih),
OpenResult::Err(e) => OpenResult::Err(e),
OpenResult::NotAvailable => OpenResult::NotAvailable,
}
}
fn input_open_name_with_abspath(
&mut self,
name: &str,
status: &mut dyn StatusBackend,
) -> OpenResult<(InputHandle, Option<PathBuf>)> {
let r = (|| {
bridgestate_ioprovider_cascade!(self, input_open_name_with_abspath(name, status));
})();
match r {
OpenResult::Ok((ref ih, ref _path)) => {
if let Some(summ) = self.events.get_mut(name) {
summ.access_pattern = match summ.access_pattern {
AccessPattern::Written => AccessPattern::WrittenThenRead,
c => c, // identity mapping makes sense for remaining options
};
} else {
self.events.insert(
name.to_owned(),
FileSummary::new(AccessPattern::Read, ih.origin()),
);
}
}
OpenResult::NotAvailable => {
// For the purposes of file access pattern tracking, an attempt to
// open a nonexistent file counts as a read of a zero-size file. I
// don't see how such a file could have previously been written, but
// let's use the full update logic just in case.
if let Some(summ) = self.events.get_mut(name) {
summ.access_pattern = match summ.access_pattern {
AccessPattern::Written => AccessPattern::WrittenThenRead,
c => c, // identity mapping makes sense for remaining options
};
} else {
// Unlike other cases, here we need to fill in the read_digest. `None`
// is not an appropriate value since, if the file is written and then
// read again later, the `None` will be overwritten; but what matters
// is the contents of the file the very first time it was read.
let mut fs = FileSummary::new(AccessPattern::Read, InputOrigin::NotInput);
fs.read_digest = Some(DigestData::of_nothing());
self.events.insert(name.to_owned(), fs);
}
}
OpenResult::Err(_) => {}
}
r
}
fn input_open_primary(&mut self, status: &mut dyn StatusBackend) -> OpenResult<InputHandle> {
match self.input_open_primary_with_abspath(status) {
OpenResult::Ok((ih, _path)) => OpenResult::Ok(ih),
OpenResult::Err(e) => OpenResult::Err(e),
OpenResult::NotAvailable => OpenResult::NotAvailable,
}
}
fn input_open_primary_with_abspath(
&mut self,
status: &mut dyn StatusBackend,
) -> OpenResult<(InputHandle, Option<PathBuf>)> {
bridgestate_ioprovider_cascade!(self, input_open_primary_with_abspath(status));
}
fn input_open_format(
&mut self,
name: &str,
status: &mut dyn StatusBackend,
) -> OpenResult<InputHandle> {
let r = (|| {
bridgestate_ioprovider_cascade!(self, input_open_format(name, status));
})();
if let OpenResult::Ok(ref ih) = r {
if let Some(summ) = self.events.get_mut(name) {
summ.access_pattern = match summ.access_pattern {
AccessPattern::Written => AccessPattern::WrittenThenRead,
c => c, // identity mapping makes sense for remaining options
};
} else {
self.events.insert(
name.to_owned(),
FileSummary::new(AccessPattern::Read, ih.origin()),
);
}
}
r
}
}
impl DriverHooks for BridgeState {
fn io(&mut self) -> &mut dyn IoProvider {
self
}
fn event_output_closed(
&mut self,
name: String,
digest: DigestData,
_status: &mut dyn StatusBackend,
) {
let summ = self
.events
.get_mut(&name)
.expect("closing file that wasn't opened?");
summ.write_digest = Some(digest);
}
fn event_input_closed(
&mut self,
name: String,
digest: Option<DigestData>,
_status: &mut dyn StatusBackend,
) {
let summ = self
.events
.get_mut(&name)
.expect("closing file that wasn't opened?");
// It's what was in the file the *first* time that it was read that
// matters, so don't replace the read digest if it's already got one.
if summ.read_digest.is_none() {
summ.read_digest = digest;
}
}
fn sysrq_shell_escape(
&mut self,
command: &str,
status: &mut dyn StatusBackend,
) -> StdResult<(), SystemRequestError> {
#[cfg(unix)]
const SHELL: &[&str] = &["sh", "-c"];
#[cfg(windows)]
const SHELL: &[&str] = &["cmd.exe", "/c"];
// Write any TeX-created files in the memory cache to the shell-escape
// working directory, since the shell-escape program may need to use
// them. (This is the case for `minted`.) We basically just hope that
// nothing will want to access the actual TeX source, which will live in
// a different directory.
//
// This is suboptimally slow since we'll be rewriting the same files
// repeatedly for repeated shell-escape invocations, but I don't feel
// like optimizing that I/O right now. Shell-escape is a gnarly hack
// anyway!
if let Some(work) = self.shell_escape_work.as_ref() {
for (name, file) in &*self.mem.files.borrow() {
// If it's in the `mem` backend, it's of interest here ...
// unless it's stdout.
if name == self.mem.stdout_key() {
continue;
}
let real_path = work.root().join(name);
let mut f = File::create(&real_path).map_err(|e| {
tt_error!(status, "failed to create file `{}`", real_path.display(); e.into());
SystemRequestError::Failed
})?;
f.write_all(&file.data).map_err(|e| {
tt_error!(status, "failed to write file `{}`", real_path.display(); e.into());
SystemRequestError::Failed
})?;
}
// Now we can actually run the command.
tt_note!(status, "running shell command: `{}`", command);
match Command::new(SHELL[0])
.args(&SHELL[1..])
.arg(command)
.current_dir(work.root())
.status()
{
Ok(s) => match s.code() {
Some(0) => Ok(()),
Some(n) => {
tt_warning!(status, "command exited with error code {}", n);
Err(SystemRequestError::Failed)
}
None => {
tt_warning!(status, "command was terminated by signal");
Err(SystemRequestError::Failed)
}
},
Err(err) => {
tt_warning!(status, "failed to run command"; err.into());
Err(SystemRequestError::Failed)
}
}
// That's it! We shouldn't clean up here, because there might be
// multiple shell-escapes that build up in sequence, and any new
// files created by the shell-escape command will be picked up by
// the filesystem I/O.
} else {
// No shell-escape work directory. This "shouldn't happen" but means
// that shell-escape is supposed to be disabled anyway!
tt_error!(
status,
"the engine requested a shell-escape invocation but it's currently disabled"
);
Err(SystemRequestError::NotAllowed)
}
}
}
/// Possible modes for handling shell-escape functionality
#[derive(Clone, Debug, Default, Eq, PartialEq)]
enum ShellEscapeMode {
/// "Default" mode: shell-escape is disabled, unless it's been turned on in
/// the unstable options, in which case it will be allowed through a
/// temporary directory.
#[default]
Defaulted,
/// Shell-escape is disabled, overriding any unstable-option setting.
Disabled,
/// Shell-escape is enabled, using a temporary work directory managed by the
/// processing session. The work directory will be deleted after processing
/// completes.
TempDir,
/// Shell-escape is enabled, using some other work directory that is managed
/// externally. The processing session won't delete this directory.
ExternallyManagedDir(PathBuf),
}
/// A custom extra pass that invokes an external tool.
///
/// This is bad for reproducibility but comes in handy.
#[derive(Debug)]
struct ExternalToolPass {
argv: Vec<String>,
extra_requires: HashSet<String>,
}
/// A builder-style interface for creating a [`ProcessingSession`].
///
/// This uses standard builder patterns. The `Default` implementation defaults
/// to restrictive security settings that disable all known-insecure features
/// that could be abused by untrusted inputs. Use
/// [`ProcessingSessionBuilder::new_with_security()`] in order to have the
/// option to enable potentially-insecure features such as shell-escape.
#[derive(Default)]
pub struct ProcessingSessionBuilder {
security: SecuritySettings,
primary_input: PrimaryInputMode,
tex_input_name: Option<String>,
output_dest: OutputDestination,
filesystem_root: Option<PathBuf>,
format_name: Option<String>,
format_cache_path: Option<PathBuf>,
output_format: OutputFormat,
makefile_output_path: Option<PathBuf>,
hidden_input_paths: HashSet<PathBuf>,
pass: PassSetting,
reruns: Option<usize>,
print_stdout: bool,
bundle: Option<Box<dyn Bundle>>,
keep_intermediates: bool,
keep_logs: bool,
synctex: bool,
build_date: Option<SystemTime>,
unstables: UnstableOptions,
shell_escape_mode: ShellEscapeMode,
html_assets_spec_path: Option<String>,
html_precomputed_assets: Option<AssetSpecification>,
html_do_not_emit_files: bool,
html_do_not_emit_assets: bool,
}
impl ProcessingSessionBuilder {
/// Create a new builder with customized security settings.
pub fn new_with_security(security: SecuritySettings) -> Self {
ProcessingSessionBuilder {
security,
..Default::default()
}
}
/// Sets the path to the primary input file.
///
/// If a primary input path is not specified, we will default to reading it from stdin.
pub fn primary_input_path<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.primary_input = PrimaryInputMode::Path(p.as_ref().to_owned());
self
}
/// Sets the primary input to be a caller-specified buffer.
///
/// If neither this nor a primary input path is specified, we will default
/// to reading the primary input from stdin.
pub fn primary_input_buffer(&mut self, buf: &[u8]) -> &mut Self {
self.primary_input = PrimaryInputMode::Buffer(buf.to_owned());
self
}
/// Sets the name of the main input file.
///
/// This value will be used to infer the names of the output files; for example, if
/// `tex_input_name` is set to `"texput.tex"` then the pdf output file will be `"texput.pdf"`.
/// As such, this parameter is mandatory, even if the real input is coming from stdin (if it is
/// not provided, [`ProcessingSessionBuilder::create`] will panic).
pub fn tex_input_name(&mut self, s: &str) -> &mut Self {
self.tex_input_name = Some(s.to_owned());
self
}
/// Set the directory that serves as the root for finding files on disk.
///
/// If unspecified, and there is a primary input file, the directory
/// containing that file will serve as the filesystem root. Otherwise, it is
/// set to the current directory.
pub fn filesystem_root<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.filesystem_root = Some(p.as_ref().to_owned());
self
}
/// A path to the directory where output files should be created.
///
/// This will default to the directory containing `primary_input_path`, or
/// the current working directory if the primary input is coming from
/// stdin.
pub fn output_dir<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.output_dest = OutputDestination::Path(p.as_ref().to_owned());
self
}
/// Indicate that output files should not be written to disk.
///
/// By default, output files will be written to the directory containing
/// `primary_input_path`, or the current working directory if the primary
/// input is coming from stdin.
pub fn do_not_write_output_files(&mut self) -> &mut Self {
self.output_dest = OutputDestination::Nowhere;
self
}
/// The name of the `.fmt` file used to initialize the TeX engine.
///
/// This file does not necessarily have to exist already; it will be created
/// if it doesn't. This parameter is mandatory (if it is not provided,
/// [`ProcessingSessionBuilder::create`] will panic).
pub fn format_name(&mut self, p: &str) -> &mut Self {
self.format_name = Some(p.to_owned());
self
}
/// Sets the path to the format file cache.
///
/// This is used to, well, cache format files, which are generated as
/// needed from the backing bundle. Defaults to the same directory as the
/// input file, or PWD if the input is a non-file (such as standard
/// input).
pub fn format_cache_path<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.format_cache_path = Some(p.as_ref().to_owned());
self
}
/// The type of output to create.
pub fn output_format(&mut self, f: OutputFormat) -> &mut Self {
self.output_format = f;
self
}
/// If set, a makefile will be written out at the given path.
pub fn makefile_output_path<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.makefile_output_path = Some(p.as_ref().to_owned());
self
}
/// Which kind of pass should the `ProcessingSession` run? Defaults to `PassSetting::Default`
/// (duh).
pub fn pass(&mut self, p: PassSetting) -> &mut Self {
self.pass = p;
self
}
/// If set, and if the pass is set to `PassSetting::Default`, the TeX engine will be re-run
/// *exactly* this many times.
///
/// If `reruns` is unset, we will auto-detect how many times the TeX engine needs to be re-run.
pub fn reruns(&mut self, r: usize) -> &mut Self {
self.reruns = Some(r);
self
}
/// If set to `true`, stdout from the TeX engine will be forwarded to actual stdout. (By
/// default, it will be suppressed.)
pub fn print_stdout(&mut self, p: bool) -> &mut Self {
self.print_stdout = p;
self
}
/// Marks a path as hidden, meaning that the TeX engine will pretend that it doesn't exist in
/// the filesystem.
pub fn hide<P: AsRef<Path>>(&mut self, p: P) -> &mut Self {
self.hidden_input_paths.insert(p.as_ref().to_owned());
self
}
/// Sets the bundle, which the various engines will use for finding style files, font files,
/// etc.
pub fn bundle(&mut self, b: Box<dyn Bundle>) -> &mut Self {
self.bundle = Some(b);
self
}
/// If set to `true`, various intermediate files will be written out to the filesystem.
pub fn keep_intermediates(&mut self, k: bool) -> &mut Self {
self.keep_intermediates = k;
self
}
/// If set to `true`, '.log' and '.blg' files will be written out to the filesystem.
pub fn keep_logs(&mut self, k: bool) -> &mut Self {
self.keep_logs = k;
self
}
/// If set to `true`, tex files will be compiled using synctex information.
pub fn synctex(&mut self, s: bool) -> &mut Self {
self.synctex = s;
self
}
/// Sets the date and time of the processing session.
/// See `TexEngine::build_date` for mor information.
pub fn build_date(&mut self, date: SystemTime) -> &mut Self {
self.build_date = Some(date);
self
}
/// Configures the date and time of the processing session from the environment:
/// If `SOURCE_DATE_EPOCH` is set, it's used as the build date.
/// If `force_deterministic` is set, we fall back to UNIX_EPOCH.
/// Otherwise, we use the current system time.
pub fn build_date_from_env(&mut self, force_deterministic: bool) -> &mut Self {
let build_date_str = std::env::var("SOURCE_DATE_EPOCH").ok();
let build_date = match (force_deterministic, build_date_str) {
(_, Some(s)) => {
let epoch = s
.parse::<u64>()
.expect("invalid SOURCE_DATE_EPOCH (not a number)");
SystemTime::UNIX_EPOCH