Skip to main content

dockerfile_roast/
evaluate.rs

1//! Static evaluation of the image configuration a Dockerfile build produces.
2//!
3//! Works over the instructions `parse_document` produces. FROM, ARG, ENV, LABEL,
4//! EXPOSE, WORKDIR, USER, CMD, ENTRYPOINT and SHELL shape the result; every other
5//! instruction is skipped. A FROM operand equal to an earlier stage's lowercased
6//! name continues from that stage's final configuration and variables, and any
7//! other operand starts a fresh stage, recorded in `base_image` unless it is
8//! `scratch`. An unknown target and a file without stages are the only errors.
9
10use std::collections::hash_map::Entry;
11use std::collections::{HashMap, HashSet};
12use std::fmt;
13use std::iter::Peekable;
14use std::str::Chars;
15
16use crate::parser::{Dockerfile, Instruction, InstructionForm, Word};
17
18/// The `PATH` BuildKit gives a stage built `FROM scratch`.
19const SCRATCH_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct EvalOptions {
23    /// `--build-arg` values; later duplicates win.
24    pub build_args: Vec<(String, String)>,
25    /// Stage name to build; defaults to the last stage.
26    pub target: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ImageConfig {
31    pub env: Vec<(String, String)>,
32    pub workdir: String,
33    pub user: Option<String>,
34    pub cmd: Option<Vec<String>>,
35    pub entrypoint: Option<Vec<String>>,
36    pub shell: Vec<String>,
37    pub labels: Vec<(String, String)>,
38    pub exposed_ports: Vec<String>,
39    /// Expanded external image the stage chain starts from; `None` for `scratch`.
40    pub base_image: Option<String>,
41}
42
43impl Default for ImageConfig {
44    fn default() -> Self {
45        Self {
46            env: Vec::new(),
47            workdir: "/".to_string(),
48            user: None,
49            cmd: None,
50            entrypoint: None,
51            shell: vec!["/bin/sh".to_string(), "-c".to_string()],
52            labels: Vec::new(),
53            exposed_ports: Vec::new(),
54            base_image: None,
55        }
56    }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum EvalError {
61    UnknownTarget(String),
62    NoStages,
63}
64
65impl fmt::Display for EvalError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::UnknownTarget(target) => write!(f, "target stage {target:?} could not be found"),
69            Self::NoStages => write!(f, "Dockerfile contains no FROM instruction"),
70        }
71    }
72}
73
74impl std::error::Error for EvalError {}
75
76/// Variables visible to expansion: valued ARGs and ENVs, latest assignment wins.
77type Vars = HashMap<String, String>;
78
79/// The config being built, with indexes so that an update never scans what
80/// the config already holds.
81struct Image {
82    config: ImageConfig,
83    env_index: HashMap<String, usize>,
84    label_index: HashMap<String, usize>,
85    ports: HashSet<String>,
86    /// Whether `config.workdir` is lexically resolved (an absolute WORKDIR is kept as written).
87    workdir_clean: bool,
88}
89
90impl Image {
91    fn new(config: ImageConfig) -> Self {
92        Self {
93            env_index: index(&config.env),
94            label_index: index(&config.labels),
95            ports: config.exposed_ports.iter().cloned().collect(),
96            workdir_clean: false,
97            config,
98        }
99    }
100}
101
102struct Stage<'a> {
103    from: &'a Instruction,
104    /// `AS` name, lowercased as BuildKit does when the stage is declared.
105    name: Option<String>,
106    body: &'a [Instruction],
107}
108
109struct Context<'a> {
110    escape: char,
111    build_args: HashMap<&'a str, &'a str>,
112}
113
114pub fn evaluate(dockerfile: &Dockerfile, options: &EvalOptions) -> Result<ImageConfig, EvalError> {
115    let instructions = &dockerfile.instructions;
116    let from_indices: Vec<usize> = instructions
117        .iter()
118        .enumerate()
119        .filter(|(_, instruction)| instruction.instruction == "FROM")
120        .map(|(index, _)| index)
121        .collect();
122    let Some(&first_from) = from_indices.first() else {
123        return Err(EvalError::NoStages);
124    };
125
126    let stages: Vec<Stage<'_>> = from_indices
127        .iter()
128        .enumerate()
129        .map(|(position, &start)| {
130            let end = from_indices
131                .get(position + 1)
132                .copied()
133                .unwrap_or(instructions.len());
134            let from = &instructions[start];
135            let words = arguments(from);
136            let name = (words.len() >= 3 && words[1].value.eq_ignore_ascii_case("as"))
137                .then(|| words[2].value.to_ascii_lowercase());
138            Stage {
139                from,
140                name,
141                body: &instructions[start + 1..end],
142            }
143        })
144        .collect();
145
146    let context = Context {
147        escape: dockerfile.escape,
148        build_args: options
149            .build_args
150            .iter()
151            .map(|(name, value)| (name.as_str(), value.as_str()))
152            .collect(),
153    };
154    let mut globals = Vars::new();
155    for instruction in &instructions[..first_from] {
156        if instruction.instruction == "ARG" {
157            context.apply_args(instruction, &mut globals, &Vars::new());
158        }
159    }
160
161    // The first stage of each name: the one a target or FROM operand refers to.
162    let mut first_named: HashMap<&str, usize> = HashMap::new();
163    for (position, stage) in stages.iter().enumerate() {
164        if let Some(name) = &stage.name {
165            first_named.entry(name).or_insert(position);
166        }
167    }
168    let target = match options.target.as_ref().filter(|name| !name.is_empty()) {
169        Some(target) => *first_named
170            .get(target.to_ascii_lowercase().as_str())
171            .ok_or_else(|| EvalError::UnknownTarget(target.clone()))?,
172        None => stages.len() - 1,
173    };
174
175    let mut chain = vec![target];
176    let (config, mut vars) = loop {
177        let current = chain[chain.len() - 1];
178        let base = arguments(stages[current].from)
179            .first()
180            .map(|word| context.expand(&word.raw, &globals))
181            .unwrap_or_default();
182        match first_named.get(base.as_str()) {
183            Some(&parent) if parent < current => chain.push(parent),
184            _ if base == "scratch" => {
185                let config = ImageConfig {
186                    env: vec![("PATH".to_string(), SCRATCH_PATH.to_string())],
187                    ..ImageConfig::default()
188                };
189                break (
190                    config,
191                    Vars::from([("PATH".to_string(), SCRATCH_PATH.to_string())]),
192                );
193            }
194            _ => {
195                let config = ImageConfig {
196                    base_image: Some(base),
197                    ..ImageConfig::default()
198                };
199                break (config, Vars::new());
200            }
201        }
202    };
203    let mut image = Image::new(config);
204    for &index in chain.iter().rev() {
205        context.run_stage(stages[index].body, &mut image, &mut vars, &globals);
206    }
207    Ok(image.config)
208}
209
210impl Context<'_> {
211    fn expand(&self, text: &str, vars: &Vars) -> String {
212        let resolve = |name: &str| vars.get(name).cloned();
213        Expander {
214            chars: text.chars().peekable(),
215            escape: self.escape,
216            lookup: &resolve,
217        }
218        .word(None)
219    }
220
221    /// Applies an ARG line left to right: each name gets the build arg, else its
222    /// expanded default, else (for a bare redeclaration) the value in `fallback`.
223    fn apply_args(&self, instruction: &Instruction, vars: &mut Vars, fallback: &Vars) {
224        for word in arguments(instruction) {
225            let (name, default) = split_assignment(&word.raw);
226            let value = match (self.build_args.get(name), default) {
227                (Some(value), _) => value.to_string(),
228                (None, Some(default)) => self.expand(default, vars),
229                (None, None) => match fallback.get(name) {
230                    Some(value) => value.clone(),
231                    None => continue,
232                },
233            };
234            vars.insert(name.to_string(), value);
235        }
236    }
237
238    /// Expanded ENV/LABEL pairs; every value sees the variables from before the line.
239    fn pairs(&self, instruction: &Instruction, vars: &Vars) -> Vec<(String, String)> {
240        key_value_pairs(instruction)
241            .into_iter()
242            .map(|(key, value)| (self.expand(key, vars), self.expand(value, vars)))
243            .collect()
244    }
245
246    /// Runs one stage's instructions.
247    fn run_stage(&self, body: &[Instruction], image: &mut Image, vars: &mut Vars, globals: &Vars) {
248        let config = &mut image.config;
249        // CMD and ENTRYPOINT are built once, at the end, from the shell in effect at
250        // their line. `cmd` is None while the stage leaves the inherited CMD alone.
251        let inherited_shell = std::mem::take(&mut config.shell);
252        let mut shell: &[String] = &inherited_shell;
253        let mut shell_replaced = false;
254        let mut cmd = None;
255        let mut entrypoint = None;
256        let mut cmd_set = false;
257        for instruction in body {
258            match instruction.instruction.as_str() {
259                "ARG" => self.apply_args(instruction, vars, globals),
260                "ENV" => {
261                    for (key, value) in self.pairs(instruction, vars) {
262                        vars.insert(key.clone(), value.clone());
263                        upsert(&mut config.env, &mut image.env_index, key, value);
264                    }
265                }
266                "LABEL" => {
267                    for (key, value) in self.pairs(instruction, vars) {
268                        upsert(&mut config.labels, &mut image.label_index, key, value);
269                    }
270                }
271                "WORKDIR" => {
272                    let path = self.expand(&instruction.command, vars);
273                    if path.starts_with('/') {
274                        config.workdir = path;
275                        image.workdir_clean = false;
276                    } else {
277                        if !image.workdir_clean {
278                            config.workdir = clean_path(&config.workdir);
279                            image.workdir_clean = true;
280                        }
281                        join_path(&mut config.workdir, &path);
282                    }
283                }
284                "USER" => config.user = Some(self.expand(&instruction.command, vars)),
285                "EXPOSE" => {
286                    for word in arguments(instruction) {
287                        let expanded = self.expand(&word.raw, vars);
288                        for port in expanded.split_whitespace().flat_map(exposed_ports) {
289                            if !image.ports.contains(&port) {
290                                image.ports.insert(port.clone());
291                                config.exposed_ports.push(port);
292                            }
293                        }
294                    }
295                }
296                "SHELL" => {
297                    if let InstructionForm::Json(json) = &instruction.form {
298                        shell = json;
299                        shell_replaced = true;
300                    }
301                }
302                "CMD" => {
303                    cmd = Some(Some((instruction, shell)));
304                    cmd_set = true;
305                }
306                "ENTRYPOINT" => {
307                    entrypoint = Some((instruction, shell));
308                    if !cmd_set {
309                        cmd = Some(None);
310                    }
311                }
312                _ => {}
313            }
314        }
315        if let Some(cmd) = cmd {
316            config.cmd = cmd.map(|(instruction, shell)| command_line(instruction, shell));
317        }
318        if let Some((instruction, shell)) = entrypoint {
319            config.entrypoint = Some(command_line(instruction, shell));
320        }
321        config.shell = if shell_replaced {
322            shell.to_vec()
323        } else {
324            inherited_shell
325        };
326    }
327}
328
329/// Words following any leading `--flag` options.
330fn arguments(instruction: &Instruction) -> &[Word] {
331    &instruction.words[instruction.flags.len().min(instruction.words.len())..]
332}
333
334fn split_assignment(raw: &str) -> (&str, Option<&str>) {
335    match raw.split_once('=') {
336        Some((name, value)) => (name, Some(value)),
337        None => (raw, None),
338    }
339}
340
341/// Raw `key=value` pairs of ENV/LABEL, or the legacy `KEY value with spaces`
342/// form whose value is the rest of the line.
343fn key_value_pairs(instruction: &Instruction) -> Vec<(&str, &str)> {
344    let words = arguments(instruction);
345    if words.first().is_some_and(|word| !word.raw.contains('=')) {
346        return instruction
347            .command
348            .split_once(char::is_whitespace)
349            .map(|(key, value)| vec![(key, value.trim_start())])
350            .unwrap_or_default();
351    }
352    words
353        .iter()
354        .filter_map(|word| word.raw.split_once('='))
355        .collect()
356}
357
358/// One EXPOSE operand as `port/protocol` entries: the protocol defaults to
359/// `tcp` and is lowercased, and a `lo-hi` range yields one entry per port.
360fn exposed_ports(spec: &str) -> Vec<String> {
361    if spec.is_empty() {
362        return Vec::new();
363    }
364    let (ports, protocol) = match spec.split_once('/') {
365        Some((ports, protocol)) if !protocol.is_empty() => (ports, protocol.to_ascii_lowercase()),
366        Some((ports, _)) => (ports, "tcp".to_string()),
367        None => (spec, "tcp".to_string()),
368    };
369    let range = ports
370        .split_once('-')
371        .and_then(|(low, high)| Some((low.parse::<u16>().ok()?, high.parse::<u16>().ok()?)));
372    match range {
373        Some((low, high)) => (low..=high)
374            .map(|port| format!("{port}/{protocol}"))
375            .collect(),
376        None => match ports.parse::<u16>() {
377            Ok(port) => vec![format!("{port}/{protocol}")],
378            Err(_) => vec![format!("{ports}/{protocol}")],
379        },
380    }
381}
382
383fn command_line(instruction: &Instruction, shell: &[String]) -> Vec<String> {
384    match &instruction.form {
385        InstructionForm::Json(arguments) => arguments.clone(),
386        _ => {
387            let mut line = shell.to_vec();
388            line.push(instruction.logical_arguments.trim().to_string());
389            line
390        }
391    }
392}
393
394/// Position of each key in an ordered list of pairs.
395fn index(entries: &[(String, String)]) -> HashMap<String, usize> {
396    entries
397        .iter()
398        .enumerate()
399        .map(|(position, (key, _))| (key.clone(), position))
400        .collect()
401}
402
403/// Sets `key` in an ordered list of pairs: a new key is appended, an existing
404/// one keeps its position.
405fn upsert(
406    entries: &mut Vec<(String, String)>,
407    index: &mut HashMap<String, usize>,
408    key: String,
409    value: String,
410) {
411    match index.entry(key) {
412        Entry::Occupied(slot) => entries[*slot.get()].1 = value,
413        Entry::Vacant(slot) => {
414            entries.push((slot.key().clone(), value));
415            slot.insert(entries.len() - 1);
416        }
417    }
418}
419
420/// Lexically resolves `.`, `..` and repeated or trailing `/` in an absolute path.
421fn clean_path(path: &str) -> String {
422    let mut parts = Vec::new();
423    for part in path.split('/') {
424        match part {
425            "" | "." => {}
426            ".." => {
427                parts.pop();
428            }
429            part => parts.push(part),
430        }
431    }
432    format!("/{}", parts.join("/"))
433}
434
435/// Joins a relative path onto a resolved absolute one, resolving `.`, `..` and
436/// repeated or trailing `/` of the relative part as it goes.
437fn join_path(workdir: &mut String, relative: &str) {
438    for part in relative.split('/') {
439        match part {
440            "" | "." => {}
441            ".." => workdir.truncate(workdir.rfind('/').unwrap_or(0).max(1)),
442            part => {
443                if workdir.len() > 1 {
444                    workdir.push('/');
445                }
446                workdir.push_str(part);
447            }
448        }
449    }
450}
451
452/// Word expansion after BuildKit's: quote removal, escapes and the `$V`,
453/// `${V}`, `${V:-w}`, `${V-w}`, `${V:+w}` and `${V+w}` forms. Other modifiers
454/// (`${V#w}`, `${V%w}`, `${V/a/b}`, `${V:?w}`, ...) give the plain value.
455struct Expander<'a, F> {
456    chars: Peekable<Chars<'a>>,
457    escape: char,
458    lookup: &'a F,
459}
460
461impl<F: Fn(&str) -> Option<String>> Expander<'_, F> {
462    fn word(&mut self, stop: Option<char>) -> String {
463        let mut result = String::new();
464        while let Some(character) = self.chars.next() {
465            match character {
466                _ if Some(character) == stop => break,
467                '\'' => result.extend(self.chars.by_ref().take_while(|&c| c != '\'')),
468                '"' => self.double_quoted(&mut result),
469                '$' => result.push_str(&self.variable()),
470                _ if character == self.escape => result.extend(self.chars.next()),
471                _ => result.push(character),
472            }
473        }
474        result
475    }
476
477    fn double_quoted(&mut self, result: &mut String) {
478        while let Some(character) = self.chars.next() {
479            match character {
480                '"' => return,
481                '$' => result.push_str(&self.variable()),
482                _ if character == self.escape => match self.chars.peek() {
483                    Some(&next) if next == '"' || next == '$' || next == self.escape => {
484                        result.push(next);
485                        self.chars.next();
486                    }
487                    Some(_) => result.push(character),
488                    None => {}
489                },
490                _ => result.push(character),
491            }
492        }
493    }
494
495    fn variable(&mut self) -> String {
496        let braced = self.chars.next_if_eq(&'{').is_some();
497        if !braced {
498            // BuildKit: `$1x` names `1`; special parameters (`$$`, `$@`, ...) are one character.
499            if let Some(first) = self.chars.next_if(|c| "@*#?-$!".contains(*c)) {
500                return (self.lookup)(&first.to_string()).unwrap_or_default();
501            }
502            if self.chars.peek().is_some_and(char::is_ascii_digit) {
503                let mut digits = String::new();
504                while let Some(digit) = self.chars.next_if(char::is_ascii_digit) {
505                    digits.push(digit);
506                }
507                return (self.lookup)(&digits).unwrap_or_default();
508            }
509        }
510        let mut name = String::new();
511        while let Some(character) = self
512            .chars
513            .next_if(|c| c.is_ascii_alphanumeric() || *c == '_')
514        {
515            name.push(character);
516        }
517        if !braced {
518            if name.is_empty() {
519                return "$".to_string();
520            }
521            return (self.lookup)(&name).unwrap_or_default();
522        }
523
524        let value = (self.lookup)(&name);
525        let colon = self.chars.next_if_eq(&':').is_some();
526        let set = value
527            .as_deref()
528            .is_some_and(|value| !colon || !value.is_empty());
529        match self.chars.next() {
530            Some('-') => {
531                let word = self.word(Some('}'));
532                if set {
533                    value.unwrap_or_default()
534                } else {
535                    word
536                }
537            }
538            Some('+') => {
539                let word = self.word(Some('}'));
540                if set {
541                    word
542                } else {
543                    String::new()
544                }
545            }
546            Some('}') | None => value.unwrap_or_default(),
547            Some(_) => {
548                self.word(Some('}'));
549                value.unwrap_or_default()
550            }
551        }
552    }
553}