(*----------------------------------------------------------------- Copyright (c) 2025 The merry programmers. All rights reserved. SPDX-License-Identifier: ISC -----------------------------------------------------------------*) open Eio.Std open Import open Exit.Syntax let mk_new_id = let i = ref 0 in fun () -> incr i; "id" ^ string_of_int @@ !i let mk_pipeline_scope () = "pipeline-" ^ mk_new_id () let pp_args = Fmt.(list ~sep:(Fmt.any " ") string) let read_env_var param = match Astring.String.cut ~sep:"=" param with | Some (param, v) -> Some (param, [ Ast.Fragment.make v ]) | _ -> None let has_ws txt = String.contains txt ' ' || String.contains txt '\t' || String.contains txt '\n' let unescape_eval txt = let s_len = String.length txt in let buf = Buffer.create s_len in let i = ref 0 in let is_backslash s i = match String.get ~label:"backslash" s i with | '\\' -> true | (exception _) | _ -> false in while !i < s_len do if is_backslash txt !i && is_backslash txt (!i + 1) then begin incr i; incr i end else if is_backslash txt !i then begin incr i end else begin Buffer.add_char buf (String.get ~label:"unescape_eval" txt !i); incr i end done; Buffer.contents buf let pp_fs_create ppf (v : Eio.Fs.create) = match v with | `If_missing o -> Fmt.pf ppf "if-missing %o" o | `Exclusive o -> Fmt.pf ppf "exclusive %o" o | `Or_truncate o -> Fmt.pf ppf "or-truncate %o" o | `Never -> Fmt.pf ppf "never" (** An evaluator over the AST *) module Make (S : Types.State) (Fd : Types.Fd) (E : Types.Exec with type fd = Fd.t) = struct (* What follows uses the POSIX definition of what a shell does ($ 2.1). It starts from point (4), completing a series of expansions on the AST, then redirection is setup, and finally functions/built-ins/commands are executed. *) let pp_redirect = Types.pp_redirect ~pp:Fd.pp let make_child_rdrs_for_parent : Fd.t Types.redirect list -> Fd.t Types.redirect list = List.map (function | Types.Redirect (false, a, b) -> Types.Redirect (true, a, b) | v -> v) module J = Job.Make (E) module Arithmetic = Arith.Make (S) module Context = Ctx.Make (Fd) (S) module Store = Store.Make (Context) module Irmin_store = Irmin_git_unix.FS.KV (Context) open Context type ctx = Context.ctx (* Non-changing, non-serialisable state that is used for running the evaluation. *) type environ = { env : Types.env; executor : E.t; async_switch : Eio.Switch.t; signal_handler : signal_handler; built_ins : (string list * (string list -> t -> t Exit.t)) option; internal_exit_handler : (ctx Exit.t -> unit) option; store : Store.t; } and signal_handler = { run_queue : (t -> t Exit.t) Queue.t; sigint_set : bool; } and config = { merge : bool; tracing : bool } and t = { environ : environ; ctx : ctx; background_jobs : t J.t list; config : config; } let switch_store t s = let ctx = Store.latest (Store.get_store_opt s) in { t with ctx; environ = { t.environ with store = s } } let with_ctx t (v, ctx) = (v, { t with ctx }) let ctx t = t.ctx let fd_opt = Fd.from_resource let env ctx = ctx.environ.env let trace t = t.ctx.trace let current_session t = Store.which_branch t.environ.store t.environ.env let is_committing t = t.ctx.commit let add_trace_entry t e = { t with ctx = { t.ctx with trace = e :: t.ctx.trace } } let add_trace_entry_opt t e = match e with None -> t | Some e -> add_trace_entry t e let should_exit ?(with_errexit = true) (v : t Exit.t) = match v with | Exit.Zero _ -> false | Exit.Nonzero { value = { ctx; _ }; should_exit = { interactive; non_interactive }; _; } -> (ctx.interactive && interactive = `Yes) || (not ctx.interactive) && non_interactive = `Yes && (if with_errexit then ctx.options.errexit else true) && not ctx.subshell let lookup_and_join ?(sep = "") state ~param = match S.lookup state ~param with | None, e -> (None, e) | Some lst, e -> (Some (Ast.Fragment.join_list ~sep lst), e) let update_variable ~splittable ~join v = List.map (fun f -> Ast.{ f with splittable; join }) v let local_state_as_env ctx = Stack.to_list ctx.local_state |> List.concat (* One day, the logic needs to be here... *) let await_job_ready j = ignore j (* J.get_reaper j |> fst |> Eio.Promise.await *) let lookup ~param ctx = let v, e = S.lookup ctx.state ~param in match List.assoc_opt ~compare:String.compare param (local_state_as_env ctx) with | Some _ as v -> (v, e) | None -> (v, e) let get_optind ctx = match lookup ~param:"OPTIND" ctx with | None, _ -> assert false | Some [ { txt; _ } ], e -> (int_of_string txt, e) | Some _, _ -> assert false let set_optind ctx v = let new_state, e = S.update ctx.state ~param:"OPTIND" [ Ast.Fragment.make (string_of_int v) ] in { ctx with state = Result.get_ok new_state; trace = e :: ctx.trace } let in_double_quotes t = t.ctx.quotes = `Double let in_quotes t = t.ctx.quotes = `Single || t.ctx.quotes = `Double exception Continue of int * t (* Used for the [continue] non-POSIX keyword *) exception Break of int * t (* Used for the [break] non-POSIX keyword *) exception Return of t Exit.t (* Used for the [return] non-POSIX keyword *) let init ~directory config fs proc = let f _ = () (* List.iter (fun { History.pre = { History.args; _ }; _ } -> *) (* LNoise.history_add (String.concat " " args) |> ignore) *) in let store = if config.merge then ( let with_latest_iter = Store.with_latest ~default:(fun () -> ()) in let zfs = Zfs_store.init fs proc "msh" in let conf = Irmin_git.config (Eio.Path.native_exn directory) in let repo = Irmin_store.Repo.v conf in let store = Irmin_store.main repo in let s = Store.(Store ((module Irmin_store), store)) in let full_store = Store.v s zfs in with_latest_iter (Some s) f; Some full_store) else None in store let default_config = { merge = false; tracing = false } let make_config ?(merge = default_config.merge) ?(tracing = default_config.tracing) () = { merge; tracing } let make_ctx ?(config = default_config) ?(build = Zfs_store.Build.Image "alpine") ?(overlays = []) ?(interactive = false) ?(toplevel = true) ?(subshell = false) ?(background_jobs = []) ?(last_background_process = "") ?current_pipeline ?last_pipeline_status ?(functions = []) ?exit_handler ?(options = Options.default) ?(hash = Hash.empty) ?(umask = 0o22) ?built_ins ~async_switch ~program ~argv ~store_dir state executor fd_table env = let signal_handler = { run_queue = Queue.create (); sigint_set = false } in let state = let s1, _e = S.update state ~param:"IFS" [ Ast.Fragment.make " \t\n" ] in let s1 = Result.get_ok' s1 in let s2, _e = S.update s1 ~param:"OPTIND" [ Ast.Fragment.make "1" ] in let s2 = s2 |> Result.get_ok in s2 in let store = init ~directory:store_dir config env#fs env#process_mgr in let environ : environ = { env :> Types.env; signal_handler; executor; async_switch; built_ins; internal_exit_handler = None; store; } in let ctx = { interactive; toplevel; trace = Trace.empty; subshell; fd_table; state; exit_handler; local_state = Stack.empty; options; last_background_process; last_pipeline_status; program; argv; functions; hash; rdrs = [ Types.Redirect (false, 0, Fd.stdin); Types.Redirect (false, 1, Fd.stdout); ]; quotes = `None; umask; current_pipeline; current_context = `Toplevel; diff = []; commit = true; mode = Void.RW; build; overlays; command = []; } in let default () = { environ; ctx; background_jobs; config } in if config.merge then Store.with_latest ~default (Store.get_store_opt store) (fun ctxs -> let ctx = List.hd ctxs in { environ; ctx; background_jobs; config }) else default () let state t = t.ctx.state let stdout ctx = ctx.environ.env#stdout let stdin ctx = ctx.environ.env#stdin let sigint_set ctx = ctx.environ.signal_handler.sigint_set let fs ctx = ctx.environ.env#fs let pop_local_state t = match Stack.pop t.ctx.local_state with | None -> t | Some (_, local_state) -> { t with ctx = { t.ctx with local_state } } let with_pipeline_scope ?(force = false) ?(remove_vars = true) ({ ctx; environ; background_jobs; config } : t) fn : t Exit.t = let saved_pipeline = ctx.current_pipeline in let current_pipeline = if force then mk_pipeline_scope () else Option.value ~default:(mk_pipeline_scope ()) ctx.current_pipeline in let changed = force || Option.is_none ctx.current_pipeline in let v = fn { ctx = { ctx with current_pipeline = Some current_pipeline }; environ; background_jobs; config; } in Exit.map ~f:(fun t -> { t with ctx = { t.ctx with current_pipeline = saved_pipeline; state = (if changed && remove_vars then S.remove_group ~id:current_pipeline t.ctx.state else t.ctx.state); }; }) v let tilde_expansion t = function | Ast.WordTildePrefix _ -> Ast.WordTildePrefix (S.expand t.ctx.state `Tilde) | v -> v let arithmetic_expansion ~expand t expr = let es, state, i = Arithmetic.eval ~expand t.ctx.state expr in ({ t with ctx = { t.ctx with state; trace = es @ t.ctx.trace } }, i) (* The minimal amount of context needed between pipeline stages. *) type pipeline_ctx = { stdin : int * Fd.t } let find_first_rdr kind rdrs = match List.find_map (function | Types.Redirect (_, j, fd) when Int.equal j 0 && kind = `Stdin -> Some (j, fd) | Types.Redirect (_, j, fd) when Int.equal j 1 && kind = `Stdout -> Some (j, fd) | _ -> None) rdrs with | Some p -> p | None -> ( match kind with `Stdin -> (0, Fd.stdin) | `Stdout -> (1, Fd.stdout)) let get_std_with_locality = function | `Local p -> (p, false) | `Global p -> (p, true) (* [std_for_pipeline] returns three things: 1. The stdin for the current command of the pipeline. 2. The stdout for the current command of the pipeline. 3. The stdin for the next part of the pipeline. *) let std_for_pipeline ?(first = false) ~sw rdrs (pctx : pipeline_ctx) ({ environ; _ } : t) rest = match (first, rest) with | true, [] -> let stdin_for_current_command = `Global (find_first_rdr `Stdin rdrs) in let stdout_for_current_command = `Global (find_first_rdr `Stdout rdrs) in (* There is no next command, so we can return whatever we like here. *) let stdin_for_next_command = stdin_for_current_command in ( stdin_for_current_command, stdout_for_current_command, stdin_for_next_command ) | false, [] -> let stdin_for_current_command = `Local pctx.stdin in let stdout_for_current_command = `Global (find_first_rdr `Stdout rdrs) in (* There is no next command, so we can return whatever we like here. *) let stdin_for_next_command = stdin_for_current_command in ( stdin_for_current_command, stdout_for_current_command, stdin_for_next_command ) | first, _ :: _ -> let r, w = E.pipe ~sw environ.executor in let stdin_for_current_command = if first then `Global pctx.stdin else `Local pctx.stdin in let stdout_for_current_command = `Local (1, w) in let stdin_for_next_command = `Local (0, r) in ( stdin_for_current_command, stdout_for_current_command, stdin_for_next_command ) let file_creation_mode ctx = 0o666 - ctx.umask let cwd_of_ctx t = S.cwd t.ctx.state |> Fpath.to_string |> ( / ) (fs t) let immediate_built_in v = `Built_in (Promise.create_resolved @@ Ok v) let arg_equals_fast a b = let s1 = String.length a in let s2 = String.length b in let bs = Bytes.create (s1 + 1 + s2) in Bytes.unsafe_blit_string a 0 bs 0 s1; Bytes.unsafe_blit_string "=" 0 bs s1 1; Bytes.unsafe_blit_string b 0 bs (s1 + 1) s2; Bytes.unsafe_to_string bs let get_env ?(extra : (string * Ast.fragments) list Stack.t = Stack.empty) ctx = (* TODO: This is a bit rickety, needs some thought as to the ordering of variables and the scoping.*) let extra = Stack.to_list extra in let env = S.exports ctx.state |> List.map (fun (k, v) -> arg_equals_fast k v) in let extra = List.map (fun (k, v) -> arg_equals_fast k @@ Ast.Fragment.join_list ~sep:"" v) (List.concat extra) in List.append env extra |> Array.of_list let update ?export ?readonly ?local t ~param v = match S.update ?export ?readonly ?local t.ctx.state ~param v with | Ok state, e -> Exit.zero { t with ctx = { t.ctx with state; trace = e :: t.ctx.trace } } | Error msg, e -> Fmt.epr "%s\n%!" msg; Exit.nonzero { t with ctx = { t.ctx with trace = e :: t.ctx.trace } } 1 let remove_quotes s = let s_len = String.length s in if s_len < 2 then s else let s = if String.get ~label:"remove-quotes" s 0 = '"' then String.sub s 1 (s_len - 1) else s in let s_len = String.length s in if String.get ~label:"remove-quotes" s (s_len - 1) = '"' then String.sub s 0 (s_len - 1) else s let catch_execs_with_error fn = try fn () with Eio.Io (err, _) -> Fmt.epr "%a\n%!" Eio.Exn.pp_err err; Error 2 let catch_execs_with_exit ctx fn = try fn () with Eio.Io (err, _) -> Fmt.epr "%a\n%!" Eio.Exn.pp_err err; Exit.nonzero ~message:(Fmt.str "%a" Eio.Exn.pp_err err) ctx 2 let set_last_background ~async process t = if async then begin { t with ctx = { t.ctx with last_background_process = string_of_int (E.pid process) }; } end else t let on_process ?process ~async t = let ctx = pop_local_state t in match process with | None -> ctx | Some process -> set_last_background ~async process ctx let handle_job j = function | `Process (c, p) -> J.add_process c p j | `Rdr p -> J.add_rdr p j | `Built_in p -> J.add_built_in p j | `Noop b -> J.add_noop b j | `Error p -> J.add_error p j | `Exit p -> J.add_exit p j let update_stdin ~stdin _ = { stdin } let exec_process ~async ~sw ({ ctx; environ; _ } as t : t) (job : t J.t) ?(fds : Fd.t Types.redirect list = []) ?pgid executable args = let fds = Eunix.keep_first fds in let pgid = match pgid with None -> 0 | Some p -> p in let reap = J.get_reaper job in let mode = if async then Types.Switched environ.async_switch else Types.Switched sw in (* Before we execute the first program, we need to set the default sigint behaviour...*) let job = match J.get_sigint job with | None -> let old_behaviour = Sys.signal Sys.sigint Sys.Signal_default in J.set_sigint old_behaviour job | Some _ -> job in let job = match J.get_sigint job with | None -> let old_behaviour = Sys.signal Sys.sigint Sys.Signal_default in J.set_sigint old_behaviour job | Some _ -> job in let t, process = let hash, prog = Eunix.resolve_program ~path:(S.path ctx.state) ~file_exists:(fun path -> Eio.Path.is_file Eio.Path.(t.environ.env#fs / path)) ctx.hash executable in let t = { t with ctx = { ctx with hash } } in match (executable, prog) with | _, None | "", _ -> Eunix.with_redirections ~sw (module Fd) (make_child_rdrs_for_parent fds) ~restore:true @@ fun () -> Eio.Flow.copy_string (Fmt.str "msh: command not found: %s\n" executable) (stdout t); (t, Error 127) | _, Some full_path -> Debug.Log.debug (fun f -> f "executing %a (rdr: %a)" Fmt.(list ~sep:(Fmt.any " ") (quote string)) (full_path :: args) Fmt.(lst pp_redirect) fds); ( t, catch_execs_with_error @@ fun () -> E.exec environ.executor ~delay_reap:(fst reap) ~fds ~pgid ~mode ~cwd:(cwd_of_ctx t) ~env:(get_env ~extra:ctx.local_state ctx) ~executable:full_path (executable :: args) ) in match process with | Error n -> let job = handle_job job (`Error n) in (on_process ~async t, job) | Ok process -> let pgid = if Int.equal pgid 0 then E.pid process else pgid in let ctx = on_process ~async ~process t in let job = handle_job job (`Process (t, process)) |> J.set_id pgid in (ctx, job) (* The main evaluation knot, bundles, mess :-) *) let rec handle_pipeline ~async (initial_ctx : t) p : t Exit.t = (* Push a new local state frame. *) let initial_ctx = { initial_ctx with ctx = { initial_ctx.ctx with local_state = Stack.push [] initial_ctx.ctx.local_state; }; } in ignore initial_ctx.ctx.fd_table; let should_exit ?with_errexit ctx = should_exit ?with_errexit ctx && List.length p = 1 in let close_flow ~is_global (_, fd) = if not is_global then begin Debug.Log.info (fun f -> f "closing %a is_global:%b" Fd.pp fd is_global); Fd.close fd end in let job_pgid (t : _ J.t) = J.get_id t in with_pipeline_scope initial_ctx @@ fun initial_ctx -> let rec loop pipeline_switch (pctx : pipeline_ctx) (job : _ J.t) : Ast.command list -> _ J.t = fun c -> let loop = loop pipeline_switch in match c with | [] -> job | Ast.SimpleCommand (Prefixed (prefix, None, _suffix)) :: rest -> Debug.Log.debug (fun f -> f "assignment-only: %a" Ast_pp.cmd_prefix prefix); let ctx = collect_assignments initial_ctx prefix in let job = handle_job job (`Noop ctx) in loop pctx job rest | [ Ast.SimpleCommand (Ast.Named ([ Ast.WordName ":" ], None)) ] -> job | Ast.SimpleCommand v :: rest as pipeline -> ( let executable, suffix = match v with | Prefixed (_, Some exec, suffix) -> (* TODO: Exit.value *) (exec, suffix) | Named (exec, suffix) -> (exec, suffix) | _ -> assert false in (* Expand without the local state *) let ctx, executable = word_expansion initial_ctx executable in match ctx with | Exit.Nonzero _ as ctx -> let job = handle_job job (`Noop ctx) in loop pctx job rest | Exit.Zero ctx -> ( let executable, extra_args = (* This is a side-effect of the alias command with something like alias ls="ls -la" *) match Ast.Fragment.join_list ~sep:"" (List.concat executable) |> String.split_on_char ' ' |> List.map Ast.Fragment.make with | [] -> ("", []) | exec :: args -> ( remove_quotes exec.txt, List.map (fun v -> Ast.Suffix_word [ Ast.WordLiteral (remove_quotes v.Ast.txt) ]) args ) in let ctx, suffix = match suffix with | None -> (ctx, []) | Some suffix -> expand_redirects (ctx, []) suffix in let ctx, args = args ctx (extra_args @ suffix) in (* Update the local state -- this is sensitive to all of the current pipeline's word expansions that need to take place. *) let ctx = match v with | Prefixed (prefix, _, _) -> ( match ctx with | Exit.Zero ctx -> collect_assignments ~update:false ctx prefix | _ -> ctx) | _ -> ctx in match ctx with | Exit.Nonzero _ as ctx -> let job = handle_job job (`Noop ctx) in loop pctx job rest | Exit.Zero t -> ( let rdrs = List.fold_left (fun acc -> function | Ast.Suffix_word _ -> acc | Ast.Suffix_redirect rdr -> rdr :: acc) [] suffix |> List.rev in match handle_redirections ~sw: (if String.equal executable "exec" then t.environ.async_switch else pipeline_switch) t rdrs with | Error ctx -> handle_job job (`Rdr (Exit.nonzero ctx 1)) | Ok (t, rdrs) -> ( let first = List.length p = List.length pipeline in let std = std_for_pipeline ~first ~sw:pipeline_switch (rdrs @ t.ctx.rdrs) pctx t rest in let ( (some_read, is_stdin_global), (some_write, is_stdout_global), (next_read, _) ) = match std with | current_stdin, current_stdout, next_stdin -> ( get_std_with_locality current_stdin, get_std_with_locality current_stdout, get_std_with_locality next_stdin ) in match Built_ins.of_args ?user_built_ins:(Option.map fst t.environ.built_ins) (executable :: args) with | Some (Error _) -> handle_job job (immediate_built_in (Exit.nonzero t 1)) | (None | Some (Ok (Command _))) as v -> ( let is_command, command_args, print_command = match v with | Some (Ok (Command { print_command; args })) -> (true, args, print_command) | _ -> (false, [], false) in (* We handle the [export] built_in explicitly as we need access to the raw CST *) match executable with | "export" -> let updated = handle_assignments `Export t args in let job = handle_job job (immediate_built_in updated) in Debug.Log.debug (fun f -> f "export %a" pp_args args); loop pctx job rest | "readonly" -> let updated = handle_assignments `Readonly t args in let job = handle_job job (immediate_built_in updated) in Debug.Log.debug (fun f -> f "readonly %a" pp_args args); loop pctx job rest | "local" -> let updated = handle_assignments `Local t args in let job = handle_job job (immediate_built_in updated) in loop pctx job rest | "exec" -> (* Redirect stdin and stdout *) let t, prog = match args with | [] -> (t, None) | name :: _ -> ( let hash, prog = Eunix.resolve_program ~update:false ~path:(S.path t.ctx.state) t.ctx.hash name in let ctx = { t with ctx = { t.ctx with hash } } in match prog with | None -> Fmt.failwith "%s not found" name | Some p -> (ctx, Some p)) in let rdrs = rdrs @ [ Types.redirect some_write; Types.redirect some_read; ] in let fds = rdrs @ t.ctx.rdrs in if t.ctx.subshell && args <> [] then let _ctx, job = exec_process ~async ~sw:pipeline_switch t job ~fds ~pgid:(job_pgid job) (Option.get prog) (List.tl args) in job else let rdrs = make_child_rdrs_for_parent rdrs in Debug.Log.debug (fun f -> f "exec [%a] [%a]" pp_args args Fmt.(list pp_redirect) rdrs); Eunix.with_redirections (module Fd) ~sw:initial_ctx.environ.async_switch ~restore:false rdrs Fun.id; let fd_table = List.fold_left (fun tb -> function | Types.Redirect (true, fd, efd) -> Fd_table.add_fd ~src:fd ~tgt:(Fd.to_int efd) tb | Types.Redirect (false, _, _) -> tb | Types.Close efd -> Fd_table.remove (Fd.to_int efd) tb) t.ctx.fd_table rdrs in if args <> [] then begin Option.iter (fun f -> f (Exit.map ~f:(fun t -> t.ctx) ctx)) (Exit.value ctx).environ .internal_exit_handler; Unix.execve (Option.get prog) (Array.of_list args) (get_env ~extra:t.ctx.local_state t.ctx) end else handle_job job (`Rdr (Exit.zero { t with ctx = { t.ctx with fd_table }; })) | ":" -> job | _ -> ( let saved_ctx = t in let func_app = if is_command then Either.left t else let rdrs = Types.redirect some_write :: rdrs in let rdrs = Types.redirect some_read :: rdrs in let t = { t with ctx = { t.ctx with rdrs; subshell = List.length p > 1; }; } in handle_function_application t ~name:executable (t.ctx.program :: args) in match func_app with | Either.Right ctx_fn -> let ctx = Eio.Fiber.fork_promise ~sw:pipeline_switch (fun () -> Debug.Log.debug (fun f -> f "With rdrs: %a" Fmt.(lst pp_redirect) rdrs); let t = ctx_fn () in Exit.map ~f:(fun t -> { saved_ctx with ctx = { saved_ctx.ctx with state = t.ctx.state; functions = t.ctx.functions; trace = t.ctx.trace; }; }) t) in Eio.Fiber.fork ~sw:pipeline_switch (fun () -> let _ = Eio.Promise.await_exn ctx in close_flow ~is_global:is_stdout_global some_write); let job = handle_job job (`Built_in ctx) in let pctx = update_stdin ~stdin:next_read pctx in loop pctx job rest | Either.Left t -> ( match Built_ins.of_args ?user_built_ins: (Option.map fst t.environ.built_ins) command_args with | Some (Error _) -> handle_job job (immediate_built_in (Exit.nonzero t 1)) | Some (Ok bi) -> let rdrs = rdrs @ [ Types.redirect some_write; Types.redirect some_read; ] in let t = Fiber.fork_promise ~sw:pipeline_switch @@ fun () -> Log.name "built-in"; let bi : t Exit.t = catch_execs_with_exit t @@ fun () -> let blt : t Exit.t = handle_built_in ~sw:t.environ.async_switch ~rdrs t bi in await_job_ready job; close_flow ~is_global:is_stdout_global some_write; blt in bi in let job = match bi with | Built_ins.Exit _ -> let t = Promise.await_exn t in if should_exit ~with_errexit:false t then exit_from_eval t else handle_job job (`Exit t) | _ -> handle_job job (`Built_in t) in let pctx = update_stdin ~stdin:next_read pctx in loop pctx job rest | _ -> ( let ctx, exec_and_args = if is_command then begin match command_args with | [] -> assert false | x :: xs -> ( let hash, prog = Eunix.resolve_program ~update:false ~path:(S.path t.ctx.state) t.ctx.hash x in let t = { t with ctx = { t.ctx with hash }; } in match prog with | None -> (t, Exit.nonzero ("", []) 1) | Some prog -> if print_command then ( t, Exit.zero ("echo", [ prog ]) ) else (t, Exit.zero (x, xs))) end else (t, Exit.zero (executable, args)) in match exec_and_args with | Exit.Nonzero _ as v -> let pctx = update_stdin ~stdin:next_read pctx in let job = handle_job job (`Noop (Exit.map ~f:(fun _ -> initial_ctx) v)) in loop pctx job rest | Exit.Zero (executable, args) -> (* Redirect stdin and stdout *) let rdrs = rdrs @ [ Types.redirect some_write; Types.redirect some_read; ] in let fds = rdrs @ t.ctx.rdrs in let _ctx, job = exec_process ~async ~sw:pipeline_switch ctx job ~fds ~pgid:(job_pgid job) executable args in Eio.Fiber.fork ~sw: (if async then ctx.environ.async_switch else pipeline_switch) (fun () -> match Promise.await (fst @@ J.get_reaper job) with | () -> (* TODO: Wrong! For failing processes? *) close_flow ~is_global:is_stdout_global some_write; close_flow ~is_global:is_stdin_global some_read); let pctx = update_stdin ~stdin:next_read pctx in loop pctx job rest)))) | Some (Ok bi) -> let rdrs = rdrs @ [ Types.redirect some_write; Types.redirect some_read; ] in let t = Fiber.fork_promise ~sw:pipeline_switch @@ fun () -> Log.name "built-in"; let bi = catch_execs_with_exit t @@ fun () -> let blt = handle_built_in ~sw:t.environ.async_switch ~rdrs t bi in await_job_ready job; close_flow ~is_global:is_stdout_global some_write; close_flow ~is_global:is_stdin_global some_read; blt in bi in let job = match bi with | Built_ins.Exit _ -> let t = Promise.await_exn t in if should_exit ~with_errexit:false t then begin if (Exit.value t).ctx.interactive then Fmt.pr "exit\n%!"; exit_from_eval t end else handle_job job (`Exit t) | _ -> handle_job job (`Built_in t) in let pctx = update_stdin ~stdin:next_read pctx in loop pctx job rest)))) | CompoundCommand (c, rdrs) :: rest as v -> ( let first = List.length p = List.length v in match handle_redirections ~for_parent:true ~sw:pipeline_switch initial_ctx rdrs with | Error ctx -> handle_job job (`Rdr (Exit.nonzero ctx 1)) | Ok (t, rdrs) -> let std = std_for_pipeline ~first ~sw:pipeline_switch (rdrs @ initial_ctx.ctx.rdrs) pctx initial_ctx rest in let ( (some_read, _is_stdin_global), (some_write, is_stdout_global), (next_read, _) ) = match std with | current_stdin, current_stdout, next_stdin -> ( get_std_with_locality current_stdin, get_std_with_locality current_stdout, get_std_with_locality next_stdin ) in let rdrs = rdrs @ [ Types.redirect some_write; Types.redirect some_read ] in let t = { t with ctx = { t.ctx with current_context = `CompoundCommand; rdrs }; } in let ctx = Fiber.fork_promise ~sw:pipeline_switch @@ fun () -> Log.name "compound-command"; with_pipeline_scope t @@ fun t -> let ctx = handle_compound_command t c in await_job_ready job; Exit.map ~f:(fun t -> { t with ctx = { t.ctx with (* rdrs = saved_rdrs; *) current_context = initial_ctx.ctx.current_context; subshell = initial_ctx.ctx.subshell; }; }) ctx in let job = handle_job job (`Built_in ctx) in (* Close stdin *) Eio.Fiber.fork ~sw: (if async then initial_ctx.environ.async_switch else pipeline_switch) (fun () -> match Promise.await ctx with | _ -> close_flow ~is_global:is_stdout_global some_write); let pctx = update_stdin ~stdin:next_read pctx in loop pctx job rest) | FunctionDefinition (name, (body, _rdrs)) :: rest -> let t = { initial_ctx with ctx = { initial_ctx.ctx with functions = List.assoc_replace_or_add (name, body) initial_ctx.ctx.functions; }; } in Debug.Log.debug (fun f -> f "Added %s %a" name Context.dump [ t.ctx ]); let job = handle_job job (`Noop (Exit.zero t)) in loop pctx job rest in let initial_job = J.make (if Option.is_some initial_ctx.environ.store then Unix.getpid () else 0) [] in let saved_ctx = initial_ctx in let subshell = saved_ctx.ctx.subshell || List.length p > 1 in let t = { initial_ctx with ctx = { initial_ctx.ctx with subshell } } in let name = Option.value ~default:"pipeline" t.ctx.current_pipeline in Eio.Switch.run ~name @@ fun sw -> let job = (* let stdout = find_first_rdr `Stdout ctx.rdrs in *) let stdin = find_first_rdr `Stdin t.ctx.rdrs in loop sw { stdin } initial_job p in let env = Types.override ~stdin:saved_ctx.environ.env#stdin t.environ.env in let environ = { t.environ with env } in (* let ctx = { ctx with environ; state = ctx.state } in *) let t = { t with environ } in match J.size job with | 0 -> Exit.zero t | _ -> if not async then begin let exit_ctxs = J.await_exit ~default:t ~pipefail:t.ctx.options.pipefail ~interactive:t.ctx.interactive job in (* Return the merged table. *) let fd_table = List.fold_left (fun m e -> Fd_table.merge m (Exit.value e).ctx.fd_table) Fd_table.empty exit_ctxs in (* Return the merged trace. *) let trace = List.fold_left (fun m e -> Trace.combine m (Exit.value e).ctx.trace) Trace.empty exit_ctxs in (* Restore the sigint handler *) Option.iter (fun v -> Sys.set_signal Sys.sigint v) (J.get_sigint job); (* Guranteed to have a head as job size > 0 *) let exit_ctx = List.hd exit_ctxs in exit_ctx >|= fun ctx -> let t = pop_local_state ctx in { t with ctx = { t.ctx with rdrs = initial_ctx.ctx.rdrs; fd_table; trace; subshell = saved_ctx.ctx.subshell; last_pipeline_status = Some (Exit.code exit_ctx); }; } end else begin (* Restore the sigint handler *) Option.iter (Sys.set_signal Sys.sigint) (J.get_sigint job); (* We must allow async jobs to be reaped, J.await_exit does this for us. *) J.reap job; let last_process = Option.map (fun p -> string_of_int (E.pid p)) @@ J.last_process job in let t = pop_local_state t in Exit.zero { t with background_jobs = job :: t.background_jobs; ctx = { t.ctx with rdrs = initial_ctx.ctx.rdrs; last_background_process = Option.value ~default:t.ctx.last_background_process last_process; subshell = saved_ctx.ctx.subshell; }; } end and handle_one_redirection ?(for_parent = false) ~sw ({ ctx; _ } as t) v = match v with | Ast.IoRedirect_IoFile (n, (op, file)) -> ( let _ctx, file = word_expansion t file in let file = Ast.Fragment.join_list ~sep:"" (List.concat file) in match op with | Io_op_less -> (* Simple redirection for input *) let r = Eio.Path.open_in ~sw (fs t / file) in let fd = fd_opt r |> Option.get in let filename = fs t / file |> Eio.Path.native_exn in let trace = Trace.add ~kind:Openat ~action:Read ~arg:filename Trace.empty in (trace, [ Types.redirect (n, fd) ]) | Io_op_lessand -> ( match file with | "-" -> if n = 0 then (Trace.empty, [ Types.Close Fd.stdin ]) else let fd = Fd.of_int ~close_underlying:true ~sw n in (Trace.empty, [ Types.Close fd ]) | m when Option.is_some (int_of_string_opt m) -> let m = int_of_string m in let v = Fd.of_int ~close_underlying:false ~sw m in (Trace.empty, [ Types.redirect (n, v) ]) | _ -> (Trace.empty, [])) | (Io_op_great | Io_op_dgreat) as v -> (* Simple file creation *) let append = v = Io_op_dgreat in let create = if append then `If_missing (file_creation_mode ctx) else if ctx.options.noclobber then `Exclusive (file_creation_mode ctx) else `Or_truncate (file_creation_mode ctx) in let w = Eio.Path.open_out ~sw ~append ~create (fs t / file) in let filename = fs t / file |> Eio.Path.native_exn in let trace = Trace.add ~kind:Openat ~action:Write ~arg:filename Trace.empty in let fd = fd_opt w |> Option.get in Debug.Log.debug (fun f -> f "Creating file (append:%b, %a): %s" append pp_fs_create create file); if n > 2 then begin Eunix.redirect (module Fd) ~sw ~src:fd ~dst:n; (trace, []) end else (trace, [ Types.redirect (n, fd) ]) | Io_op_greatand -> ( match file with | "-" -> if n = 0 then (Trace.empty, [ Types.Close Fd.stdout ]) else let fd = Fd.of_int ~close_underlying:true ~sw n in (Trace.empty, [ Types.Close fd ]) | m when Option.is_some (int_of_string_opt m) -> let m = int_of_string m in let m = Fd.of_int ~close_underlying:false ~sw m in if for_parent then begin Eunix.redirect (module Fd) ~sw ~src:m ~dst:n; (Trace.empty, []) end else (Trace.empty, [ Types.redirect (n, m) ]) | _ -> (Trace.empty, [])) | Io_op_andgreat -> (* Yesh, not very POSIX *) (* Simple file creation *) let w = Eio.Path.open_out ~sw ~create:(`If_missing (file_creation_mode ctx)) (fs t / file) in let filename = fs t / file |> Eio.Path.native_exn in let trace = Trace.add ~kind:Openat ~action:Write ~arg:filename Trace.empty in let fd = fd_opt w |> Option.get in (trace, [ Types.redirect (1, fd); Types.redirect (2, fd) ]) | Io_op_clobber -> let w = Eio.Path.open_out ~sw ~create:(`Or_truncate (file_creation_mode ctx)) (fs t / file) in let filename = fs t / file |> Eio.Path.native_exn in let trace = Trace.add ~kind:Openat ~action:Write ~arg:filename Trace.empty in let fd = fd_opt w |> Option.get in (trace, [ Types.redirect (n, fd) ]) | Io_op_lessgreat -> Fmt.failwith "<> not support yet.") | Ast.IoRedirect_IoHere (i, Ast.IoHere (_, v)) -> let _ctx, cst = word_expansion t v in let s = List.concat cst |> Ast.Fragment.join_list ~sep:"" in let r, w = E.pipe ~sw t.environ.executor in let w_flow = E.import_rw ~sw ~close_unix:false w in Eio.Flow.copy_string s w_flow; Fd.close w; (Trace.empty, [ Types.redirect (i, r) ]) | Ast.IoRedirect_IoHere (i, Ast.IoHere_Dash (_, v)) -> let _ctx, cst = word_expansion t v in let strip_tab (Ast.{ txt; _ } as v) = let txt = String.split_on_char '\n' txt |> List.map String.trim |> String.concat "\n" in { v with txt } in let s = List.concat cst |> List.map strip_tab |> Ast.Fragment.join_list ~sep:"" in let r, w = E.pipe ~sw t.environ.executor in let w_flow = E.import_rw ~sw ~close_unix:false w in Eio.Flow.copy_string s w_flow; Fd.close w; (Trace.empty, [ Types.redirect (i, r) ]) and handle_redirections ?for_parent ~sw t rdrs = try let rdrs = List.map (handle_one_redirection ?for_parent ~sw t) rdrs in let traces, rdrs = List.split rdrs |> fun (a, b) -> (List.concat a, List.concat b) in let t = { t with ctx = { t.ctx with trace = Trace.combine traces t.ctx.trace } } in Ok (t, rdrs) with Eio.Io (Eio.Fs.E (Already_exists _), _) -> Fmt.epr "msh: cannot overwrite existing file\n%!"; Error t and parameter_expansion ctx ast : t Exit.t * Ast.fragment list = let get_prefix ~pattern ~kind param = let _, prefix = String.fold_left (fun (so_far, acc) c -> match acc with | Some s when kind = `Smallest -> (so_far, Some s) | _ -> ( let s = so_far ^ String.make 1 c in match Glob.test ~pattern s with | true -> (s, Some s) | false -> (s, acc))) ("", None) param in prefix in let get_suffix ~pattern ~kind param = let _, prefix = String.fold_left (fun (so_far, acc) c -> match acc with | Some s when kind = `Smallest -> (so_far, Some s) | _ -> ( let s = String.make 1 c ^ so_far in match Glob.test ~pattern s with | true -> (s, Some s) | false -> (s, acc))) ("", None) (String.fold_left (fun acc c -> String.make 1 c ^ acc) "" param) in prefix in let tl_or_empty v = try List.tl v with _ -> [] in let lookup_variable { ctx; _ } ~param = match int_of_string_opt param with | Some n -> ( match Array.get ~label:(Fmt.str "parameter-expansion-argv(%i)" n) ctx.argv n with | v -> Debug.Log.debug (fun f -> f "lookup argv %s => %a %i chars" param Fmt.(quote string) v (String.length v)); ( Some Ast.Fragment.[ make v ], Trace.make_entry ~arg:param Pos Read ) | exception Invalid_argument _ -> (None, Trace.make_entry ~arg:param Pos Read)) | None -> let v, e = lookup ctx ~param in Debug.Log.debug (fun f -> f "lookup %s => %a" param Fmt.(quote (option (lst Ast.Fragment.pp))) v); (v, e) in let maybe_join ctx = if in_quotes ctx then `Yes else `With_previous in let rec expand ({ ctx; _ } as t : t) v : t Exit.t * Ast.fragment list = let module Fragment = struct include Ast.Fragment let make ?(join = if in_double_quotes t then `With_previous else `Yes) ?globbable ?splittable ?tilde_expansion ?(was_quoted = in_quotes t) ?(escaping = if in_quotes t then false else true) v = Ast.Fragment.make ~join ?splittable ?tilde_expansion ?globbable ~was_quoted ~escaping v end in match v with | Ast.WordVariable v -> ( match v with | Ast.VariableAtom ("!", NoAttribute) -> (Exit.zero t, [ Fragment.make t.ctx.last_background_process ]) | Ast.VariableAtom ("?", NoAttribute) -> let status = match ctx.last_pipeline_status with | None -> [] | Some i -> [ Fragment.make (string_of_int i) ] in (Exit.zero t, status) | Ast.VariableAtom ("-", NoAttribute) -> let i = if ctx.interactive then "i" else "" in ( Exit.zero t, [ Fragment.make (Options.to_letters ctx.options ^ i) ] ) | Ast.VariableAtom ("@", NoAttribute) -> let args = tl_or_empty @@ Array.to_list ctx.argv in Debug.Log.debug (fun f -> f "expanding %@: %a\n%!" Fmt.(lst string) args); let args = if not (in_double_quotes t) then begin List.map (fun v -> Fragment.make ~join:`No ~splittable:true v) args end else let l = List.length args in List.mapi (fun idx arg -> if idx = 0 then Fragment.make ~join:`With_previous arg else if idx = l - 1 then Fragment.make ~join:`With_next arg else Fragment.make ~join:`No arg) args in (Exit.zero t, args) | Ast.VariableAtom ("*", NoAttribute) -> let args = tl_or_empty @@ Array.to_list ctx.argv in Debug.Log.debug (fun f -> f "expanding *: %a\n%!" Fmt.(list string) args); let args, e = if not (in_double_quotes t) then (List.map Ast.Fragment.make args, None) else let v, e = lookup_and_join ctx.state ~param:"IFS" in ( [ Ast.Fragment.make ~join:`With_previous (String.concat (Option.value ~default:" " v) args); ], Some e ) in (Exit.zero (add_trace_entry_opt t e), args) | Ast.VariableAtom ("#", NoAttribute) -> ( Exit.zero t, [ Fragment.make (string_of_int (List.length @@ tl_or_empty (Array.to_list ctx.argv))); ] ) | Ast.VariableAtom (n, NoAttribute) when Option.is_some (int_of_string_opt n) -> ( let n = int_of_string n in match Array.get ~label:(Fmt.str "argv(%i)" n) ctx.argv n with | v -> ( Exit.zero t, [ Fragment.make ~splittable:(not (in_double_quotes t)) v ] ) | exception Invalid_argument _ -> if in_double_quotes t then (Exit.zero t, [ Ast.Fragment.make "" ]) else (Exit.zero t, [])) | Ast.VariableAtom (s, NoAttribute) -> ( match lookup_variable t ~param:s with | None, e when not (in_quotes t) -> if ctx.options.no_unset then begin ( Exit.nonzero_msg (add_trace_entry t e) ~exit_code:1 "%s: unbound variable" s, [] ) end else (Exit.zero (add_trace_entry t e), []) | Some [ Ast.{ txt = ""; _ } ], e when not (in_quotes t) -> (Exit.zero (add_trace_entry t e), []) | (None | Some [] | Some [ Ast.{ txt = ""; _ } ]), e -> (Exit.zero (add_trace_entry t e), [ Fragment.make "" ]) | Some cst, e -> ( Exit.zero (add_trace_entry t e), update_variable ~splittable:(not (in_double_quotes t)) ~join:(maybe_join t) cst )) | Ast.VariableAtom (s, ParameterLength) -> ( let v, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match v with | None -> (Exit.zero t, [ Fragment.make "0" ]) | Some cst -> ( Exit.zero t, [ Fragment.make (string_of_int (Ast.Fragment.length cst)) ] )) | Ast.VariableAtom (s, UseDefaultValues (_, cst)) -> ( let v, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match v with | None | Some [ Ast.{ txt = ""; _ } ] -> let nctx, w = let nctx, w = word_expansion t cst in let v = List.map (fun (f : Ast.fragment) -> { f with splittable = not (in_quotes t) }) @@ List.concat w in (nctx, v) in (nctx, w) | Some cst -> ( Exit.zero t, update_variable ~splittable:(not (in_quotes t)) ~join:(maybe_join t) cst )) | Ast.VariableAtom ( s, (( RemoveSmallestPrefixPattern cst | RemoveLargestPrefixPattern cst ) as v) ) -> ( let t, spp = word_expansion t cst in match t with | Exit.Nonzero _ as t -> (t, [ Fragment.make "" ]) | Exit.Zero t -> ( let pattern = Fragment.join_list ~sep:"" (List.concat spp) in let var, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match var with | None -> let fs = if in_quotes t then [ Ast.Fragment.make "" ] else [] in (Exit.zero t, fs) | Some cst -> ( let kind = match v with | RemoveSmallestPrefixPattern _ -> `Smallest | RemoveLargestPrefixPattern _ -> `Largest | _ -> assert false in let param = Ast.Fragment.join_list ~sep:"" cst in let prefix = get_prefix ~pattern ~kind param in let splittable = not (in_quotes t) in match prefix with | None | Some "" -> (Exit.zero t, [ Fragment.make ~splittable param ]) | Some s -> ( match String.cut_prefix ~prefix:s param with | Some s -> (Exit.zero t, [ Fragment.make ~splittable s ]) | None -> (Exit.zero t, [ Fragment.make ~splittable param ]) )))) | Ast.VariableAtom ( s, (( RemoveSmallestSuffixPattern cst | RemoveLargestSuffixPattern cst ) as v) ) -> ( let ctx, spp = word_expansion t cst in let pattern = Fragment.join_list ~sep:"" (List.concat spp) in match ctx with | Exit.Nonzero _ as ctx -> (ctx, [ Fragment.empty ]) | Exit.Zero t -> ( let var, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match var with | Some [ { txt = ""; _ } ] | None -> let fs = if in_quotes t then [ Ast.Fragment.make "" ] else [] in (Exit.zero t, fs) | Some cst -> ( let kind = match v with | RemoveSmallestSuffixPattern _ -> `Smallest | RemoveLargestSuffixPattern _ -> `Largest | _ -> assert false in let param = Ast.Fragment.join_list ~sep:"" cst in let suffix = get_suffix ~pattern ~kind param in let splittable = not (in_quotes t) in match suffix with | None -> (Exit.zero t, [ Fragment.make ~splittable param ]) | Some s -> ( match String.cut_suffix ~suffix:s param with | Some s -> (Exit.zero t, [ Fragment.make ~splittable s ]) | None -> (Exit.zero t, [ Fragment.make ~splittable param ]) )))) | Ast.VariableAtom (s, UseAlternativeValue (_, alt)) -> ( let nctx, alt = word_expansion t alt in let var, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match var with | Some [ { txt = ""; _ } ] | None -> let fs = if in_quotes t then [ Ast.Fragment.make "" ] else [] in (nctx, fs) | Some _ -> let alt = List.map (fun (f : Ast.fragment) -> { f with splittable = not (in_quotes t) }) @@ List.concat alt in (nctx, alt)) | Ast.VariableAtom (s, AssignDefaultValues (_, value)) -> ( let new_ctx, value = word_expansion t value in let var, e = lookup_variable t ~param:s in let t = add_trace_entry t e in match var with | Some [ { txt = ""; _ } ] | None -> ( match S.update ctx.state ~param:s (List.concat value) with | Ok state, e -> let new_t = Exit.value new_ctx in let new_ctx = { new_t with ctx = { new_t.ctx with state; trace = e :: new_t.ctx.trace; }; } in (Exit.zero new_ctx, List.concat value) | Error m, e -> ( Exit.nonzero_msg ~exit_code:1 (add_trace_entry t e) "%s" m, [] )) | Some cst -> (new_ctx, cst)) | Ast.VariableAtom (p, IndicateErrorifNullorUnset (_, msg)) -> ( let v, e = lookup ~param:p ctx in let t = add_trace_entry t e in match v with | None | Some [] | Some [ { txt = ""; _ } ] -> let _ctx, fs = word_expansion t msg in ( Exit.nonzero_msg t "msh err: %s: %s" p (Ast.Fragment.join_list ~sep:"" (List.concat fs)), [] ) | Some f -> (Exit.zero t, f))) | Ast.WordDoubleQuoted [] -> (Exit.zero t, [ Ast.Fragment.empty ]) | Ast.WordDoubleQuoted cst -> ( let saved_dqoute = ctx.quotes in let t = { t with ctx = { t.ctx with quotes = `Double } } in let new_ctx, cst_acc = word_expansion t cst in let new_ctx = Exit.map ~f:(fun t -> { t with ctx = { t.ctx with quotes = saved_dqoute } }) new_ctx in match new_ctx with | Exit.Nonzero _ -> (new_ctx, List.concat cst_acc) | Exit.Zero new_ctx -> (Exit.zero new_ctx, List.concat cst_acc)) | Ast.WordSingleQuoted [] -> (Exit.zero t, [ Ast.Fragment.empty ]) | Ast.WordSingleQuoted cst -> ( let saved_dqoute = ctx.quotes in let ctx = { t with ctx = { t.ctx with quotes = `Single } } in let new_ctx, cst_acc = word_expansion ctx cst in let new_ctx = Exit.map ~f:(fun t -> { t with ctx = { t.ctx with quotes = saved_dqoute } }) new_ctx in match new_ctx with | Exit.Nonzero _ -> (new_ctx, List.concat cst_acc) | Exit.Zero new_ctx -> (Exit.zero new_ctx, List.concat cst_acc)) | Ast.WordAssignmentWord (Name n, w) -> ( let new_ctx, cst_acc = word_expansion t w in match new_ctx with | Exit.Nonzero _ -> (new_ctx, List.concat cst_acc) | Exit.Zero _ -> ( new_ctx, [ Fragment.make (n ^ "=" ^ Fragment.join_list ~sep:"" (List.concat cst_acc)); ] )) | Ast.WordSubshell sub -> (* Command substitution *) let saved_ctx = t in let t = { t with ctx = { ctx with quotes = `None } } in Debug.Log.info (fun f -> f "Subshell %a" Ast_pp.complete_commands sub); let es, s = command_substitution t sub in let saved_ctx = { saved_ctx with ctx = { saved_ctx.ctx with trace = es @ saved_ctx.ctx.trace }; } in Debug.Log.info (fun f -> f "Subshell done"); ( Exit.zero saved_ctx, [ Fragment.make ~splittable:(not (in_quotes saved_ctx)) ~join:`Yes s; ] ) | Ast.WordArithmeticExpression cst -> let diff t1 t2 = Trace.diff t1.ctx.trace t2.ctx.trace in let aexpand state ~param = match expand { t with ctx = { t.ctx with state } } (Sast.WordVariable param) with | e, [] -> (None, diff t (Exit.value e)) | e, frags -> ( Some (Ast.Fragment.join_list ~sep:"" frags), diff t (Exit.value e) ) in arithmetic_expansion ~expand:aexpand t cst |> fun (ctx, v) -> (Exit.zero ctx, [ Fragment.make @@ string_of_int v ]) | Ast.WordName s -> (Exit.zero t, [ Fragment.make s ]) | Ast.WordLiteral s -> let v = Fragment.make s in (Exit.zero t, [ v ]) | Ast.WordGlobAll -> (Exit.zero t, [ Fragment.make ~globbable:true "*" ]) | Ast.WordGlobAny -> (Exit.zero t, [ Fragment.make ~globbable:true "?" ]) | Ast.WordTildePrefix s -> (Exit.zero t, [ Fragment.make ~tilde_expansion:true s ]) | Ast.WordEmpty -> let fs = if in_quotes t then [ Ast.Fragment.make "" ] else [] in (Exit.zero t, fs) | v -> Fmt.failwith "TODO: expansion of %a" yojson_pp (Ast.word_component_to_yojson v) in expand ctx ast and split_fields ifs s = let v, ls = String.fold_left (fun (so_far, ls) c -> if String.contains ifs c then begin if has_ws ifs && String.(equal so_far empty) then ("", ls) else ("", so_far :: ls) end else (so_far ^ String.make 1 c, ls)) ("", []) s in List.rev (v :: ls) and field_splitting { ctx; _ } v = let ifs, _ = lookup ctx ~param:"IFS" in let rec loop = function | [] -> [] | Ast.{ splittable = true; txt; globbable; _ } :: rest -> ( let ifs = Option.map (Ast.Fragment.join_list ~sep:"") ifs in match ifs with | Some "" -> [ Ast.Fragment.make ~join:`No ~globbable txt ] | (None | Some _) as ifs -> let ifs = Option.value ~default:" \t\n" ifs in let txt = if has_ws ifs then String.trim txt else txt in (split_fields ifs txt |> List.map (Ast.Fragment.make ~globbable)) @ loop rest) | txt :: rest -> txt :: loop rest in let fields = loop v in match fields with | [] | [ _ ] -> fields | _ -> ( (* Remove empty final field if any *) let fields = match List.rev fields with | { Sast.txt = ""; _ } :: rest -> List.rev rest | _ -> fields in match (Option.map (Ast.Fragment.join_list ~sep:"") ifs, fields) with | Some w, { Sast.txt = ""; _ } :: rest when String.contains w ' ' -> rest | _ -> fields) and word_expansion' ctx cst : t Exit.t * Ast.fragments = let cst = tilde_expansion ctx cst in parameter_expansion ctx cst and word_expansion ?collect ?(update = false) (t : t) cst : t Exit.t * Ast.fragments list = let rec aux ctx = function | [] -> (ctx, []) (* one empty word *) | c :: rest -> let new_ctx, l = word_expansion' (Exit.value ctx) c in let next_ctx, r = aux new_ctx rest in let combined = l @ r in (next_ctx, combined) in let ctx, cst = aux (Exit.zero t) cst in let ctx = match (ctx, collect) with | _, None -> ctx | Exit.Nonzero _, Some _ -> ctx | Exit.Zero t, Some param -> ( Debug.Log.debug (fun f -> f "collect assignment: %s is %a" param Fmt.(lst @@ Ast.Fragment.pp) cst); let state, e = if update then begin let export = t.ctx.options.all_export in S.update ~export t.ctx.state ~param cst |> map_snd Option.some end else (Ok t.ctx.state, None) in let t = add_trace_entry_opt t e in match state with | Error message -> Exit.nonzero ~message t 1 | Ok state -> let v = (param, cst) in let local_state = match Stack.pop t.ctx.local_state with | Some (h, rest) -> let h = v :: h in Stack.push h rest | None -> Stack.push [ v ] Stack.empty in Exit.Zero { t with ctx = { t.ctx with state; local_state } }) in let cst = Ast.Fragment.handle_joins cst in match ctx with | Exit.Nonzero _ -> (ctx, [ cst ]) | Exit.Zero t -> let fields = cst in let fields = field_splitting t fields in let t = add_trace_entry t (Trace.make_entry ~arg:"IFS" Env Read) in let (t, cst) : t * Ast.fragments list = begin let glob = Ast.Fragment.join_list ~sep:"" fields in let vs : Ast.fragments list = let has_glob = List.exists (fun (f : Ast.fragment) -> f.globbable) fields in let _new_ctx, s = if (not t.ctx.options.no_path_expansion) && has_glob then glob_expand t glob else if t.ctx.options.no_path_expansion && has_glob then (t, [ Ast.Fragment.make glob ]) else (t, fields) in [ s ] in (t, vs) end in (Exit.zero t, List.map Ast.Fragment.handle_joins cst) and handle_assignments kind ({ ctx; _ } as t : t) (assignments : string list) = let flags, assignments = List.fold_left (fun (fs, args) v -> match Astring.String.cut ~sep:"-" v with | Some ("", f) -> (f :: fs, args) | _ -> (fs, v :: args)) ([], []) assignments in let update = match kind with | `Export -> update ~export:true ~readonly:false ~local:false | `Readonly -> update ~export:false ~readonly:true ~local:false | `Local -> update ~export:false ~readonly:false ~local:true in let read_arg acc_ctx param = (* TODO: quoting? *) match read_env_var param with | Some (param, v) -> update acc_ctx ~param v | None -> ( let v, e = S.lookup acc_ctx.ctx.state ~param in let acc_ctx = add_trace_entry acc_ctx e in match v with | Some v -> update acc_ctx ~param v | None -> update acc_ctx ~param [ (* TODO: Empty string? *) ]) in match (flags, assignments) with | [], assignments -> List.fold_left (fun ctx w -> match ctx with Exit.Zero ctx -> read_arg ctx w | _ -> ctx) (Exit.zero t) assignments | fs, _assignments -> if List.mem ~compare:String.compare "p" fs then begin match kind with | `Readonly -> S.pp_readonly Fmt.stdout ctx.state | `Export -> S.pp_export Fmt.stdout ctx.state | `Local -> () end; Exit.zero t and expand_redirects ((ctx, acc) : t * Ast.cmd_suffix_item list) (c : Ast.cmd_suffix_item list) = match c with | [] -> (ctx, List.rev acc) | Ast.Suffix_redirect (IoRedirect_IoFile (num, (op, file))) :: rest -> ( let ctx, cst = word_expansion ctx file in match ctx with | Exit.Nonzero _ -> Fmt.failwith "Redirect expansion" | Exit.Zero ctx -> let cst = List.map (fun Ast.{ txt; _ } -> Ast.WordLiteral txt) (List.concat cst) in let v = Ast.Suffix_redirect (IoRedirect_IoFile (num, (op, cst))) in expand_redirects (ctx, v :: acc) rest) | (Ast.Suffix_redirect _ as v) :: rest -> expand_redirects (ctx, v :: acc) rest | s :: rest -> expand_redirects (ctx, s :: acc) rest and handle_and_or ~async ctx c = let pipeline = function | Ast.Pipeline p -> (Fun.id, p) | Ast.Pipeline_Bang p -> (Exit.not, p) in let rec fold : Ast.and_or * t Exit.t -> Ast.pipeline Ast.and_or_list -> t Exit.t = fun (sep, exit_so_far) pipe -> match (sep, pipe) with | And, Nlist.Singleton (p, _) -> ( match exit_so_far with | Exit.Zero ctx -> let f, p = pipeline p in f @@ handle_pipeline ~async ctx p | v -> v) | Or, Nlist.Singleton (p, _) -> ( match exit_so_far with | Exit.Zero _ as ctx -> ctx | _ -> let f, p = pipeline p in f @@ handle_pipeline ~async ctx p) | Noand_or, Nlist.Singleton (p, _) -> let f, p = pipeline p in f @@ handle_pipeline ~async ctx p | Noand_or, Nlist.Cons ((p, next_sep), rest) -> let f, p = pipeline p in let exit_status = f (handle_pipeline ~async ctx p) in fold (next_sep, exit_status) rest | And, Nlist.Cons ((p, next_sep), rest) -> ( match exit_so_far with | Exit.Zero ctx -> let f, p = pipeline p in fold (next_sep, f (handle_pipeline ~async ctx p)) rest | Exit.Nonzero _ as v -> v) | Or, Nlist.Cons ((p, next_sep), rest) -> ( match exit_so_far with | Exit.Zero _ as exit_so_far -> fold (next_sep, exit_so_far) rest | Exit.Nonzero _ -> let f, p = pipeline p in fold (next_sep, f (handle_pipeline ~async ctx p)) rest) in match fold (Noand_or, Exit.zero ctx) c with | Exit.Zero _ as v -> v | Exit.Nonzero n -> if Nlist.length c > 1 then Exit.Nonzero { n with should_exit = { n.should_exit with non_interactive = `No }; } else Exit.Nonzero n and handle_for_clause (t : t) v : t Exit.t = match v with | Ast.For_Name_DoGroup (_, (term, sep)) -> exec t (term, Some sep) | Ast.For_Name_In_WordList_DoGroup (Name name, wdlist, (term, sep)) -> ( Debug.Log.debug (fun f -> f "for-loop: start"); (* TODO: fold ctx with exit value... *) let t, wdlist = Nlist.fold_left (fun (ctx, acc) wd -> Debug.Log.debug (fun f -> f "FOR: Local state: %a" Context.dump [ (Exit.value ctx).ctx ]); let ctx, w = word_expansion (Exit.value ctx) wd in Debug.Log.debug (fun f -> f "FOR: %a" Fmt.(lst @@ lst Ast.Fragment.pp) w); if w = [ [] ] then (ctx, acc) else (ctx, acc @ [ w ])) (Exit.zero t, []) wdlist in try let v : t Exit.t = List.fold_left (fun (ctx : t Exit.t) words -> Fiber.yield (); let ctx = Exit.value ctx in List.fold_left (fun ctx word -> update (Exit.value ctx) ~param:name [ word ] >>= fun ctx -> try exec ctx (term, Some sep) with | Continue (1, ctx) -> Exit.zero ctx | Continue (n, ctx) -> raise (Continue (n - 1, ctx))) (Exit.zero ctx) (List.concat words)) t wdlist in v with | Break (1, ctx) -> Exit.zero ctx | Break (n, ctx) -> raise (Break (n - 1, ctx))) and handle_if_clause (t : t) = function | Ast.If_then ((e1, sep1), (e2, sep2)) -> ( let ctx = exec t (e1, Some sep1) in match ctx with | Exit.Zero ctx -> exec ctx (e2, Some sep2) | Exit.Nonzero { value = ctx; _ } -> Exit.zero ctx) | Ast.If_then_else ((e1, sep1), (e2, sep2), else_part) -> ( let ctx = exec t (e1, Some sep1) in match ctx with | Exit.Zero ctx -> exec ctx (e2, Some sep2) | Exit.Nonzero { value = ctx; _ } -> handle_else_part ctx else_part) and handle_else_part ctx = function | Ast.Else (c, sep) -> exec ctx (c, Some sep) | Ast.Elif_then ((e1, sep1), (e2, sep2)) -> ( let ctx = exec ctx (e1, Some sep1) in match ctx with | Exit.Zero ctx -> exec ctx (e2, Some sep2) | Exit.Nonzero { value = ctx; _ } -> Exit.zero ctx) | Ast.Elif_then_else ((e1, sep1), (e2, sep2), else_part) -> ( let ctx = exec ctx (e1, Some sep1) in match ctx with | Exit.Zero ctx -> exec ctx (e2, Some sep2) | Exit.Nonzero { value = ctx; _ } -> handle_else_part ctx else_part) and handle_case_clause ctx = function | Ast.Case _ -> Exit.zero ctx | Cases (word, case_list) -> ( let ctx, word = word_expansion ctx word in match ctx with | Exit.Nonzero _ as ctx -> ctx | Exit.Zero t -> ( let scrutinee = Ast.Fragment.join_list ~sep:"" @@ List.concat word in let res = Nlist.fold_left (fun acc pat -> match acc with | Some _ as ctx -> ctx | None -> ( match pat with | Ast.Case_pattern (p, sub) -> Nlist.fold_left (fun inner_acc pattern -> match inner_acc with | Some _ as v -> v | None -> let _, pattern = word_expansion { t with ctx = { t.ctx with options = Options.with_options ~no_path_expansion:true t.ctx.options; }; } pattern in let pattern = Ast.Fragment.join_list ~sep:"" (List.concat pattern) in if Glob.test ~pattern scrutinee then begin match sub with | Some (c, sep) -> Some (exec t (c, Some sep)) | None -> Some (Exit.zero t) end else inner_acc) None p)) None case_list in match res with Some ctx -> ctx | None -> Exit.zero t)) and exec_subshell ctx (term, sep) = let saved_ctx = ctx in Debug.Log.debug (fun f -> f "enter subshell"); let e = exec ctx (term, Some sep) in Debug.Log.debug (fun f -> f "leave subshell"); let v = e >|= fun _ -> saved_ctx in v and handle_while_clause ctx (While ((term, sep), (term', sep')) : Ast.while_clause) = let rec loop exit_so_far = let running_ctx = Exit.value exit_so_far in match exec running_ctx (term, Some sep) with | Exit.Nonzero { value; _ } -> Exit.map ~f:(fun _ -> value) exit_so_far (* TODO: Context? *) | Exit.Zero ctx -> (* Before we loop, we yield to other pipeline tasks. *) Fiber.yield (); loop (try exec ctx (term', Some sep') with | Continue (1, ctx) -> Exit.zero ctx | Continue (n, ctx) -> raise (Continue (n - 1, ctx))) in try loop (Exit.zero ctx) with | Break (1, ctx) -> Exit.zero ctx | Break (n, ctx) -> raise (Break (n - 1, ctx)) and handle_until_clause ctx (Until ((term, sep), (term', sep')) : Ast.until_clause) = let rec loop exit_so_far = let running_ctx = Exit.value exit_so_far in match exec running_ctx (term, Some sep) with | Exit.Zero value -> Exit.map ~f:(fun _ -> value) exit_so_far (* TODO: Context? *) | Exit.Nonzero { value = ctx; _ } -> loop (try exec ctx (term', Some sep') with | Continue (1, ctx) -> Exit.zero ctx | Continue (n, ctx) -> raise (Continue (n - 1, ctx))) in try loop (Exit.zero ctx) with | Break (1, ctx) -> Exit.zero ctx | Break (n, ctx) -> raise (Break (n - 1, ctx)) and handle_compound_command ctx v : t Exit.t = match v with | Ast.ForClause fc -> handle_for_clause ctx fc | Ast.IfClause if_ -> handle_if_clause ctx if_ | Ast.BraceGroup (term, sep) -> exec ctx (term, Some sep) | Ast.Subshell s -> exec_subshell ctx s | Ast.CaseClause cases -> handle_case_clause ctx cases | Ast.WhileClause while_ -> handle_while_clause ctx while_ | Ast.UntilClause until -> handle_until_clause ctx until and handle_function_application (t : t) ~name argv : (t, unit -> t Exit.t) Either.t = let v, t = with_ctx t (Context.find_function ~name t.ctx) in match v with | None -> Either.left t | Some commands -> Debug.Log.debug (fun f -> f "function enter: %s [%a]" name Fmt.(list ~sep:Fmt.(any " ") (quote string)) argv); (* Add new variable scope for locals *) let new_state = S.push t.ctx.state in let t = { t with ctx = { t.ctx with argv = Array.of_list argv; (* subshell = true; *) state = new_state; }; } in let v = Either.right @@ fun () -> try let t = handle_compound_command t commands in let t = Exit.map ~f:(fun t -> { t with ctx = { t.ctx with state = S.pop t.ctx.state } }) t in Debug.Log.debug (fun f -> f "function leave: %s" name); t with Return t -> Exit.map ~f:(fun t -> { t with ctx = { t.ctx with state = S.pop t.ctx.state } }) t in v and command_substitution (t : t) (cc : Ast.complete_commands) : Trace.t * string = let exec_subshell t s = let buf = Buffer.create 16 in let stdout = Eio.Flow.buffer_sink buf in let sub_ctx = Eio.Switch.run ~name:"command-sub" @@ fun sw -> let r, w = E.pipe ~sw t.environ.executor in let r_flow = E.import_ro ~sw ~close_unix:false r in Eio.Fiber.fork ~sw (fun () -> Log.name "command-sub-copy"; Eio.Flow.copy r_flow stdout); let rdrs = Types.Redirect (false, 1, w) :: t.ctx.rdrs in let subshell_ctx = { t with ctx = { t.ctx with subshell = true; rdrs } } in let sub_ctx, _ = run (Exit.zero subshell_ctx) s in Fd.close w; sub_ctx in ((sub_ctx >|= fun _ -> t), Buffer.contents buf) in let run_subshells s = let new_t, std = exec_subshell t s in (Trace.diff t.ctx.trace (Exit.value new_t).ctx.trace, String.trim std) in run_subshells cc and glob_expand ({ ctx; _ } as t : t) pattern : t * Ast.fragment list = Debug.Log.info (fun f -> f "Expanding %s" pattern); Eio.Switch.run @@ fun sw -> let dir = if not @@ Filename.is_relative pattern then fs t else Eio.Path.open_dir ~sw (fs t / Fpath.to_string (S.cwd ctx.state)) in ( t, match Glob.glob_dir dir pattern with | [] -> Debug.Log.debug (fun f -> f "Glob %s returned nothing" pattern); [ Ast.Fragment.make pattern ] | exception e -> Debug.Log.debug (fun f -> f "Glob expand exception: %s" (Printexc.to_string e)); [] | xs -> Debug.Log.debug (fun f -> f "Globbed %s to [%a]" pattern Fmt.(list (quote string)) xs); List.map Ast.Fragment.make xs ) and collect_assignments ?(update = true) (ctx : t) vs : t Exit.t = List.fold_left (fun ctx prefix -> match ctx with | Exit.Nonzero _ -> ctx | Exit.Zero ctx -> ( match prefix with | Ast.Prefix_assignment (Name param, v) -> (* Expand the values but update the state too. *) let ctx, _v = word_expansion ~collect:param ~update ctx v in ctx | _ -> Exit.zero ctx)) (Exit.zero ctx) vs and args ctx swc : t Exit.t * string list = let ctx, fs = List.fold_left (fun (ctx, acc) -> function | Ast.Suffix_redirect _ -> (ctx, acc) | Suffix_word wc -> ( match ctx with | Exit.Nonzero _ as ctx -> (ctx, acc) | Exit.Zero ctx -> ( let ctx, cst = word_expansion ctx wc in match ctx with | Exit.Nonzero _ as ctx -> (ctx, acc) | Exit.Zero _ as ctx -> (ctx, acc @ List.map Ast.Fragment.handle_joins cst)))) (Exit.zero ctx, []) swc in let arguments = List.map Ast.Fragment.to_string (List.concat fs) in (ctx, arguments) and handle_built_in : sw:Eio.Switch.t -> rdrs:Fd.t Types.redirect list -> t -> Built_ins.t -> t Exit.t = fun ~sw ~rdrs ({ ctx; environ; _ } as t : t) v -> let rdrs = make_child_rdrs_for_parent rdrs in Eunix.with_redirections (module Fd) ~sw ~restore:true rdrs @@ fun () -> Debug.Log.debug (fun f -> f "built-in: %s" (Built_ins.to_string v)); match v with | Built_ins.Msh_info -> let str = Fmt.str "msh-info\n%a\n" Context.dump [ ctx ] in Eio.Flow.copy_string str (stdout t); Exit.zero t | Cd { path } -> let cwd = S.cwd ctx.state in let+ state = match path with | Some p -> let fp = Fpath.append cwd (Fpath.v p) in if Eio.Path.is_directory (fs t / Fpath.to_string fp) then begin Unix.chdir (Fpath.to_string fp); Exit.zero @@ S.set_cwd ctx.state (Fpath.normalize fp) end else Exit.nonzero_msg ~exit_code:1 ctx.state "cd: not a directory: %a" Fpath.pp fp | None -> ( let v, e = S.lookup ctx.state ~param:"HOME" in let ctx = { ctx with trace = e :: ctx.trace } in match v with | None -> Exit.nonzero_msg ctx.state "HOME not set" | Some p -> let p = Ast.Fragment.join_list ~sep:"" p in Exit.zero (S.set_cwd ctx.state @@ Fpath.v p)) in { t with ctx = { ctx with state } } | Pwd -> let () = Eio.Flow.copy_string (Fmt.str "%a\n%!" Fpath.pp (S.cwd ctx.state)) (stdout t) in Exit.zero t | Exit n -> let should_exit = { Exit.default_should_exit with interactive = `Yes } in Exit.nonzero ~should_exit t n | Return 0 -> raise (Return (Exit.zero t)) | Return n -> raise (Return (Exit.nonzero t n)) | Break n -> raise (Break (n, t)) | Continue n -> raise (Continue (n, t)) | Set { update; arguments; print_options } -> let v = Exit.zero { t with ctx = { t.ctx with options = Options.update t.ctx.options update; argv = (if arguments = [] then t.ctx.argv else Array.of_list (Array.get ~label:"set" ctx.argv 0 :: arguments)); }; } in if print_options then Eio.Flow.copy_string (Fmt.str "%a" Options.pp ctx.options) (stdout t); v | Wait i -> ( match Unix.waitpid [] i with | _, WEXITED 0 -> Exit.zero t | _, (WEXITED n | WSIGNALED n | WSTOPPED n) -> Exit.nonzero t n) | Dot file -> ( let hash, prog = Eunix.resolve_program ~path:(S.path ctx.state) ctx.hash file in let t = { t with ctx = { ctx with hash } } in match prog with | None -> Exit.nonzero t 127 | Some fname -> Debug.Log.debug (fun f -> f "sourcing..."); let program = Ast.of_file (fs t / fname) in let ctx, _ = run' ~make_process_group:false (Exit.zero t) program in Debug.Log.debug (fun f -> f "finished sourcing %s" fname); ctx) | Unset names -> ( match names with | `Variables names -> let state, es = List.fold_left (fun (t, es) param -> S.remove ~param t |> fun (_, st, e) -> (st, e :: es)) (ctx.state, []) names in Exit.zero { t with ctx = { ctx with state; trace = es @ ctx.trace } } | `Functions names -> let functions = List.fold_left (fun t param -> List.remove_assoc ~compare:String.compare param t) ctx.functions names in Exit.zero { t with ctx = { ctx with functions } }) | Hash v -> ( match v with | Built_ins.Hash_remove -> Exit.zero { t with ctx = { ctx with hash = Hash.empty } } | Built_ins.Hash_stats -> Eio.Flow.copy_string (Fmt.str "%a" Hash.pp ctx.hash) (stdout t); Exit.zero t | _ -> assert false) | Alias | Unalias -> Exit.zero t (* Morbig handles this for us *) | Eval args -> let script = String.concat " " args in (* TODO: Hmmm, might be a Morbig issue... *) let script = unescape_eval script in let ast = Ast.of_string script in let ctx, _ = run (Exit.zero t) ast in ctx | Echo args -> let str = String.concat " " args ^ "\n" in Eio.Flow.copy_string str (stdout t); Exit.zero t | Trap (action, signals) -> let saved_ctx = t in let sig_action = match action with | Action m -> let ast = Ast.of_string m in let f _signal_number = Queue.push (fun ctx -> let ctx, _ = run (Exit.zero ctx) ast in ctx) saved_ctx.environ.signal_handler.run_queue in Sys.Signal_handle f | Default -> Sys.Signal_default | Ignore -> Sys.Signal_ignore | Int _ -> assert false in Exit.zero @@ List.fold_left (fun t signal -> match signal with | `Exit -> let action = match action with | Default | Int _ | Ignore -> None | Action m -> Some (Ast.of_string m) in { t with ctx = { t.ctx with exit_handler = action } } | `Signal signal -> let action = (* Handle sigint separately for interactive mode *) match (sig_action, signal) with | Sys.Signal_default, Eunix.Signals.Interrupt -> if ctx.interactive then Sys.Signal_ignore else sig_action | _ -> sig_action in let setting_sigint = environ.signal_handler.sigint_set = false && match action with | Sys.Signal_handle _ -> true | _ -> false in Sys.set_signal (Eunix.Signals.to_int signal) action; { t with environ = { environ with signal_handler = { environ.signal_handler with sigint_set = setting_sigint; }; }; }) t signals | Umask None -> let str = Fmt.str "0%o\n" ctx.umask in Eio.Flow.copy_string str (stdout t); Exit.zero t | Umask (Some i) -> Exit.zero { t with ctx = { ctx with umask = i } } | Shift n -> (* Since we store $0 in argv, we need to shift everything starting from position 1 *) let n = Option.value ~default:1 n in let arg_len = Array.length ctx.argv - 1 in let new_len = arg_len - n in if new_len < 0 then begin Fmt.epr "Shift count out of range\n%!"; Exit.nonzero t 1 end else let argv = List.init new_len (fun i -> Array.get ~label:"shift" ctx.argv (i + n + 1)) in let argv = Array.get ~label:"shift-2" ctx.argv 0 :: argv |> Array.of_list in Exit.zero { t with ctx = { ctx with argv } } | Read (_backslash, vars) -> ( let line = let buf = Cstruct.create 1 in let rec loop acc = match Eio.Flow.read_exact (stdin t) buf; Cstruct.to_string buf with | "\n" -> Some acc | c -> loop (acc ^ c) | exception End_of_file -> if String.equal acc "" then None else Some acc in loop "" in let rec loop acc = function | v :: vars, Ast.{ txt; _ } :: fs -> loop ((v, txt) :: acc) (vars, fs) | _, [] -> List.rev acc | [], lines -> let last_var, last_line = List.hd acc in List.rev ((last_var, last_line ^ Ast.Fragment.join_list ~sep:" " lines) :: acc) in let fields = Option.map (fun s -> ( field_splitting t [ Ast.Fragment.make ~splittable:true s ], Trace.make_entry ~arg:"IFS" Env Read )) line in let t = add_trace_entry_opt t (Option.map snd fields) in match fields with | None -> Exit.nonzero t 1 | Some (fs, _) -> let vars = loop [] (vars, fs) in let state, es = List.fold_left (fun (st, es) (k, v) -> (* TODO: Maybe just return the raw fragments from the loop... *) let v, e = S.update ?id:ctx.current_pipeline st ~param:k [ Ast.Fragment.make v ] in (v |> Result.get_ok, e :: es)) (ctx.state, []) vars in Exit.zero { t with ctx = { ctx with state; trace = es @ t.ctx.trace } }) | Getopts { optstring; name; params = _ } -> ( let optind, e = get_optind ctx in let t = add_trace_entry t e in match Array.get ~label:"getopts" ctx.argv optind with | exception Invalid_argument _ -> let _, state, e = S.remove ~param:"OPTARG" ctx.state in Exit.nonzero { t with ctx = { ctx with state; trace = e :: t.ctx.trace } } 127 | arg -> ( let is_arg arg c = let c = String.make 1 c in String.equal arg ("-" ^ c) || String.equal arg ("--" ^ c) in let match_flag_or_arg arg = List.find_map (function | `Flag f -> if is_arg arg f then Some (`Flag f) else None | `Arg f -> if is_arg arg f then Some (`Arg f) else None) optstring in match match_flag_or_arg arg with | None -> let _, state, e = S.remove ~param:"OPTARG" ctx.state in Exit.nonzero { t with ctx = { ctx with state; trace = e :: ctx.trace } } 127 | Some (`Flag f) -> let _, state, e = S.remove ~param:"OPTARG" ctx.state in let state, e2 = S.update state ~param:name [ Ast.Fragment.make (String.make 1 f) ] in let state = Result.get_ok' state in Exit.zero { t with ctx = set_optind { ctx with state; trace = e2 :: e :: ctx.trace } (optind + 1); } | Some (`Arg f) -> let argument = match Array.get ~label:"getopts" ctx.argv (optind + 1) with | arg -> Some arg | exception _ -> None in let state, e2 = S.update ctx.state ~param:name [ Ast.Fragment.make (String.make 1 f) ] |> map_fst Result.get_ok' in let state, e1 = match argument with | Some argument -> S.update state ~param:"OPTARG" [ Ast.Fragment.make argument ] |> map_fst Result.get_ok' |> map_snd Option.some | None -> (state, None) in let t = add_trace_entry t e2 in let t = add_trace_entry_opt t e1 in Exit.zero { t with ctx = set_optind { ctx with state } (optind + 2) })) | Test test -> ( try if Built_ins.Test.run (fs t) test then Exit.zero t else Exit.nonzero t 1 with | Failure msg -> Exit.nonzero ~message:msg t 2 | Eio.Io _ -> Exit.nonzero t 1) | Meta meta -> run_meta t meta | X s -> ( (* User specified built-ins *) match environ.built_ins with | None -> assert false | Some (_, fn) -> fn s t) | Command _ -> (* Handled separately *) assert false and poll_signals ctx = let rec loop ctx = match Queue.pop ctx.environ.signal_handler.run_queue with | f -> loop (Exit.value (f ctx)) | exception Queue.Empty -> ctx in loop ctx and exit_from_eval : 'a. t Exit.t -> 'a = fun ctx -> Option.iter (fun ast -> let _, _ = run (Exit.zero (Exit.value ctx)) ast in Debug.Log.info (fun f -> f "Running exit handler")) (Exit.value ctx).ctx.exit_handler; Option.iter (fun f -> f (Exit.map ~f:(fun t -> t.ctx) ctx)) (Exit.value ctx).environ.internal_exit_handler; exit (Exit.code ctx) (* Meta Commands *) and run_meta (t : t) meta : t Exit.t = let s = t.environ.store in match meta with | Meta.Set_mode mode -> Store.with_latest ~default:(fun _ -> Exit.zero t) (Store.get_store_opt s) @@ fun contents -> let ctx = List.hd contents in Store.commit ~message:"mode change" t.environ.env#clock s ({ ctx with mode } :: contents); Exit.zero t | Session None -> let sessions = Store.sessions s in Fmt.pr "%a\n%!" Fmt.(list ~sep:(Fmt.any "\n") string) sessions; Exit.zero t | Session (Some v) -> ( (* Either set the session if the branch exists or create a new branch from the latest commit of the current branch *) let sessions = Store.sessions s in let rec new_name () = let name = Name_generator.new_name t.environ.env#secure_random in if List.mem ~compare:String.compare name sessions then new_name () else name in let name, image = match v with | Name n -> (n, None) | Image n -> (new_name (), Some n) | Name_and_image (n, i) -> (n, Some i) in match List.exists (String.equal name) sessions with | true -> let store = Store.set_session t.environ.env s name in Exit.zero (switch_store t (Some store)) | false -> ( let detach = Option.is_some image in match Store.fork ~detach t.environ.env s ~new_branch:name with | Error (`Msg err) -> Fmt.pr "[fork]: %a\n%!" (Logger.pp_colored `Red Fmt.string) err; Exit.zero t | Ok store -> ( match image with | None -> Exit.zero (switch_store t (Some store)) | Some img -> (* We need to pull the image and set everything up for this detached, new session *) let ctx = { t.ctx with build = Zfs_store.Build.Image img } in Store.commit ~message:(Fmt.str "from %s" img) t.environ.env#clock (Some store) [ ctx ]; Exit.zero (switch_store t s)))) | Unknown args -> Fmt.epr "%a" (Logger.pp_colored `Red Fmt.string) "Unknown Shelter Action\n"; Exit.nonzero ~message:(String.concat " " args) t 127 | Info `Current -> let sessions = Store.sessions s in let sesh = Option.value ~default:"main" (snd (Store.which_branch s t.environ.env)) in let commits = Store.commit_info s in let latest = Store.with_latest ~default:(fun () -> None) (Store.get_store_opt s) (fun c -> let e = List.hd c in Some (Repr.to_string Zfs_store.Build.t e.build)) in Fmt.pr "Sessions: %a\nCurrent: %a\nHash: %a\nCommits:@. %a\n%!" Fmt.(list ~sep:(Fmt.any ", ") string) sessions (Logger.pp_colored `Green Fmt.string) sesh Fmt.(option string) latest Fmt.(vbox ~indent:2 @@ list Fmt.commit) commits; Exit.zero t | Undo n -> ( match Store.reset_hard ~n s with | Ok s -> Exit.zero (switch_store t s) | Error msg -> Exit.nonzero ~message:msg t 44) | Replay branch -> ( match Store.replay (fun store ctx -> let t = { t with ctx; environ = { t.environ with store } } in match Ast.first_and_or_pipeline t.ctx.command with | None -> (Error (`Shell (`Msg "Failed to find command to replay")), []) | Some v -> Debug.Log.info (fun f -> f "Replaying command: %a" Ast_pp.complete_commands t.ctx.command); let r, d = run_with_store t v in ( Result.map_error (fun _ -> `Shell (`Msg "Failed to replay")) r, d )) s t.environ.env branch with | Ok store -> Exit.zero (switch_store t store) | Error (`Shell (`Msg m)) -> Fmt.epr "%a\n%!" Logger.(pp_colored `Red Fmt.string) ("Replay failed: " ^ m); Exit.nonzero t 127) | Merge branch -> ( match Store.merge s t.environ.env branch with | Ok () -> Exit.zero t | Error con -> Exit.nonzero ~message: (Fmt.str "Merged failed: %a" (Repr.pp Irmin.Merge.conflict_t) con) t 127) | Info `History -> let entries = Store.with_latest ~default:(fun () -> []) (Store.get_store_opt s) Fun.id |> List.rev in Fmt.pr "%a\n%!" Jsont.pp_json (Jsont.Json.encode Context.jsont entries |> Result.get_ok'); Exit.zero t | Check command -> ( let command = String.concat " " command |> Ast.of_string |> List.hd |> fst |> Nlist.hd in try let _new_entry, _diff = run_with_store t command in Exit.zero t with Eio.Exn.Io (Eio.Process.E _, _) -> Exit.nonzero t 127) | Commit b -> Exit.zero { t with ctx = { t.ctx with commit = b } } and run_with_store (t : t) ((complete_command, sep) : Ast.pipeline Ast.and_or_list * Ast.separator) = let entry = t.ctx in let s = t.environ.store in let build, entry = match entry.build with | Zfs_store.Build.Image img -> let build, env, _cmd, _user = Zfs_store.fetch (Store.get_ctx_exn s) img in let state = List.fold_left (fun acc v -> match read_env_var v with | Some (param, frag) -> ( match S.update acc ~param frag with | Ok v, _ -> v | Error _, _ -> acc) | None -> acc) S.empty env in let e = { entry with build = Build build; state } in (build, e) | Zfs_store.Build.Build cid -> (cid, entry) in let hash_entry = { entry with command = [ (Nlist.Singleton (complete_command, sep), None) ]; } in (* Store things under History.pre, this makes it possible to rediscover the hash for something purely from the arguments needed to execute something rather than needing, for example, the time it took to execute! Also, combine it with previous build step. *) let new_cid = Zfs_store.cid (Cid.to_string build ^ Repr.to_string Context.ctx_t Context.(set_for_hash hash_entry)) in let with_rootfs fn = if entry.mode = R then ( Zfs_store.Run.with_build ~overlays:entry.overlays (Store.get_ctx_exn s) build fn, [] ) else let diff_path = Eio.Path.( t.environ.env#fs / Filename.temp_dir "shelter-diff-" "" / "diff") in Zfs_store.Run.with_clone ~overlays:entry.overlays (Store.get_ctx_exn s) ~src:build new_cid diff_path fn in with_rootfs @@ function | `Exists path -> (* Copy the stdout log to stdout *) let pp_info ppf entry = match entry.build with | Zfs_store.Build.Image img -> Fmt.pf ppf "FROM %s" img | _ -> Ast_pp.complete_commands ppf entry.command in Debug.Log.debug (fun f -> f "[Restoring from %a]: %a" Fmt.cid new_cid (Fmt.styled (`Fg `Cyan) pp_info) entry); let () = Eio.Path.(with_open_in (t.environ.env#fs / (path :> string) / "log")) @@ fun ic -> Eio.Flow.copy ic t.environ.env#stdout in let c = Eio.Path.(load (t.environ.env#fs / (path :> string) / "hash")) in Ok (`Reset c) | `Build rootfs -> ( let spawn () = let root = Filename.concat rootfs "rootfs" in let actions = [ Void.Private.Fork_actions.pivot_root ~root entry.mode ] in Debug.Log.info (fun f -> f "Pivoting the root to %s" root); let v = Eio.Path.with_open_out ~create:(`If_missing 0o644) (t.environ.env#fs / rootfs / "log") @@ fun log -> Context.Fork.spawn ~fs:t.environ.env#fs ~stdout:t.environ.env#stdout ~log ~actions (fun upd env -> let t = { t with ctx = hash_entry; environ = { t.environ with internal_exit_handler = Some upd; env }; } in Exit.map ~f:(fun t -> t.ctx) (handle_and_or ~async:false t complete_command)) in let ctx : ctx Exit.t * Trace.t = match v with | Ok v -> v | Error s -> Fmt.invalid_arg "Failed to decode context: %s" s in ctx in let ctx, extra_trace = spawn () in let trace = extra_trace @ (Exit.value ctx).trace in match ctx with | Exit.Zero ctx -> let t = { ctx with trace } in if entry.mode = RW then let t = { t with build = Build new_cid } in Ok (`Entry (Exit.zero t, rootfs)) else Ok (`Entry (Exit.zero t, rootfs)) | Exit.Nonzero _ as e -> Error e) and exec (initial_ctx : t) ((command, sep) : Ast.complete_command) = let rec loop : ?async:bool -> t -> Ast.clist -> t Exit.t = fun ?(async = false) acc_ctx v -> let t = poll_signals acc_ctx in let run_in_fork ~async:_ t (c, sep) = let v, diff = run_with_store t (c, sep) in match v with | Ok (`Entry (ctx, _)) | Error ctx -> ( if not t.ctx.commit then Exit.map ~f:(fun ctx -> { t with ctx }) ctx else match Store.save_execution t.environ.store t.environ.env v diff with | Ok store -> Exit.map ~f:(fun ctx -> { t with ctx; environ = { t.environ with store } }) ctx | Error _ -> Exit.nonzero { t with ctx = Exit.value ctx } 127) | Ok (`Reset _) -> ( match Store.save_execution t.environ.store t.environ.env v diff with | Ok store -> let ctx = Store.with_latest ~default:(fun () -> assert false) (Store.get_store_opt store) List.hd in Exit.zero { t with ctx; environ = { t.environ with store } } | Error _ -> Fmt.failwith "Resetting failed, please contact the authors.") in match v with | Nlist.Singleton (c, sep) -> let async = match sep with Semicolon -> async | Ampersand -> true in if initial_ctx.ctx.toplevel && t.config.merge && not (Ast.is_meta_command c) then begin run_in_fork ~async t (c, sep) end else handle_and_or ~async t c | Nlist.Cons ((c, sep), cs) -> ( let async = match sep with Semicolon -> async | Ampersand -> true in let result = if initial_ctx.ctx.toplevel && t.config.merge && not (Ast.is_meta_command c) then run_in_fork ~async { t with ctx = { t.ctx with toplevel = false } } (c, sep) else handle_and_or ~async t c in match result with | Exit.Zero t -> loop { t with ctx = { t.ctx with toplevel = false } } cs | Exit.Nonzero { value = t; _ } as v -> if should_exit v then v else loop { t with ctx = { t.ctx with toplevel = false } } cs) in match sep with | Some Semicolon | None -> loop initial_ctx command | Some Ampersand -> loop ~async:true initial_ctx command and execute ctx ast = exec ctx ast and run ?(make_process_group = true) (t : t Exit.t) ast = run' ~make_process_group t ast and run' ?(make_process_group = true) (t : t Exit.t) ast = (* Make the shell its own process group *) if make_process_group then Eunix.make_process_group (); let ctx, cs = let rec loop_commands (t, cs) (c : Ast.complete_commands) = match c with | [] -> (t, cs) | command :: commands -> ( let t = Exit.value t in (* For our sanity *) let has_async = Ast.has_async command in if has_async && not t.ctx.options.async then begin Fmt.epr "You are using asynchronous operators and [set -o async] has \ not been called.\n\ %!"; exit_from_eval (Exit.nonzero t 1) end; let exit = try execute t command with | Eio.Io (Eio.Process.E (Eio.Process.Executable_not_found m), _ctx) -> Exit.nonzero_msg t ~exit_code:127 "command not found: %s" m in match exit with | Exit.Nonzero { exit_code; message; should_exit; _ } -> ( Option.iter (Fmt.epr "%s\n%!") message; match ( should_exit.interactive, should_exit.non_interactive, t.ctx.subshell, t.ctx.interactive, t.ctx.options.errexit, commands ) with | `Yes, _, false, true, _, [] | _, `Yes, false, false, _, [] -> if should_exit.interactive = `Yes && t.ctx.interactive then Fmt.epr "exit\n%!"; Stdlib.exit exit_code | _, `Yes, false, false, true, _ -> Stdlib.exit exit_code | _ -> loop_commands (exit, c :: cs) commands) | Exit.Zero _ as ctx -> loop_commands (ctx, c :: cs) commands) in loop_commands (t, []) ast in (ctx, List.rev cs) end