open Uxn open Effect.Deep let trace = Option.is_some (Sys.getenv_opt "UXNEMU_DEBUG") module System = Varvara.System.Make () module Console = Varvara.Console.Make () module File = Uxn.Device.Compose (Varvara.File.Make (struct let start = 0xa0 end)) (Varvara.File.Make (struct let start = 0xb0 end)) module Devices = Uxn.Device.Compose (Uxn.Device.Compose (System) (Console)) (File) let run m pc = let dev = Machine.dev m in try Machine.dispatch ~trace m pc with | effect Machine.Trace (pc, instr, args), k -> if trace then begin Printf.eprintf "PC = %04x %6s %s\n" pc (Instr.to_string instr) (List.map (Format.sprintf "%02x") args |> String.concat " "); Out_channel.flush stderr end; continue k () | effect Machine.BRK, _ -> () | effect Machine.DEI (`Byte, port), k -> ( match Devices.dei m port with | Some v -> continue k v | None -> continue k (Bytes.get_uint8 dev port)) | effect Machine.DEI (`Short, port), k -> ( match Devices.dei2 m port with | Some v -> continue k v | None -> continue k (Util.get_uint16_wrap dev port)) | effect Machine.DEO (port, value), k -> if Devices.can_handle port then Devices.deo m port value; continue k () let main () = if Array.length Sys.argv < 2 then ( Printf.eprintf "usage: uxnemu file.rom ...\n"; exit 1); let code = In_channel.with_open_bin Sys.argv.(1) (fun i -> In_channel.input_all i) in In_channel.set_binary_mode stdin true; Out_channel.set_binary_mode stdout true; let mach = Machine.create code in let dev = Machine.dev mach in let has_args = Array.length Sys.argv > 2 in Bytes.set_uint8 dev 0x17 (if has_args then 1 else 0); run mach 0x100; if Console.state.console_vector <> 0 then begin let console_input ch ty = Bytes.set_uint8 dev 0x12 ch; Bytes.set_uint8 dev 0x17 ty; if Bytes.get_uint8 dev 0x0f = 0 then run mach Console.state.console_vector in if has_args then begin for i = 2 to Array.length Sys.argv - 1 do let arg = Sys.argv.(i) in String.iter (fun c -> if Bytes.get_uint8 dev 0x0f = 0 then console_input (Char.code c) 2) arg; if Bytes.get_uint8 dev 0x0f = 0 then console_input 0 (if i = Array.length Sys.argv - 1 then 4 else 3) done end; try while Bytes.get_uint8 dev 0x0f = 0 do match In_channel.input_byte stdin with | None -> raise Exit | Some c -> console_input c 1 done with Exit -> console_input 0 4 end; exit (Bytes.get_uint8 dev 0x0f land 0x7f) let _ = main ()