/
sandbox.rs
1293 lines (1039 loc) · 36.7 KB
/
sandbox.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
use serde_derive::Deserialize;
use snafu::{ResultExt, Snafu};
use std::{
collections::BTreeMap,
ffi::OsStr,
fmt,
fs::{self, File},
io::{self, prelude::*, BufReader, BufWriter, ErrorKind},
path::{Path, PathBuf},
process::Command,
string,
};
use tempdir::TempDir;
#[derive(Debug, Deserialize)]
struct CrateInformationInner {
name: String,
version: String,
id: String,
}
#[derive(Debug, Clone)]
pub struct CrateInformation {
pub name: String,
pub version: String,
pub id: String,
}
impl From<CrateInformationInner> for CrateInformation {
fn from(me: CrateInformationInner) -> Self {
let CrateInformationInner { name, version, id } = me;
Self { name, version, id }
}
}
#[derive(Debug, Clone)]
pub struct Version {
pub release: String,
pub commit_hash: String,
pub commit_date: String,
}
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Unable to create temporary directory: {}", source))]
UnableToCreateTempDir { source: io::Error },
#[snafu(display("Unable to create source file: {}", source))]
UnableToCreateSourceFile { source: io::Error },
#[snafu(display("Unable to execute the compiler: {}", source))]
UnableToExecuteCompiler { source: io::Error },
#[snafu(display("Unable to read output file: {}", source))]
UnableToReadOutput { source: io::Error },
#[snafu(display("Unable to read crate information: {}", source))]
UnableToParseCrateInformation { source: ::serde_json::Error },
#[snafu(display("Output was not valid UTF-8: {}", source))]
OutputNotUtf8 { source: string::FromUtf8Error },
#[snafu(display("Output was missing"))]
OutputMissing,
#[snafu(display("Release was missing from the version output"))]
VersionReleaseMissing,
#[snafu(display("Commit hash was missing from the version output"))]
VersionHashMissing,
#[snafu(display("Commit date was missing from the version output"))]
VersionDateMissing,
}
pub type Result<T, E = Error> = ::std::result::Result<T, E>;
pub struct Sandbox {
#[allow(dead_code)]
scratch: TempDir,
input_file: PathBuf,
output_dir: PathBuf,
}
fn vec_to_str(v: Vec<u8>) -> Result<String> {
String::from_utf8(v).eager_context(OutputNotUtf8)
}
impl Sandbox {
pub fn new() -> Result<Self> {
let scratch = TempDir::new("playground").context(UnableToCreateTempDir)?;
let input_file = scratch.path().join("input.rs");
let output_dir = scratch.path().join("output");
Ok(Sandbox {
scratch,
input_file,
output_dir,
})
}
pub fn compile(&self, req: &CompileRequest) -> Result<CompileResponse> {
self.write_source_code(&req.code)?;
let mut command = self.compile_command(req.target, req.channel, req.mode, req.tests, req);
let output = command.output().context(UnableToExecuteCompiler)?;
// The compiler writes the file to a name like
// `compilation-3b75174cac3d47fb.ll`, so we just find the
// first with the right extension.
let file =
fs::read_dir(&self.output_dir)
.context(UnableToReadOutput)?
.flat_map(|entry| entry)
.map(|entry| entry.path())
.find(|path| path.extension() == Some(req.target.extension()));
let stdout = vec_to_str(output.stdout)?;
let mut stderr = vec_to_str(output.stderr)?;
let mut code = match file {
Some(file) => read(&file)?.unwrap_or_else(String::new),
None => {
// If we didn't find the file, it's *most* likely that
// the user's code was invalid. Tack on our own error
// to the compiler's error instead of failing the
// request.
use self::fmt::Write;
write!(&mut stderr, "\nUnable to locate file for {} output", req.target)
.expect("Unable to write to a string");
String::new()
}
};
if let CompileTarget::Assembly(_, demangle, process) = req.target {
if demangle == DemangleAssembly::Demangle {
code = super::asm_cleanup::demangle_asm(&code);
}
if process == ProcessAssembly::Filter {
code = super::asm_cleanup::filter_asm(&code);
}
}
Ok(CompileResponse {
success: output.status.success(),
code,
stdout,
stderr,
})
}
pub fn execute(&self, req: &ExecuteRequest) -> Result<ExecuteResponse> {
self.write_source_code(&req.code)?;
let mut command = self.execute_command(req.channel, req.mode, req.tests, req);
let output = command.output().context(UnableToExecuteCompiler)?;
Ok(ExecuteResponse {
success: output.status.success(),
stdout: vec_to_str(output.stdout)?,
stderr: vec_to_str(output.stderr)?,
})
}
pub fn format(&self, req: &FormatRequest) -> Result<FormatResponse> {
self.write_source_code(&req.code)?;
let mut command = self.format_command(req);
let output = command.output().context(UnableToExecuteCompiler)?;
Ok(FormatResponse {
success: output.status.success(),
code: read(self.input_file.as_ref())?.ok_or(Error::OutputMissing)?,
stdout: vec_to_str(output.stdout)?,
stderr: vec_to_str(output.stderr)?,
})
}
pub fn clippy(&self, req: &ClippyRequest) -> Result<ClippyResponse> {
self.write_source_code(&req.code)?;
let mut command = self.clippy_command(req);
let output = command.output().context(UnableToExecuteCompiler)?;
Ok(ClippyResponse {
success: output.status.success(),
stdout: vec_to_str(output.stdout)?,
stderr: vec_to_str(output.stderr)?,
})
}
pub fn miri(&self, req: &MiriRequest) -> Result<MiriResponse> {
self.write_source_code(&req.code)?;
let mut command = self.miri_command(req);
let output = command.output().context(UnableToExecuteCompiler)?;
Ok(MiriResponse {
success: output.status.success(),
stdout: vec_to_str(output.stdout)?,
stderr: vec_to_str(output.stderr)?,
})
}
pub fn crates(&self) -> Result<Vec<CrateInformation>> {
let mut command = basic_secure_docker_command();
command.args(&[Channel::Stable.container_name()]);
command.args(&["cat", "crate-information.json"]);
let output = command.output().context(UnableToExecuteCompiler)?;
let crate_info: Vec<CrateInformationInner> = ::serde_json::from_slice(&output.stdout).context(UnableToParseCrateInformation)?;
let crates = crate_info.into_iter()
.map(Into::into)
.collect();
Ok(crates)
}
pub fn version(&self, channel: Channel) -> Result<Version> {
let mut command = basic_secure_docker_command();
command.args(&[channel.container_name()]);
command.args(&["rustc", "--version", "--verbose"]);
let output = command.output().context(UnableToExecuteCompiler)?;
let version_output = vec_to_str(output.stdout)?;
let mut info: BTreeMap<String, String> = version_output.lines().skip(1).filter_map(|line| {
let mut pieces = line.splitn(2, ':').fuse();
match (pieces.next(), pieces.next()) {
(Some(name), Some(value)) => Some((name.trim().into(), value.trim().into())),
_ => None
}
}).collect();
let release = info.remove("release").ok_or(Error::VersionReleaseMissing)?;
let commit_hash = info.remove("commit-hash").ok_or(Error::VersionHashMissing)?;
let commit_date = info.remove("commit-date").ok_or(Error::VersionDateMissing)?;
Ok(Version { release, commit_hash, commit_date })
}
pub fn version_rustfmt(&self) -> Result<Version> {
let mut command = basic_secure_docker_command();
command.args(&["rustfmt", "cargo", "fmt", "--version"]);
self.cargo_tool_version(command)
}
pub fn version_clippy(&self) -> Result<Version> {
let mut command = basic_secure_docker_command();
command.args(&["clippy", "cargo", "clippy", "--version"]);
self.cargo_tool_version(command)
}
pub fn version_miri(&self) -> Result<Version> {
let mut command = basic_secure_docker_command();
command.args(&["miri", "cargo", "miri", "--version"]);
self.cargo_tool_version(command)
}
// Parses versions of the shape `toolname 0.0.0 (0000000 0000-00-00)`
fn cargo_tool_version(&self, mut command: Command) -> Result<Version> {
let output = command.output().context(UnableToExecuteCompiler)?;
let version_output = vec_to_str(output.stdout)?;
let mut parts = version_output.split_whitespace().fuse().skip(1);
let release = parts.next().unwrap_or("").into();
let commit_hash = parts.next().unwrap_or("").trim_start_matches('(').into();
let commit_date = parts.next().unwrap_or("").trim_end_matches(')').into();
Ok(Version { release, commit_hash, commit_date })
}
fn write_source_code(&self, code: &str) -> Result<()> {
let data = code.as_bytes();
let file = File::create(&self.input_file).context(UnableToCreateSourceFile)?;
let mut file = BufWriter::new(file);
file.write_all(data).context(UnableToCreateSourceFile)?;
log::debug!("Wrote {} bytes of source to {}", data.len(), self.input_file.display());
Ok(())
}
fn compile_command(&self, target: CompileTarget, channel: Channel, mode: Mode, tests: bool, req: impl CrateTypeRequest + EditionRequest + BacktraceRequest) -> Command {
let mut cmd = self.docker_command(Some(req.crate_type()));
set_execution_environment(&mut cmd, Some(target), &req);
let execution_cmd = build_execution_command(Some(target), channel, mode, &req, tests);
cmd.arg(&channel.container_name()).args(&execution_cmd);
log::debug!("Compilation command is {:?}", cmd);
cmd
}
fn execute_command(&self, channel: Channel, mode: Mode, tests: bool, req: impl CrateTypeRequest + EditionRequest + BacktraceRequest) -> Command {
let mut cmd = self.docker_command(Some(req.crate_type()));
set_execution_environment(&mut cmd, None, &req);
let execution_cmd = build_execution_command(None, channel, mode, &req, tests);
cmd.arg(&channel.container_name()).args(&execution_cmd);
log::debug!("Execution command is {:?}", cmd);
cmd
}
fn format_command(&self, req: impl EditionRequest) -> Command {
let crate_type = CrateType::Binary;
let mut cmd = self.docker_command(Some(crate_type));
cmd.apply_edition(req);
cmd.arg("rustfmt").args(&["cargo", "fmt"]);
log::debug!("Formatting command is {:?}", cmd);
cmd
}
fn clippy_command(&self, req: impl CrateTypeRequest + EditionRequest) -> Command {
let mut cmd = self.docker_command(Some(req.crate_type()));
cmd.apply_crate_type(&req);
cmd.apply_edition(&req);
cmd.arg("clippy").args(&["cargo", "clippy"]);
log::debug!("Clippy command is {:?}", cmd);
cmd
}
fn miri_command(&self, req: impl EditionRequest) -> Command {
let mut cmd = self.docker_command(None);
cmd.apply_edition(req);
cmd.arg("miri").args(&["cargo", "miri-playground"]);
log::debug!("Miri command is {:?}", cmd);
cmd
}
fn docker_command(&self, crate_type: Option<CrateType>) -> Command {
let crate_type = crate_type.unwrap_or(CrateType::Binary);
let mut mount_input_file = self.input_file.as_os_str().to_os_string();
mount_input_file.push(":");
mount_input_file.push("/playground/");
mount_input_file.push(crate_type.file_name());
let mut mount_output_dir = self.output_dir.as_os_str().to_os_string();
mount_output_dir.push(":");
mount_output_dir.push("/playground-result");
let mut cmd = basic_secure_docker_command();
cmd
.arg("--volume").arg(&mount_input_file)
.arg("--volume").arg(&mount_output_dir);
cmd
}
}
fn basic_secure_docker_command() -> Command {
let mut cmd = Command::new("docker");
cmd
.arg("run")
.arg("--rm")
.arg("--cap-drop=ALL")
.arg("--cap-add=DAC_OVERRIDE")
.arg("--security-opt=no-new-privileges")
.args(&["--workdir", "/playground"])
.args(&["--net", "none"])
.args(&["--memory", "256m"])
.args(&["--memory-swap", "320m"])
.args(&["--env", "PLAYGROUND_TIMEOUT=10"]);
if cfg!(feature = "fork-bomb-prevention") {
cmd.args(&["--pids-limit", "512"]);
}
cmd
}
fn build_execution_command(target: Option<CompileTarget>, channel: Channel, mode: Mode, req: impl CrateTypeRequest, tests: bool) -> Vec<&'static str> {
use self::CompileTarget::*;
use self::CrateType::*;
use self::Mode::*;
let mut cmd = vec!["cargo"];
match (target, req.crate_type(), tests) {
(Some(Wasm), _, _) => cmd.push("wasm"),
(Some(_), _, _) => cmd.push("rustc"),
(_, _, true) => cmd.push("test"),
(_, Library(_), _) => cmd.push("build"),
(_, _, _) => cmd.push("run"),
}
if mode == Release {
cmd.push("--release");
}
if let Some(target) = target {
cmd.extend(&["--", "-o", "/playground-result/compilation"]);
match target {
Assembly(flavor, _, _) => {
use self::AssemblyFlavor::*;
cmd.push("--emit=asm");
// Enable extra assembly comments for nightly builds
if let Channel::Nightly = channel {
cmd.push("-Z");
cmd.push("asm-comments");
}
cmd.push("-C");
match flavor {
Att => cmd.push("llvm-args=-x86-asm-syntax=att"),
Intel => cmd.push("llvm-args=-x86-asm-syntax=intel"),
}
},
LlvmIr => cmd.push("--emit=llvm-ir"),
Mir => cmd.push("--emit=mir"),
Wasm => { /* handled by cargo-wasm wrapper */ },
}
}
cmd
}
fn set_execution_environment(cmd: &mut Command, target: Option<CompileTarget>, req: impl CrateTypeRequest + EditionRequest + BacktraceRequest) {
use self::CompileTarget::*;
if let Some(Wasm) = target {
cmd.args(&["--env", "PLAYGROUND_NO_DEPENDENCIES=true"]);
cmd.args(&["--env", "PLAYGROUND_RELEASE_LTO=true"]);
}
cmd.apply_crate_type(&req);
cmd.apply_edition(&req);
cmd.apply_backtrace(&req);
}
fn read(path: &Path) -> Result<Option<String>> {
let f = match File::open(path) {
Ok(f) => f,
Err(ref e) if e.kind() == ErrorKind::NotFound => return Ok(None),
e => e.context(UnableToReadOutput)?,
};
let mut f = BufReader::new(f);
let mut s = String::new();
f.read_to_string(&mut s).context(UnableToReadOutput)?;
Ok(Some(s))
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AssemblyFlavor {
Att,
Intel,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DemangleAssembly {
Demangle,
Mangle,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ProcessAssembly {
Filter,
Raw,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CompileTarget {
Assembly(AssemblyFlavor, DemangleAssembly, ProcessAssembly),
LlvmIr,
Mir,
Wasm,
}
impl CompileTarget {
fn extension(&self) -> &'static OsStr {
let ext = match *self {
CompileTarget::Assembly(_, _, _) => "s",
CompileTarget::LlvmIr => "ll",
CompileTarget::Mir => "mir",
CompileTarget::Wasm => "wat",
};
OsStr::new(ext)
}
}
impl fmt::Display for CompileTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::CompileTarget::*;
match *self {
Assembly(_, _, _) => "assembly".fmt(f),
LlvmIr => "LLVM IR".fmt(f),
Mir => "Rust MIR".fmt(f),
Wasm => "WebAssembly".fmt(f),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Channel {
Stable,
Beta,
Nightly,
}
impl Channel {
fn container_name(&self) -> &'static str {
use self::Channel::*;
match *self {
Stable => "rust-stable",
Beta => "rust-beta",
Nightly => "rust-nightly",
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Mode {
Debug,
Release,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Edition {
Rust2015,
Rust2018,
}
impl Edition {
fn cargo_ident(&self) -> &'static str {
use self::Edition::*;
match *self {
Rust2015 => "2015",
Rust2018 => "2018",
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CrateType {
Binary,
Library(LibraryType),
}
impl CrateType {
fn file_name(&self) -> &'static str {
use self::CrateType::*;
match *self {
Binary => "src/main.rs",
Library(_) => "src/lib.rs",
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum LibraryType {
Lib,
Dylib,
Rlib,
Staticlib,
Cdylib,
ProcMacro
}
impl LibraryType {
fn cargo_ident(&self) -> &'static str {
use self::LibraryType::*;
match *self {
Lib => "lib",
Dylib => "dylib",
Rlib => "rlib",
Staticlib => "staticlib",
Cdylib => "cdylib",
ProcMacro => "proc-macro",
}
}
}
trait DockerCommandExt {
fn apply_crate_type(&mut self, req: impl CrateTypeRequest);
fn apply_edition(&mut self, req: impl EditionRequest);
fn apply_backtrace(&mut self, req: impl BacktraceRequest);
}
impl DockerCommandExt for Command {
fn apply_crate_type(&mut self, req: impl CrateTypeRequest) {
if let CrateType::Library(lib) = req.crate_type() {
self.args(&["--env", &format!("PLAYGROUND_CRATE_TYPE={}", lib.cargo_ident())]);
}
}
fn apply_edition(&mut self, req: impl EditionRequest) {
if let Some(edition) = req.edition() {
self.args(&["--env", &format!("PLAYGROUND_EDITION={}", edition.cargo_ident())]);
}
}
fn apply_backtrace(&mut self, req: impl BacktraceRequest) {
if req.backtrace() {
self.args(&["--env", "RUST_BACKTRACE=1"]);
}
}
}
trait CrateTypeRequest {
fn crate_type(&self) -> CrateType;
}
impl<R: CrateTypeRequest> CrateTypeRequest for &'_ R {
fn crate_type(&self) -> CrateType { (*self).crate_type() }
}
trait EditionRequest {
fn edition(&self) -> Option<Edition>;
}
impl<R: EditionRequest> EditionRequest for &'_ R {
fn edition(&self) -> Option<Edition> { (*self).edition() }
}
trait BacktraceRequest {
fn backtrace(&self) -> bool;
}
impl<R: BacktraceRequest> BacktraceRequest for &'_ R {
fn backtrace(&self) -> bool { (*self).backtrace() }
}
#[derive(Debug, Clone)]
pub struct CompileRequest {
pub target: CompileTarget,
pub channel: Channel,
pub crate_type: CrateType,
pub mode: Mode,
pub edition: Option<Edition>,
pub tests: bool,
pub backtrace: bool,
pub code: String,
}
impl CrateTypeRequest for CompileRequest {
fn crate_type(&self) -> CrateType { self.crate_type }
}
impl EditionRequest for CompileRequest {
fn edition(&self) -> Option<Edition> { self.edition }
}
impl BacktraceRequest for CompileRequest {
fn backtrace(&self) -> bool { self.backtrace }
}
#[derive(Debug, Clone)]
pub struct CompileResponse {
pub success: bool,
pub code: String,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone)]
pub struct ExecuteRequest {
pub channel: Channel,
pub mode: Mode,
pub edition: Option<Edition>,
pub crate_type: CrateType,
pub tests: bool,
pub backtrace: bool,
pub code: String,
}
impl CrateTypeRequest for ExecuteRequest {
fn crate_type(&self) -> CrateType { self.crate_type }
}
impl EditionRequest for ExecuteRequest {
fn edition(&self) -> Option<Edition> { self.edition }
}
impl BacktraceRequest for ExecuteRequest {
fn backtrace(&self) -> bool { self.backtrace }
}
#[derive(Debug, Clone)]
pub struct ExecuteResponse {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone)]
pub struct FormatRequest {
pub code: String,
pub edition: Option<Edition>,
}
impl EditionRequest for FormatRequest {
fn edition(&self) -> Option<Edition> { self.edition }
}
#[derive(Debug, Clone)]
pub struct FormatResponse {
pub success: bool,
pub code: String,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone)]
pub struct ClippyRequest {
pub code: String,
pub edition: Option<Edition>,
pub crate_type: CrateType,
}
impl CrateTypeRequest for ClippyRequest {
fn crate_type(&self) -> CrateType { self.crate_type }
}
impl EditionRequest for ClippyRequest {
fn edition(&self) -> Option<Edition> { self.edition }
}
#[derive(Debug, Clone)]
pub struct ClippyResponse {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone)]
pub struct MiriRequest {
pub code: String,
pub edition: Option<Edition>,
}
impl EditionRequest for MiriRequest {
fn edition(&self) -> Option<Edition> { self.edition }
}
#[derive(Debug, Clone)]
pub struct MiriResponse {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
#[cfg(test)]
mod test {
use super::*;
const HELLO_WORLD_CODE: &'static str = r#"
fn main() {
println!("Hello, world!");
}
"#;
impl Default for ExecuteRequest {
fn default() -> Self {
ExecuteRequest {
channel: Channel::Stable,
crate_type: CrateType::Binary,
mode: Mode::Debug,
tests: false,
code: HELLO_WORLD_CODE.to_string(),
edition: None,
backtrace: false,
}
}
}
impl Default for CompileRequest {
fn default() -> Self {
CompileRequest {
target: CompileTarget::LlvmIr,
channel: Channel::Stable,
crate_type: CrateType::Binary,
mode: Mode::Debug,
tests: false,
code: HELLO_WORLD_CODE.to_string(),
edition: None,
backtrace: false,
}
}
}
impl Default for ClippyRequest {
fn default() -> Self {
ClippyRequest {
code: HELLO_WORLD_CODE.to_string(),
crate_type: CrateType::Binary,
edition: None,
}
}
}
#[test]
fn basic_functionality() {
let req = ExecuteRequest::default();
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("Hello, world!"));
}
const COMPILATION_MODE_CODE: &'static str = r#"
#[cfg(debug_assertions)]
fn main() {
println!("Compiling in debug mode");
}
#[cfg(not(debug_assertions))]
fn main() {
println!("Compiling in release mode");
}
"#;
#[test]
fn debug_mode() {
let req = ExecuteRequest {
code: COMPILATION_MODE_CODE.to_string(),
..ExecuteRequest::default()
};
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("debug mode"));
}
#[test]
fn release_mode() {
let req = ExecuteRequest {
mode: Mode::Release,
code: COMPILATION_MODE_CODE.to_string(),
..ExecuteRequest::default()
};
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("release mode"));
}
static VERSION_CODE: &'static str = r#"
use std::process::Command;
fn main() {
let output = Command::new("rustc").arg("--version").output().unwrap();
let output = String::from_utf8(output.stdout).unwrap();
println!("{}", output);
}
"#;
#[test]
fn stable_channel() {
let req = ExecuteRequest {
channel: Channel::Stable,
code: VERSION_CODE.to_string(),
..ExecuteRequest::default()
};
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("rustc"));
assert!(!resp.stdout.contains("beta"));
assert!(!resp.stdout.contains("nightly"));
}
#[test]
fn beta_channel() {
let req = ExecuteRequest {
channel: Channel::Beta,
code: VERSION_CODE.to_string(),
..ExecuteRequest::default()
};
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("rustc"));
assert!(resp.stdout.contains("beta"));
assert!(!resp.stdout.contains("nightly"));
}
#[test]
fn nightly_channel() {
let req = ExecuteRequest {
channel: Channel::Nightly,
code: VERSION_CODE.to_string(),
..ExecuteRequest::default()
};
let sb = Sandbox::new().expect("Unable to create sandbox");
let resp = sb.execute(&req).expect("Unable to execute code");
assert!(resp.stdout.contains("rustc"));
assert!(!resp.stdout.contains("beta"));
assert!(resp.stdout.contains("nightly"));
}
// Code that will only work in Rust 2015
const EDITION_CODE: &str = r#"
fn main() {
let async = true;
}
"#;
const EDITION_ERROR: &str = "found reserved keyword `async`";
#[test]
fn rust_edition_default() -> Result<()> {
let req = ExecuteRequest {
channel: Channel::Nightly,
code: EDITION_CODE.to_string(),
..ExecuteRequest::default()
};
let resp = Sandbox::new()?.execute(&req)?;
assert!(!resp.stderr.contains(EDITION_ERROR));
Ok(())
}
#[test]
fn rust_edition_2015() -> Result<()> {
let req = ExecuteRequest {
channel: Channel::Nightly,
code: EDITION_CODE.to_string(),
edition: Some(Edition::Rust2015),
..ExecuteRequest::default()
};
let resp = Sandbox::new()?.execute(&req)?;
assert!(!resp.stderr.contains(EDITION_ERROR));
Ok(())
}
#[test]
fn rust_edition_2018() -> Result<()> {
let req = ExecuteRequest {
channel: Channel::Nightly,
code: EDITION_CODE.to_string(),
edition: Some(Edition::Rust2018),
..ExecuteRequest::default()
};
let resp = Sandbox::new()?.execute(&req)?;
assert!(resp.stderr.contains(EDITION_ERROR));
Ok(())
}
const BACKTRACE_CODE: &str = r#"
fn trigger_the_problem() {
None::<u8>.unwrap();
}
fn main() {
trigger_the_problem()
}
"#;
const BACKTRACE_NOTE: &str = "Run with `RUST_BACKTRACE=1` environment variable to display a backtrace";
#[test]
fn backtrace_disabled() -> Result<()> {
let req = ExecuteRequest {
code: BACKTRACE_CODE.to_string(),
backtrace: false,
..ExecuteRequest::default()
};
let sb = Sandbox::new()?;
let resp = sb.execute(&req)?;
assert!(resp.stderr.contains(BACKTRACE_NOTE));