From 8e89711ecea5a8360e167793701f83248f283fd6 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 15:39:35 +0100 Subject: [PATCH 1/3] vm: file times keep nanoseconds; clock_gettime refuses unknown clocks File::Stat, File.mtime/atime/ctime/birthtime and the new File#mtime & co. carry the stat struct's nanoseconds in the local zone, as MRI's stat_time does; File.atime and File.ctime read st_atime/st_ctime instead of answering the modification time; File.birthtime works where the stat struct has a creation time; each singleton names its own C function in ENOENT and declares arity 1. File.utime and File.lutime write the nanoseconds too: their carrier was int64 seconds. Process.clock_gettime and clock_getres follow process.c v4.0.10: the platform's CLOCK_* constants with the host's clockid_t values (darwin and linux), the real clock_gettime(2) for every id, Errno::EINVAL naming the id for one the host does not have (it used to answer the wall clock), MRI's symbolic emulations with their resolutions, NUM2UINT/NUM2INT range errors, and "unexpected unit". floatToLong is shared with Math.ldexp. Closes go-embedded-ruby/ruby#705 Co-Authored-By: Claude Opus 5.5 --- internal/vm/file.go | 91 +++----- .../vm/file_lutime_chroot_internal_test.go | 5 +- internal/vm/file_ops_internal_test.go | 3 +- internal/vm/filestat.go | 121 +++++++--- internal/vm/filestat_plan9.go | 4 +- internal/vm/filestat_stage1_internal_test.go | 16 +- internal/vm/filestat_unix.go | 9 +- internal/vm/filestat_wasm.go | 3 +- internal/vm/filestat_windows.go | 3 +- internal/vm/math.go | 9 +- internal/vm/process.go | 72 +----- internal/vm/process_clock.go | 215 ++++++++++++++++++ internal/vm/process_clock_darwin.go | 106 +++++++++ internal/vm/process_clock_linux.go | 67 ++++++ internal/vm/process_clock_other.go | 57 +++++ internal/vm/process_clock_test.go | 215 ++++++++++++++++++ internal/vm/process_limits_internal_test.go | 6 +- internal/vm/statdetail_internal_test.go | 40 ++-- internal/vm/stdlib_puppet_batch_test.go | 3 +- 19 files changed, 858 insertions(+), 187 deletions(-) create mode 100644 internal/vm/process_clock.go create mode 100644 internal/vm/process_clock_darwin.go create mode 100644 internal/vm/process_clock_linux.go create mode 100644 internal/vm/process_clock_other.go create mode 100644 internal/vm/process_clock_test.go diff --git a/internal/vm/file.go b/internal/vm/file.go index b413e604..3aa4ff46 100644 --- a/internal/vm/file.go +++ b/internal/vm/file.go @@ -1,6 +1,7 @@ package vm import ( + "math" "os" "os/user" "path" // always '/'-separated, as Ruby's File is — not path/filepath @@ -256,17 +257,20 @@ func (vm *VM) registerFile() { } return object.IntValue(fi.Size()) }) - // File.mtime returns the file's last-modification Time (whole-second - // resolution, matching the Time class's granularity). A missing file raises - // Errno::ENOENT, as in MRI. - def("mtime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - p := pathArg(vm, args[0]) - fi, err := os.Stat(p) - if err != nil { - raise("Errno::ENOENT", "No such file or directory @ rb_file_s_stat - %s", p) - } - return unixTime(fi.ModTime().Unix()) - }) + // File.mtime / .atime / .ctime / .birthtime read the stat struct, as MRI's + // rb_file_s_mtime & co. do, with the nanoseconds and the local zone + // (statTime). atime and ctime used to answer the MODIFICATION time, on the + // belief that Go's portable stat exposes nothing else; statTimestamps has + // read the real st_atime / st_ctime off Sys() for File::Stat all along (#705). + for _, name := range []string{"mtime", "atime", "ctime", "birthtime"} { + def(name, func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + checkArgc(args, 1, name) + p := pathArg(vm, args[0]) + return statForTime(p, "rb_file_s_"+name).timeOf(name) + }) + // rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1). + cFile.smethods[name].argc = declareArgc(1) + } delete := func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { for _, a := range args { p := pathArg(vm, a) @@ -335,7 +339,7 @@ func (vm *VM) registerFile() { return object.IntValue(int64(len(paths))) }) def("utime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - at, mt := timeArgUnixOrNow(args[0]), timeArgUnixOrNow(args[1]) + at, mt := utimeArgOrNow(args[0]), utimeArgOrNow(args[1]) paths := args[2:] for _, a := range paths { p := pathArg(vm, a) @@ -353,7 +357,7 @@ func (vm *VM) registerFile() { if len(args) < 2 { raise("ArgumentError", "wrong number of arguments (given %d, expected 2+)", len(args)) } - at, mt := timeArgUnixOrNow(args[0]), timeArgUnixOrNow(args[1]) + at, mt := utimeArgOrNow(args[0]), utimeArgOrNow(args[1]) paths := args[2:] for _, a := range paths { p := pathArg(vm, a) @@ -519,31 +523,6 @@ func (vm *VM) registerFile() { return object.Bool(err1 == nil && err2 == nil && os.SameFile(fi1, fi2)) }) - // atime / ctime return the file's access / change Time (whole-second, like - // mtime — Go's portable stat exposes only ModTime, so both report it). A missing - // file raises Errno::ENOENT, as MRI does. - modTimeOf := func(vm *VM, args []object.Value) object.Value { - p := pathArg(vm, args[0]) - fi, err := os.Stat(p) - if err != nil { - raise("Errno::ENOENT", "No such file or directory @ rb_file_s_stat - %s", p) - } - return unixTime(fi.ModTime().Unix()) - } - def("atime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { return modTimeOf(vm, args) }) - def("ctime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { return modTimeOf(vm, args) }) - // birthtime: unavailable through Go's portable stat surface (and on Linux - // without statx), so — matching MRI on unsupported platforms — it raises - // Errno::ENOENT for a missing path and NotImplementedError otherwise. - def("birthtime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - p := pathArg(vm, args[0]) - if _, err := os.Stat(p); err != nil { - raise("Errno::ENOENT", "No such file or directory @ rb_file_s_birthtime - %s", p) - } - raise("NotImplementedError", "birthtime() function is unimplemented") - return object.NilV - }) - // link / symlink create a hard / symbolic link and return 0; an existing target // raises Errno::EEXIST, a missing source directory Errno::ENOENT (MRI). Both // require exactly two path arguments. @@ -683,9 +662,7 @@ func (vm *VM) num2mode(v object.Value) int64 { // File.chown as a no-op, so the Windows build returns nil. var ( fileChmod = os.Chmod - fileChtimes = func(p string, atime, mtime int64) error { - return osChtimes(p, atime, mtime) - } + fileChtimes = os.Chtimes ) // rubyBasename returns the last component of a '/'-separated path, matching Ruby's @@ -1037,13 +1014,6 @@ func expandTildePath(p string) string { // concurrently-running tests). var setUmask = osUmask -// osChtimes sets the access and modification times of path from whole-second -// Unix timestamps, via os.Chtimes. It is wrapped (rather than used directly) so -// the seam in fileChtimes takes int64 seconds, matching utime's Time arguments. -func osChtimes(p string, atime, mtime int64) error { - return os.Chtimes(p, stdtime.Unix(atime, 0), stdtime.Unix(mtime, 0)) -} - // chownID converts a File.chown id argument to the int the os layer expects: a // nil id means "leave unchanged" (-1, as POSIX chown interprets it), any other // value is coerced through intArg. @@ -1054,23 +1024,30 @@ func chownID(v object.Value) int { return clampInt(intArg(v)) } -// timeArgUnix marshals a File.utime time argument (a Time, or an Integer/Float -// seconds-since-epoch) to a whole number of Unix seconds. -func timeArgUnix(v object.Value) int64 { +// utimeArg marshals a File.utime time argument (a Time, or an Integer/Float +// seconds-since-epoch) to the instant it names, nanoseconds included, as +// rb_time_timespec does. It used to return whole seconds, so File.utime +// dropped the sub-second part MRI writes (#705). +func utimeArg(v object.Value) stdtime.Time { if t, ok := v.(*Time); ok { - return t.t.Unix() + return t.t + } + if i, ok := v.(object.Integer); ok { + return stdtime.Unix(int64(i), 0) } - return int64(numFloat(v)) + f := numFloat(v) + sec := math.Floor(f) + return stdtime.Unix(int64(sec), int64(math.Round((f-sec)*1e9))) } -// timeArgUnixOrNow is timeArgUnix with MRI's nil handling for File.utime / +// utimeArgOrNow is utimeArg with MRI's nil handling for File.utime / // File.lutime: a nil atime/mtime means "use the current time" (file.c // utime_internal leaves the timespec NULL, which utimensat reads as UTIME_NOW). -func timeArgUnixOrNow(v object.Value) int64 { +func utimeArgOrNow(v object.Value) stdtime.Time { if v == object.NilV { - return stdtime.Now().Unix() + return stdtime.Now() } - return timeArgUnix(v) + return utimeArg(v) } // registerErrnoClasses installs the Errno::Exxx hierarchy under the Errno module diff --git a/internal/vm/file_lutime_chroot_internal_test.go b/internal/vm/file_lutime_chroot_internal_test.go index 61f526dc..76f8657a 100644 --- a/internal/vm/file_lutime_chroot_internal_test.go +++ b/internal/vm/file_lutime_chroot_internal_test.go @@ -10,6 +10,7 @@ import ( "runtime" "syscall" "testing" + "time" ) // origChrootFn / origLutimesFn capture the platform seams so each test can @@ -53,7 +54,7 @@ func TestFileLutime(t *testing.T) { if got := runFS(t, `p (File.mtime("`+f+`").to_i == 1000000001)`); got != "true\n" { t.Errorf("lutime mtime: got %q want true", got) } - // nil atime/mtime means the current time (timeArgUnixOrNow nil branch). + // nil atime/mtime means the current time (utimeArgOrNow nil branch). if got := runFS(t, `File.lutime(nil, nil, "`+f+`"); p ((Time.now.to_i - File.mtime("`+f+`").to_i).abs < 5)`); got != "true\n" { t.Errorf("lutime nil: got %q want true", got) } @@ -65,7 +66,7 @@ func TestFileLutime(t *testing.T) { } // Error branch: a failing seam maps to Errno::ENOENT. - lutimesFn = func(string, int64, int64) error { return os.ErrNotExist } + lutimesFn = func(string, time.Time, time.Time) error { return os.ErrNotExist } if got := runFSErr(t, `File.lutime(0, 0, "x")`); got != "Errno::ENOENT" { t.Errorf("lutime err: got %q want Errno::ENOENT", got) } diff --git a/internal/vm/file_ops_internal_test.go b/internal/vm/file_ops_internal_test.go index 895af2c9..53f4a82d 100644 --- a/internal/vm/file_ops_internal_test.go +++ b/internal/vm/file_ops_internal_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "testing" + "time" ) // TestFileMetaOps covers File.chmod/chown/lchown/utime/umask and the access @@ -62,7 +63,7 @@ func TestFileMetaOpsErrors(t *testing.T) { defer restoreFileSeams() failMode := func(string, os.FileMode) error { return os.ErrNotExist } failOwn := func(string, int, int) error { return os.ErrNotExist } - failTimes := func(string, int64, int64) error { return os.ErrNotExist } + failTimes := func(string, time.Time, time.Time) error { return os.ErrNotExist } fileChmod = failMode fileChown = failOwn diff --git a/internal/vm/filestat.go b/internal/vm/filestat.go index 7e7c9eed..8e09eacf 100644 --- a/internal/vm/filestat.go +++ b/internal/vm/filestat.go @@ -10,6 +10,7 @@ import ( "reflect" "strconv" "strings" + stdtime "time" "github.com/go-embedded-ruby/ruby/internal/object" ) @@ -24,12 +25,16 @@ type statFields struct { rdev, blocks int64 hasSys bool // atime/ctime/btime are the stat struct's access, status-change and birth - // times in whole seconds, filled by statTimestamps rather than by the - // build-tagged statSys: the FIELDS are spelled differently per platform + // timespecs, seconds AND nanoseconds, filled by statTimestamps rather than by + // the build-tagged statSys: the FIELDS are spelled differently per platform // (Linux's Atim vs the BSDs' Atimespec) but reading them is one shared rule, // so it lives in the shared file where the POSIX lanes can cover it. // hasBtime is false where the platform has no creation time at all. - atime, ctime, btime int64 + // + // They were int64 seconds, and a carrier that cannot hold the precision + // drops it at every use: mtime.nsec read 0 where MRI reads the file's + // nanoseconds (#705). + atime, ctime, btime stdtime.Time hasBtime bool } @@ -74,7 +79,7 @@ func (s *FileStat) Inspect() string { {"blksize", strconv.FormatInt(s.sys.blksize, 10)}, {"blocks", s.blocksValue().Inspect()}, {"atime", statTime(s.sys.atime).Inspect()}, - {"mtime", statTime(s.fi.ModTime().Unix()).Inspect()}, + {"mtime", statTime(s.fi.ModTime()).Inspect()}, {"ctime", statTime(s.sys.ctime).Inspect()}, } { if b.Len() > len("#", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { other, ok := args[0].(*FileStat) @@ -555,11 +598,7 @@ func (vm *VM) registerFileStat() { // statx, and MRI raises NotImplementedError there with exactly this message, // so the absence is reported rather than faked. d("birthtime", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - s := self(v) - if !s.sys.hasBtime { - raise("NotImplementedError", "birthtime() function is unimplemented") - } - return statTime(s.sys.btime) + return self(v).timeOf("birthtime") }) // File.stat / File.lstat class methods on the File class. @@ -594,6 +633,20 @@ func (vm *VM) registerFileStat() { cFile.define("stat", statOfStream(true)) cFile.define("lstat", statOfStream(false)) + // File#mtime / #atime / #ctime / #birthtime: the open stream's own stat + // times (rb_file_mtime & co. fstat the descriptor), defined on File itself + // with arity 0. rbgo had none of the four as instance methods, so + // File.new(f).mtime was a NoMethodError. A closed stream raises IOError. + for _, name := range []string{"mtime", "atime", "ctime", "birthtime"} { + cFile.defineArgc(name, 0, func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { + o := self.(*IOObj) + if o.closed { + raise("IOError", "closed stream") + } + return statOrRaise(o.path, true).timeOf(name) + }) + } + vm.registerFileTest() // Dir includes Enumerable — deferred here because registerDir runs before the diff --git a/internal/vm/filestat_plan9.go b/internal/vm/filestat_plan9.go index ce81af17..c120d7d8 100644 --- a/internal/vm/filestat_plan9.go +++ b/internal/vm/filestat_plan9.go @@ -27,8 +27,8 @@ var chrootFn = func(string) error { return errors.ErrUnsupported } // lutimesFn sets a file's access and modification times. Plan 9 has no symbolic // links, so "without following a final link" is the same operation as // utime: os.Chtimes (a wstat of the Dir's Atime and Mtime). -var lutimesFn = func(path string, atime, mtime int64) error { - return os.Chtimes(path, time.Unix(atime, 0), time.Unix(mtime, 0)) +var lutimesFn = func(path string, atime, mtime time.Time) error { + return os.Chtimes(path, atime, mtime) } // statSys extracts the stat fields from the *syscall.Dir os.FileInfo carries; see diff --git a/internal/vm/filestat_stage1_internal_test.go b/internal/vm/filestat_stage1_internal_test.go index deb7752b..eb2878cb 100644 --- a/internal/vm/filestat_stage1_internal_test.go +++ b/internal/vm/filestat_stage1_internal_test.go @@ -222,14 +222,22 @@ func TestFileLevelPredicates(t *testing.T) { t.Errorf("src=%q got=%q want=%q", c.src, got, c.want) } } - // atime/ctime/birthtime on a missing path raise Errno::ENOENT; birthtime on an - // existing file raises NotImplementedError. + // atime/ctime/birthtime on a missing path raise Errno::ENOENT. birthtime on an + // existing file answers exactly what File::Stat#birthtime does on this host: + // a Time where the stat struct carries one (Darwin, as MRI 4.0.10 there), a + // NotImplementedError where it does not. It used to raise everywhere (#705). for _, expr := range []string{`File.atime("/no/x")`, `File.ctime("/no/x")`, `File.birthtime("/no/x")`} { if got := runFSErr(t, expr); got != "Errno::ENOENT" { t.Errorf("%s: got %q want Errno::ENOENT", expr, got) } } - if got := runFSErr(t, `File.birthtime("`+reg+`")`); got != "NotImplementedError" { - t.Errorf("File.birthtime(existing): got %q want NotImplementedError", got) + if got := runFS(t, `r = ->(&b) { b.call rescue $!.class } +p r.call { File.birthtime("`+reg+`") } == r.call { File.stat("`+reg+`").birthtime }`); got != "true\n" { + t.Errorf("File.birthtime(existing) disagrees with File::Stat#birthtime: %q", got) + } + if runtime.GOOS == "darwin" { + if got := runFS(t, `p File.birthtime("`+reg+`").class`); got != "Time\n" { + t.Errorf("File.birthtime on Darwin: got %q want Time", got) + } } } diff --git a/internal/vm/filestat_unix.go b/internal/vm/filestat_unix.go index 983d8ec2..5aab81a0 100644 --- a/internal/vm/filestat_unix.go +++ b/internal/vm/filestat_unix.go @@ -9,6 +9,7 @@ package vm import ( "io/fs" "syscall" + "time" "golang.org/x/sys/unix" ) @@ -28,11 +29,9 @@ var ( // symbolic link — utimensat(AT_FDCWD, path, ts, AT_SYMLINK_NOFOLLOW), the // no-follow that distinguishes File.lutime from File.utime (file.c // utime_internal passes follow=TRUE, which maps to AT_SYMLINK_NOFOLLOW). - lutimesFn = func(path string, atime, mtime int64) error { - ts := []unix.Timespec{ - unix.NsecToTimespec(atime * int64(1e9)), - unix.NsecToTimespec(mtime * int64(1e9)), - } + // The times keep their nanoseconds (#705): a seconds carrier truncated them. + lutimesFn = func(path string, atime, mtime time.Time) error { + ts := []unix.Timespec{unix.NsecToTimespec(atime.UnixNano()), unix.NsecToTimespec(mtime.UnixNano())} return unix.UtimesNanoAt(unix.AT_FDCWD, path, ts, unix.AT_SYMLINK_NOFOLLOW) } ) diff --git a/internal/vm/filestat_wasm.go b/internal/vm/filestat_wasm.go index 6bf8e705..0b3df352 100644 --- a/internal/vm/filestat_wasm.go +++ b/internal/vm/filestat_wasm.go @@ -10,6 +10,7 @@ import ( "errors" "io/fs" "syscall" + "time" ) // chrootFn / lutimesFn are unsupported under GOARCH=wasm: Dir.chroot and @@ -18,7 +19,7 @@ import ( // shared dir.go / file.go code references. var ( chrootFn = func(string) error { return errors.ErrUnsupported } - lutimesFn = func(string, int64, int64) error { return errors.ErrUnsupported } + lutimesFn = func(string, time.Time, time.Time) error { return errors.ErrUnsupported } ) // statSys is the GOARCH=wasm counterpart of the Unix syscall.Stat_t extraction. diff --git a/internal/vm/filestat_windows.go b/internal/vm/filestat_windows.go index b189d13b..9e48da2e 100644 --- a/internal/vm/filestat_windows.go +++ b/internal/vm/filestat_windows.go @@ -9,6 +9,7 @@ package vm import ( "errors" "io/fs" + "time" ) // chrootFn / lutimesFn are unsupported on Windows: Dir.chroot and File.lutime are @@ -17,7 +18,7 @@ import ( // operation as unsupported. var ( chrootFn = func(string) error { return errors.ErrUnsupported } - lutimesFn = func(string, int64, int64) error { return errors.ErrUnsupported } + lutimesFn = func(string, time.Time, time.Time) error { return errors.ErrUnsupported } ) // statSys is the Windows counterpart of the Unix syscall.Stat_t extraction. diff --git a/internal/vm/math.go b/internal/vm/math.go index 11616c24..be8fa2da 100644 --- a/internal/vm/math.go +++ b/internal/vm/math.go @@ -111,6 +111,13 @@ func mathBignumRange() int { // "float ... out of range of integer", while a value that fits a long but not a // C int reports "integer ... too big/small to convert to 'int'". func mathFloatToInt(f float64) int { + return mathInt32(floatToLong(f)) +} + +// floatToLong is rb_num2long's Float stage: NaN, ±Inf and anything beyond a +// machine long are "float ... out of range of integer", the rest truncates +// toward zero. +func floatToLong(f float64) int64 { if math.IsNaN(f) { raise("RangeError", "float NaN out of range of integer") } @@ -124,7 +131,7 @@ func mathFloatToInt(f float64) int { if f >= 9223372036854775808.0 || f < -9223372036854775808.0 { raise("RangeError", "float %v out of range of integer", f) } - return mathInt32(int64(math.Trunc(f))) + return int64(math.Trunc(f)) } // registerMath installs the Math module, its constants and its functions. diff --git a/internal/vm/process.go b/internal/vm/process.go index 560ed36b..5018d5f5 100644 --- a/internal/vm/process.go +++ b/internal/vm/process.go @@ -79,64 +79,18 @@ func (vm *VM) registerProcess() { return args[0] }) - def("clock_gettime", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - clk := intArg(args[0]) - var d time.Duration - switch clk { - case clockMonotonic: - d = processMonoNow().Sub(processClockEpoch) - default: // CLOCK_REALTIME and any other clock -> wall clock since the epoch - now := processMonoNow() - d = time.Duration(now.UnixNano()) - } - return clockGettimeUnit(d, args) + def("clock_gettime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + return vm.clockGettime(args) }) - - mod.consts["CLOCK_REALTIME"] = object.IntValue(clockRealtime) - vm.consts["Process::CLOCK_REALTIME"] = object.IntValue(clockRealtime) - mod.consts["CLOCK_MONOTONIC"] = object.IntValue(clockMonotonic) - vm.consts["Process::CLOCK_MONOTONIC"] = object.IntValue(clockMonotonic) + vm.defineClockConsts(mod) vm.defineProcessExit(def) // unconditional: Init_process declares these on every platform vm.registerProcessPosix(mod, def) vm.registerProcessResiduals(mod, def) } -// Clock identifiers match the Linux/macOS values MRI exposes (CLOCK_REALTIME=0, -// CLOCK_MONOTONIC=6 on Darwin); only the relative ordering matters to callers, -// who pass the constant straight back. -const ( - clockRealtime = 0 - clockMonotonic = 6 - processMaxGroups = 16 -) - -// clockGettimeUnit converts a duration to the requested unit symbol (default -// :float_second), matching Process.clock_gettime's unit argument. -func clockGettimeUnit(d time.Duration, args []object.Value) object.Value { - unit := "float_second" - if len(args) > 1 { - if s, ok := args[1].(object.Symbol); ok { - unit = string(s) - } - } - switch unit { - case "nanosecond": - return object.IntValue(d.Nanoseconds()) - case "microsecond": - return object.IntValue(d.Microseconds()) - case "millisecond": - return object.IntValue(d.Milliseconds()) - case "second": - return object.IntValue(int64(d.Seconds())) - case "float_microsecond": - return object.Float(float64(d.Nanoseconds()) / 1e3) - case "float_millisecond": - return object.Float(float64(d.Nanoseconds()) / 1e6) - default: // float_second - return object.Float(d.Seconds()) - } -} +// The clock ids are per platform (process_clock_.go). +const processMaxGroups = 16 // Identity seams over the os package so tests can drive every branch without // depending on the host's actual uid/gid/groups. @@ -615,18 +569,10 @@ func (vm *VM) registerProcessResiduals(mod *RClass, def func(string, NativeFn)) vm.registerProcessIdentityModules(mod) vm.registerProcessTms(mod, def) - // clock_getres(clock, unit = :float_second). The three documented symbolic - // clocks have fixed resolutions; the numeric clocks report the 1µs this - // host's clock_getres(2) does, which is what MRI answers on Linux and Darwin. - def("clock_getres", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - if len(args) == 0 { - raise("ArgumentError", "wrong number of arguments (given 0, expected 1..2)") - } - res := time.Microsecond - if sym, ok := args[0].(object.Symbol); ok && string(sym) == "TIME_BASED_CLOCK_REALTIME" { - res = time.Second - } - return clockGettimeUnit(res, args) + // clock_getres(clock, unit = :float_second): rb_clock_getres, in + // process_clock.go with clock_gettime. + def("clock_getres", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + return vm.clockGetres(args) }) // argv0 is the name the main script was given, frozen, and the SAME object on diff --git a/internal/vm/process_clock.go b/internal/vm/process_clock.go new file mode 100644 index 00000000..354fc539 --- /dev/null +++ b/internal/vm/process_clock.go @@ -0,0 +1,215 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "math" + "time" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// Process.clock_gettime and Process.clock_getres, after process.c v4.0.10: +// rb_clock_gettime, rb_clock_getres, make_clock_result and clock_failed (#705). +// +// A clock is either a Symbol naming one of MRI's documented emulations, or a +// number converted with NUM2CLOCKID and handed to the host's clock_gettime(2). +// Before #705 every number that was not CLOCK_MONOTONIC answered the WALL clock, +// so a program asking for a clock rbgo did not have got a plausible wrong value +// instead of MRI's Errno::EINVAL; and the four CPU/raw clock constants were +// missing. The platform half (which constants exist, the syscall, the +// resolutions) lives in process_clock_.go. + +// clockTick is one times(3) tick: 1/CLK_TCK, and CLK_TCK is 100 on Linux and +// Darwin. MRI's TIMES_BASED clocks count in it and report it as their +// resolution (measured on MRI 4.0.10 darwin: 10000000 ns). +const clockTick = 10 * time.Millisecond + +// clockRealtimeNow and clockMonotonicNow read the two clocks Time.now and +// Benchmark rely on through the processMonoNow seam, so tests stay +// deterministic. CLOCK_MONOTONIC counts from the first reading in this process +// rather than from boot: only differences between readings are meaningful, the +// same contract MRI documents. +func clockRealtimeNow() time.Duration { return time.Duration(processMonoNow().UnixNano()) } +func clockMonotonicNow() time.Duration { return processMonoNow().Sub(processClockEpoch) } + +// clockProcessCPU is the process's user + system CPU time, getrusage(RUSAGE_SELF) +// at microsecond precision — the source of every *_CLOCK_PROCESS_CPUTIME_ID +// emulation. +func clockProcessCPU() time.Duration { + u, s := procRusage() + return time.Duration(math.Round((u+s)*1e6)) * time.Microsecond +} + +// symClock is one of MRI's symbolic clocks: how to read it and the resolution +// rb_clock_getres reports for it. +type symClock struct { + read func() time.Duration + res time.Duration +} + +// symbolicClock resolves a Symbol clock id the way rb_clock_gettime's chain of +// `if (clk_id == RUBY_..._CLOCK_...)` does, each emulation present only where +// its #ifdef guard holds on the platform rbgo was built for. +func symbolicClock(name string) (symClock, bool) { + switch name { + case "GETTIMEOFDAY_BASED_CLOCK_REALTIME": // #ifdef HAVE_GETTIMEOFDAY: everywhere + return symClock{func() time.Duration { return clockRealtimeNow().Truncate(time.Microsecond) }, time.Microsecond}, true + case "TIME_BASED_CLOCK_REALTIME": // no guard + return symClock{func() time.Duration { return clockRealtimeNow().Truncate(time.Second) }, time.Second}, true + case "CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID": // no guard; clock() / CLOCKS_PER_SEC + return symClock{func() time.Duration { return clockProcessCPU().Truncate(clockClocksPerSecRes) }, clockClocksPerSecRes}, true + } + if clockHasPosixEmulations { + switch name { + case "TIMES_BASED_CLOCK_MONOTONIC": // #ifdef HAVE_TIMES + return symClock{func() time.Duration { return clockMonotonicNow().Truncate(clockTick) }, clockTick}, true + case "GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID": // #ifdef RUSAGE_SELF + return symClock{clockProcessCPU, time.Microsecond}, true + case "TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID": // #ifdef HAVE_TIMES + return symClock{func() time.Duration { return clockProcessCPU().Truncate(clockTick) }, clockTick}, true + } + } + return platformSymbolicClock(name) // MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC, #ifdef __APPLE__ +} + +// clockFailed is process.c clock_failed: Errno::EINVAL whose message names the +// call and the clock id as #inspect renders it — `clock_gettime(:foo)`, +// `clock_gettime(1.5)` — so the id the program passed is the one it reads back. +func (vm *VM) clockFailed(name string, clk object.Value) { + raise("Errno::EINVAL", "Invalid argument - clock_%s(%s)", name, vm.inspectStr(clk)) +} + +// clockIDArg is NUM2CLOCKID: an Integer passes, a Float is truncated (so 1.5 is +// clock 1, and its EINVAL still names 1.5) after rb_num2long's range check, a +// Bignum is a RangeError naming the C type clockid_t converts through, and +// anything else must answer #to_int with an Integer (rb_to_int). The result is +// then narrowed to clockid_t by clockIDNarrow, which raises the platform's +// "too big / too small to convert" RangeError — MRI 4.0.10 darwin: +// clock_gettime(2**40) is "integer 1099511627776 too big to convert to +// 'unsigned int'", never EINVAL. +func (vm *VM) clockIDArg(v object.Value) int64 { + switch n := v.(type) { + case object.Integer: + return clockIDNarrow(int64(n)) + case object.Float: + return clockIDNarrow(floatToLong(float64(n))) + case *object.Bignum: + raise("RangeError", "bignum too big to convert into '%s'", clockIDCType) + } + if object.IsNil(v) || !vm.respondsToDynamic(v, "to_int") { + raise("TypeError", "no implicit conversion of %s into Integer", classNameOf(v)) + } + r := vm.send(v, "to_int", nil, nil) + switch r.(type) { + case object.Integer, *object.Bignum: + return vm.clockIDArg(r) + } + raise("TypeError", "can't convert %s to Integer (%s#to_int gives %s)", classNameOf(v), classNameOf(v), classNameOf(r)) + return 0 +} + +// clockArgs checks rb_check_arity(argc, 1, 2) and splits off the unit. +func clockArgs(args []object.Value) (clk, unit object.Value) { + if len(args) < 1 || len(args) > 2 { + raise("ArgumentError", "%s", argcMessage(len(args), 1, 2)) + } + if len(args) == 2 { + unit = args[1] + } + return args[0], unit +} + +// clockGettime is rb_clock_gettime. +func (vm *VM) clockGettime(args []object.Value) object.Value { + clk, unit := clockArgs(args) + if sym, ok := clk.(object.Symbol); ok { + c, found := symbolicClock(string(sym)) + if !found { + vm.clockFailed("gettime", clk) + } + return vm.clockResult(c.read(), unit, false) + } + switch id := vm.clockIDArg(clk); id { + case clockRealtime: + return vm.clockResult(clockRealtimeNow(), unit, false) + case clockMonotonic: + return vm.clockResult(clockMonotonicNow(), unit, false) + default: + d, err := platformClockGettime(id) + if err != nil { + vm.clockFailed("gettime", clk) + } + return vm.clockResult(d, unit, false) + } +} + +// clockGetres is rb_clock_getres; it also accepts :hertz, the reciprocal. +func (vm *VM) clockGetres(args []object.Value) object.Value { + clk, unit := clockArgs(args) + if sym, ok := clk.(object.Symbol); ok { + c, found := symbolicClock(string(sym)) + if !found { + vm.clockFailed("getres", clk) + } + return vm.clockResult(c.res, unit, true) + } + d, err := platformClockGetres(vm.clockIDArg(clk)) + if err != nil { + vm.clockFailed("getres", clk) + } + return vm.clockResult(d, unit, true) +} + +// clockResult is make_clock_result: nil or :float_second by default, the other +// named units, and ArgumentError "unexpected unit: " for anything +// else. :hertz is a clock_getres unit only. +func (vm *VM) clockResult(d time.Duration, unit object.Value, getres bool) object.Value { + name := "float_second" + if !object.IsNil(unit) { + sym, ok := unit.(object.Symbol) + if !ok { + raise("ArgumentError", "unexpected unit: %s", vm.objAsString(unit)) + } + name = string(sym) + } + switch name { + case "float_second": + return object.Float(d.Seconds()) + case "float_millisecond": + return object.Float(float64(d.Nanoseconds()) / 1e6) + case "float_microsecond": + return object.Float(float64(d.Nanoseconds()) / 1e3) + case "second": + return object.IntValue(int64(d / time.Second)) + case "millisecond": + return object.IntValue(int64(d / time.Millisecond)) + case "microsecond": + return object.IntValue(int64(d / time.Microsecond)) + case "nanosecond": + return object.IntValue(d.Nanoseconds()) + case "hertz": + if getres { + return object.Float(1e9 / float64(d.Nanoseconds())) + } + } + raise("ArgumentError", "unexpected unit: %s", name) + return nil +} + +// defineClockConsts installs the CLOCK_* constants this platform has, in MRI's +// InitVM_process order, each with the host's own clockid_t value. +func (vm *VM) defineClockConsts(mod *RClass) { + for _, c := range platformClockConsts { + mod.consts[c.name] = object.IntValue(c.id) + vm.consts["Process::"+c.name] = object.IntValue(c.id) + } +} + +// clockConst is one Process::CLOCK_* constant. +type clockConst struct { + name string + id int64 +} diff --git a/internal/vm/process_clock_darwin.go b/internal/vm/process_clock_darwin.go new file mode 100644 index 00000000..d7871bb3 --- /dev/null +++ b/internal/vm/process_clock_darwin.go @@ -0,0 +1,106 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build darwin + +package vm + +import ( + "math" + "runtime" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// The clock ids defines on Darwin, in InitVM_process order. Measured +// on MRI 4.0.10 arm64-darwin: REALTIME 0, MONOTONIC 6, PROCESS_CPUTIME_ID 12, +// THREAD_CPUTIME_ID 16, MONOTONIC_RAW 4, MONOTONIC_RAW_APPROX 5, UPTIME_RAW 8, +// UPTIME_RAW_APPROX 9; CLOCK_UPTIME is not defined. +const ( + clockRealtime = unix.CLOCK_REALTIME + clockMonotonic = unix.CLOCK_MONOTONIC +) + +var platformClockConsts = []clockConst{ + {"CLOCK_REALTIME", unix.CLOCK_REALTIME}, + {"CLOCK_MONOTONIC", unix.CLOCK_MONOTONIC}, + {"CLOCK_PROCESS_CPUTIME_ID", unix.CLOCK_PROCESS_CPUTIME_ID}, + {"CLOCK_THREAD_CPUTIME_ID", unix.CLOCK_THREAD_CPUTIME_ID}, + {"CLOCK_MONOTONIC_RAW", unix.CLOCK_MONOTONIC_RAW}, + {"CLOCK_MONOTONIC_RAW_APPROX", unix.CLOCK_MONOTONIC_RAW_APPROX}, + {"CLOCK_UPTIME_RAW", unix.CLOCK_UPTIME_RAW}, + {"CLOCK_UPTIME_RAW_APPROX", unix.CLOCK_UPTIME_RAW_APPROX}, +} + +// clockid_t is an enum on Darwin and NUM2CLOCKID converts through unsigned +// long: MRI 4.0.10 says "bignum too big to convert into 'unsigned long'". +const clockIDCType = "unsigned long" + +// clock() counts in CLOCKS_PER_SEC = 1000000 on Darwin. +const clockClocksPerSecRes = time.Microsecond + +const clockHasPosixEmulations = true + +// clockMachRes is mach_timebase_info's numer/denom in whole nanoseconds, MRI's +// resolution for MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC: Apple silicon ticks at +// 24 MHz (125/3 → 41, measured on MRI 4.0.10), Intel at 1/1. +// clockMachResCeil is the same ratio rounded UP, which is what libc's +// clock_getres reports for the mach-backed clocks (42 ns measured). +var clockMachRes, clockMachResCeil = func() (time.Duration, time.Duration) { + if runtime.GOARCH == "arm64" { + return 41, 42 + } + return 1, 1 +}() + +// clockIDNarrow is NUM2UINT, which is how MRI 4.0.10 darwin converts a +// clockid_t (measured): a value past UINT_MAX is "too big", one below INT_MIN +// "too small", and a negative one inside int wraps — so -1 reaches libc, which +// answers EINVAL. +func clockIDNarrow(x int64) int64 { + if x > math.MaxUint32 { + raise("RangeError", "integer %d too big to convert to 'unsigned int'", x) + } + if x < math.MinInt32 { + raise("RangeError", "integer %d too small to convert to 'unsigned int'", x) + } + return x +} + +// platformSymbolicClock adds Darwin's own emulation, a mach_absolute_time +// reading; it is the monotonic clock rbgo reads everywhere. +func platformSymbolicClock(name string) (symClock, bool) { + if name == "MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC" { + return symClock{clockMonotonicNow, clockMachRes}, true + } + return symClock{}, false +} + +// platformClockGettime is clock_gettime(2) through libc; the int32 conversion +// is the C one (4294967295 is the same bits as -1), and libc answers EINVAL for +// an id it does not know. +func platformClockGettime(id int64) (time.Duration, error) { + var ts unix.Timespec + if err := unix.ClockGettime(int32(id), &ts); err != nil { + return 0, err + } + return time.Duration(ts.Nano()), nil +} + +// platformClockGetres answers what Darwin's clock_getres(3) does, which x/sys +// does not wrap: 1 µs for the gettimeofday-backed clocks, and the mach +// timebase rounded up (42 ns on Apple silicon) for the raw, uptime and thread +// clocks. Measured on MRI 4.0.10 arm64-darwin for every id below. +func platformClockGetres(id int64) (time.Duration, error) { + switch id { + case unix.CLOCK_REALTIME, unix.CLOCK_MONOTONIC, unix.CLOCK_PROCESS_CPUTIME_ID: + return time.Microsecond, nil + case unix.CLOCK_MONOTONIC_RAW, unix.CLOCK_MONOTONIC_RAW_APPROX, + unix.CLOCK_UPTIME_RAW, unix.CLOCK_UPTIME_RAW_APPROX, unix.CLOCK_THREAD_CPUTIME_ID: + return clockMachResCeil, nil + } + return 0, syscall.EINVAL +} diff --git a/internal/vm/process_clock_linux.go b/internal/vm/process_clock_linux.go new file mode 100644 index 00000000..3d867ed4 --- /dev/null +++ b/internal/vm/process_clock_linux.go @@ -0,0 +1,67 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux + +package vm + +import ( + "time" + + "golang.org/x/sys/unix" +) + +// The clock ids glibc's defines, in InitVM_process order, each behind +// the same `#ifdef CLOCK_X` MRI uses; the FreeBSD-only (VIRTUAL, PROF, *_FAST, +// *_PRECISE, SECOND, UPTIME) and Darwin-only (*_RAW_APPROX, UPTIME_RAW) ids are +// absent on Linux, so they are absent here too. +const ( + clockRealtime = unix.CLOCK_REALTIME + clockMonotonic = unix.CLOCK_MONOTONIC +) + +var platformClockConsts = []clockConst{ + {"CLOCK_REALTIME", unix.CLOCK_REALTIME}, + {"CLOCK_MONOTONIC", unix.CLOCK_MONOTONIC}, + {"CLOCK_PROCESS_CPUTIME_ID", unix.CLOCK_PROCESS_CPUTIME_ID}, + {"CLOCK_THREAD_CPUTIME_ID", unix.CLOCK_THREAD_CPUTIME_ID}, + {"CLOCK_REALTIME_COARSE", unix.CLOCK_REALTIME_COARSE}, + {"CLOCK_REALTIME_ALARM", unix.CLOCK_REALTIME_ALARM}, + {"CLOCK_MONOTONIC_RAW", unix.CLOCK_MONOTONIC_RAW}, + {"CLOCK_MONOTONIC_COARSE", unix.CLOCK_MONOTONIC_COARSE}, + {"CLOCK_BOOTTIME", unix.CLOCK_BOOTTIME}, + {"CLOCK_BOOTTIME_ALARM", unix.CLOCK_BOOTTIME_ALARM}, + {"CLOCK_TAI", unix.CLOCK_TAI}, +} + +// clockid_t is int on Linux, so NUM2CLOCKID is NUM2INT: a Bignum fails in +// rb_num2long ("into 'long'") and a Fixnum past int in rb_num2int. +const clockIDCType = "long" + +// clock() counts in CLOCKS_PER_SEC = 1000000 (POSIX XSI). +const clockClocksPerSecRes = time.Microsecond + +const clockHasPosixEmulations = true + +// clockIDNarrow is NUM2INT: rb_num2int's range check, before the syscall. +func clockIDNarrow(x int64) int64 { return int64(mathInt32(x)) } + +// No mach_absolute_time off Apple. +func platformSymbolicClock(string) (symClock, bool) { return symClock{}, false } + +func platformClockGettime(id int64) (time.Duration, error) { + var ts unix.Timespec + if err := unix.ClockGettime(int32(id), &ts); err != nil { + return 0, err + } + return time.Duration(ts.Nano()), nil +} + +func platformClockGetres(id int64) (time.Duration, error) { + var ts unix.Timespec + if err := unix.ClockGetres(int32(id), &ts); err != nil { + return 0, err + } + return time.Duration(ts.Nano()), nil +} diff --git a/internal/vm/process_clock_other.go b/internal/vm/process_clock_other.go new file mode 100644 index 00000000..693a7738 --- /dev/null +++ b/internal/vm/process_clock_other.go @@ -0,0 +1,57 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !darwin && !linux + +package vm + +import ( + "runtime" + "syscall" + "time" +) + +// Everywhere else rbgo keeps the two clocks it has always had, read through +// Go's time package, under the ids it has always used; any other number is +// EINVAL, never the wall clock. The BSDs, Solaris and Windows each have their own +// clockid_t table in MRI (FreeBSD: MONOTONIC 4, PROCESS_CPUTIME_ID 15, …; +// Windows: emulated 0..3) — not wired here because there is no MRI on those +// hosts to measure them against. +const ( + clockRealtime = 0 + clockMonotonic = 6 +) + +var platformClockConsts = []clockConst{ + {"CLOCK_REALTIME", clockRealtime}, + {"CLOCK_MONOTONIC", clockMonotonic}, +} + +const clockIDCType = "long" + +// clock() counts in CLOCKS_PER_SEC: 1000 on Windows, 1000000 on POSIX. +var clockClocksPerSecRes = func() time.Duration { + if runtime.GOOS == "windows" { + return time.Millisecond + } + return time.Microsecond +}() + +// times(3) and getrusage(2) exist on the POSIX hosts, not on Windows, Plan 9 +// or WebAssembly. +var clockHasPosixEmulations = runtime.GOOS != "windows" && runtime.GOOS != "plan9" && runtime.GOARCH != "wasm" + +// clockIDNarrow keeps the whole long: no clockid_t is consulted here. +func clockIDNarrow(x int64) int64 { return x } + +func platformSymbolicClock(string) (symClock, bool) { return symClock{}, false } + +func platformClockGettime(int64) (time.Duration, error) { return 0, syscall.EINVAL } + +func platformClockGetres(id int64) (time.Duration, error) { + if id == clockRealtime || id == clockMonotonic { + return time.Microsecond, nil + } + return 0, syscall.EINVAL +} diff --git a/internal/vm/process_clock_test.go b/internal/vm/process_clock_test.go new file mode 100644 index 00000000..7188db89 --- /dev/null +++ b/internal/vm/process_clock_test.go @@ -0,0 +1,215 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// TestProcessClockRefusesUnknownClocks pins the #705 defect: an unknown clock id +// used to answer the WALL clock. MRI 4.0.10 raises Errno::EINVAL naming the id as +// #inspect renders it, for clock_gettime and clock_getres alike. +func TestProcessClockRefusesUnknownClocks(t *testing.T) { + for _, tc := range []struct{ src, class, msg string }{ + {`Process.clock_gettime(999)`, "Errno::EINVAL", "Invalid argument - clock_gettime(999)"}, + {`Process.clock_getres(999)`, "Errno::EINVAL", "Invalid argument - clock_getres(999)"}, + {`Process.clock_gettime(:foo)`, "Errno::EINVAL", "Invalid argument - clock_gettime(:foo)"}, + {`Process.clock_getres(:foo)`, "Errno::EINVAL", "Invalid argument - clock_getres(:foo)"}, + {`Process.clock_gettime("x")`, "TypeError", "no implicit conversion of String into Integer"}, + {`Process.clock_gettime(nil)`, "TypeError", "no implicit conversion of nil into Integer"}, + {`Process.clock_gettime(2**70)`, "RangeError", "bignum too big to convert into '" + clockIDCType + "'"}, + {`Process.clock_gettime(Process::CLOCK_REALTIME, :foo)`, "ArgumentError", "unexpected unit: foo"}, + {`Process.clock_gettime(Process::CLOCK_REALTIME, "foo")`, "ArgumentError", "unexpected unit: foo"}, + {`Process.clock_gettime(Process::CLOCK_REALTIME, :hertz)`, "ArgumentError", "unexpected unit: hertz"}, + // rb_num2long's Float stage and rb_to_int, as MRI 4.0.10 words them. + {`Process.clock_gettime(Float::NAN)`, "RangeError", "float NaN out of range of integer"}, + {`Process.clock_gettime(1e30)`, "RangeError", "float 1e+30 out of range of integer"}, + {`Process.clock_gettime(-Float::INFINITY)`, "RangeError", "float -Inf out of range of integer"}, + {"o = Object.new; def o.to_int = \"x\"; Process.clock_gettime(o)", "TypeError", "can't convert Object to Integer (Object#to_int gives String)"}, + {`Process.clock_gettime`, "ArgumentError", "wrong number of arguments (given 0, expected 1..2)"}, + {`Process.clock_gettime(0, :second, 1)`, "ArgumentError", "wrong number of arguments (given 3, expected 1..2)"}, + } { + class, msg := evalErr(t, tc.src) + if class != tc.class || msg != tc.msg { + t.Errorf("%s: got %s/%q want %s/%q", tc.src, class, msg, tc.class, tc.msg) + } + } + // An object answering #to_int with an Integer names that clock. + if got := eval(t, `o = Object.new; def o.to_int = Process::CLOCK_REALTIME; p Process.clock_gettime(o).class`); got != "Float\n" { + t.Errorf("#to_int clock: got %q", got) + } + // clockid_t's own C type bounds the id before the syscall: unsigned int on + // Darwin (NUM2UINT, measured on MRI 4.0.10), int on Linux (NUM2INT). + ctype := map[string]string{"darwin": "unsigned int", "linux": "int"}[runtime.GOOS] + if ctype == "" { + return + } + for _, tc := range []struct{ src, msg string }{ + {`Process.clock_gettime(2**40)`, "integer 1099511627776 too big to convert to '" + ctype + "'"}, + {`Process.clock_getres(-2**40)`, "integer -1099511627776 too small to convert to '" + ctype + "'"}, + } { + if class, msg := evalErr(t, tc.src); class != "RangeError" || msg != tc.msg { + t.Errorf("%s: got %s/%q want RangeError/%q", tc.src, class, msg, tc.msg) + } + } +} + +// TestProcessClockSymbolic covers MRI's documented emulations: each one reads, +// and clock_getres answers the resolution rb_clock_getres gives it. +func TestProcessClockSymbolic(t *testing.T) { + cases := []struct{ sym, res string }{ + {"GETTIMEOFDAY_BASED_CLOCK_REALTIME", "1000"}, + {"TIME_BASED_CLOCK_REALTIME", "1000000000"}, + {"CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID", map[bool]string{true: "1000000", false: "1000"}[runtime.GOOS == "windows"]}, + } + if clockHasPosixEmulations { + cases = append(cases, + struct{ sym, res string }{"GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID", "1000"}, + struct{ sym, res string }{"TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID", "10000000"}, + struct{ sym, res string }{"TIMES_BASED_CLOCK_MONOTONIC", "10000000"}) + } + for _, c := range cases { + got := eval(t, `v = Process.clock_gettime(:`+c.sym+`) +p [v.class, v >= 0, Process.clock_getres(:`+c.sym+`, :nanosecond)]`) + if want := "[Float, true, " + c.res + "]\n"; got != want { + t.Errorf("%s: got %q want %q", c.sym, got, want) + } + } + // TIME_BASED is whole seconds; GETTIMEOFDAY_BASED whole microseconds. + if got := eval(t, `p Process.clock_gettime(:TIME_BASED_CLOCK_REALTIME, :nanosecond) % 1_000_000_000`); got != "0\n" { + t.Errorf("TIME_BASED_CLOCK_REALTIME carries a fraction: %q", got) + } + if got := eval(t, `p Process.clock_gettime(:GETTIMEOFDAY_BASED_CLOCK_REALTIME, :nanosecond) % 1000`); got != "0\n" { + t.Errorf("GETTIMEOFDAY_BASED_CLOCK_REALTIME carries nanoseconds: %q", got) + } + // :hertz is the reciprocal, and only clock_getres takes it. + if got := eval(t, `p Process.clock_getres(:TIME_BASED_CLOCK_REALTIME, :hertz)`); got != "1.0\n" { + t.Errorf(":hertz: got %q", got) + } + if got := eval(t, `p Process.clock_getres(:GETTIMEOFDAY_BASED_CLOCK_REALTIME, :microsecond)`); got != "1\n" { + t.Errorf(":microsecond: got %q", got) + } + if got := eval(t, `p Process.clock_getres(:TIME_BASED_CLOCK_REALTIME, :millisecond)`); got != "1000\n" { + t.Errorf(":millisecond: got %q", got) + } + if got := eval(t, `p Process.clock_getres(:TIME_BASED_CLOCK_REALTIME, :second)`); got != "1\n" { + t.Errorf(":second: got %q", got) + } +} + +// TestProcessClockCPU: the CPU clocks exist and advance while the process +// computes — the constants were missing before #705. +func TestProcessClockCPU(t *testing.T) { + if runtime.GOOS != "darwin" && runtime.GOOS != "linux" { + t.Skip("CLOCK_PROCESS_CPUTIME_ID is wired on Darwin and Linux only") + } + got := eval(t, ` +c = Process::CLOCK_PROCESS_CPUTIME_ID +t0 = Process.clock_gettime(c) +x = 0 +x += 1 until Process.clock_gettime(c) > t0 +p [Process::CLOCK_THREAD_CPUTIME_ID.class, Process::CLOCK_MONOTONIC_RAW.class, + Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID).class, + Process.clock_gettime(Process::CLOCK_MONOTONIC_RAW, :nanosecond).class]`) + if got != "[Integer, Integer, Float, Integer]\n" { + t.Errorf("got %q", got) + } +} + +// TestProcessClockDarwin pins the ids and resolutions measured on MRI 4.0.10 +// arm64-darwin, and a Float id truncated to a clock Darwin does not have (1) +// while its error still names 1.5. +func TestProcessClockDarwin(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("Darwin's own clockid_t values") + } + got := eval(t, `p %i[CLOCK_REALTIME CLOCK_MONOTONIC CLOCK_PROCESS_CPUTIME_ID CLOCK_THREAD_CPUTIME_ID + CLOCK_MONOTONIC_RAW CLOCK_UPTIME_RAW CLOCK_MONOTONIC_RAW_APPROX CLOCK_UPTIME_RAW_APPROX].map { Process.const_get(_1) } +p Process.const_defined?(:CLOCK_UPTIME) +p [0, 6, 12].map { Process.clock_getres(_1, :nanosecond) } +p Process.clock_gettime(:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC).class`) + want := "[0, 6, 12, 16, 4, 8, 5, 9]\nfalse\n[1000, 1000, 1000]\nFloat\n" + if got != want { + t.Errorf("got %q want %q", got, want) + } + if runtime.GOARCH == "arm64" { + if got := eval(t, `p [4, 5, 8, 9, 16].map { Process.clock_getres(_1, :nanosecond) }, Process.clock_getres(:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC, :nanosecond)`); got != "[42, 42, 42, 42, 42]\n41\n" { + t.Errorf("mach resolutions: got %q", got) + } + } + for _, tc := range []struct{ src, msg string }{ + {`Process.clock_gettime(1.5)`, "Invalid argument - clock_gettime(1.5)"}, + {`Process.clock_gettime(-1)`, "Invalid argument - clock_gettime(-1)"}, + {`Process.clock_getres(-1)`, "Invalid argument - clock_getres(-1)"}, + } { + if class, msg := evalErr(t, tc.src); class != "Errno::EINVAL" || msg != tc.msg { + t.Errorf("%s: got %s/%q", tc.src, class, msg) + } + } +} + +// TestFileTimesFromStat covers the File half of #705: File.atime/.ctime read the +// stat struct (they answered mtime), every stamp keeps its nanoseconds and the +// local zone, File#mtime & co. exist with arity 0, and the singleton methods +// declare arity 1 and name their own C function in ENOENT. All witnessed on MRI +// 4.0.10. +func TestFileTimesFromStat(t *testing.T) { + dir := t.TempDir() + f := filepath.Join(dir, "f") + if err := os.WriteFile(f, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + at, mt := time.Unix(1_000_000_000, 123_456_789), time.Unix(1_100_000_000, 987_654_321) + if err := os.Chtimes(f, at, mt); err != nil { + t.Fatal(err) + } + got := runFS(t, ` +f = `+rq(f)+` +p [File.atime(f).nsec, File.mtime(f).nsec, File.atime(f).to_i, File.mtime(f).to_i] +p [File.mtime(f).utc?, File.stat(f).mtime.utc?, File.mtime(f).utc_offset == Time.at(0).utc_offset] +p [File.ctime(f) == File.stat(f).ctime, File.atime(f) == File.stat(f).atime] +io = File.new(f) +p [io.mtime == File.mtime(f), io.atime == File.atime(f), io.ctime == File.ctime(f)] +io.close +begin; io.mtime; rescue IOError => e; p e.message; end +p [File.method(:mtime).arity, File.method(:atime).arity, File.instance_method(:ctime).arity, File.instance_method(:mtime).owner] +%i[mtime atime ctime].each { |m| begin; File.send(m, f + "-none"); rescue Errno::ENOENT => e; p e.message.sub(f, "F"); end } +begin; File.mtime; rescue ArgumentError => e; p e.message; end +`) + want := "[123456789, 987654321, 1000000000, 1100000000]\n" + + "[false, false, true]\n" + + "[true, true]\n" + + "[true, true, true]\n" + + "\"closed stream\"\n" + + "[1, 1, 0, File]\n" + + "\"No such file or directory @ rb_file_s_mtime - F-none\"\n" + + "\"No such file or directory @ rb_file_s_atime - F-none\"\n" + + "\"No such file or directory @ rb_file_s_ctime - F-none\"\n" + + "\"wrong number of arguments (given 0, expected 1)\"\n" + if runtime.GOOS == "windows" { + t.Skip("atime is read from a Filetime on Windows; see TestFileStatAtimeIsNotMtime") + } + if got != want { + t.Errorf("got\n%s\nwant\n%s", got, want) + } + // File.utime and File.lutime WRITE the nanoseconds too: their carrier was + // whole seconds, so a stamp set from Ruby read back with nsec 0. + got = runFS(t, `f = `+rq(f)+` +File.utime(Time.at(1_000_000_000, 5, :nsec), Time.at(1_000_000_001, 7, :nsec), f) +p [File.atime(f).nsec, File.mtime(f).nsec] +File.utime(1.5, 2.25, f) +p [File.atime(f).to_r, File.mtime(f).to_r] +File.utime(3, 4, f) +p [File.atime(f).to_r, File.mtime(f).to_r] +File.lutime(Time.at(9, 11, :nsec), Time.at(10, 13, :nsec), f) +p [File.atime(f).nsec, File.mtime(f).nsec]`) + if want := "[5, 7]\n[(3/2), (9/4)]\n[(3/1), (4/1)]\n[11, 13]\n"; got != want { + t.Errorf("utime nanoseconds: got %q want %q", got, want) + } +} diff --git a/internal/vm/process_limits_internal_test.go b/internal/vm/process_limits_internal_test.go index e7619ae1..3108a577 100644 --- a/internal/vm/process_limits_internal_test.go +++ b/internal/vm/process_limits_internal_test.go @@ -392,11 +392,13 @@ p Process.times.utime > u`, "true\n"}, {`p Process.clock_getres(:GETTIMEOFDAY_BASED_CLOCK_REALTIME, :nanosecond)`, "1000\n"}, {`p Process.clock_getres(:TIME_BASED_CLOCK_REALTIME, :nanosecond)`, "1000000000\n"}, {`p Process.clock_getres(:GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID, :nanosecond)`, "1000\n"}, - {`p Process.clock_getres(Process::CLOCK_REALTIME, :nanosecond)`, "1000\n"}, + // The numeric clocks answer the host's clock_getres: 1000 ns on Darwin, + // 1 ns on Linux (#705), so only the bounds are portable. + {`p Process.clock_getres(Process::CLOCK_REALTIME, :nanosecond).between?(1, 1000)`, "true\n"}, // 1e-06 second, the same value and now the same spelling as MRI: the // Float#inspect divergence this case used to document (1e-06 here, // 1.0e-06 in MRI) is fixed in internal/object. - {`p Process.clock_getres(Process::CLOCK_MONOTONIC)`, "1.0e-06\n"}, + {`p Process.clock_getres(:GETTIMEOFDAY_BASED_CLOCK_REALTIME)`, "1.0e-06\n"}, // argv0 is frozen and is the same object every time. {`p [Process.argv0.is_a?(String), Process.argv0.frozen?, Process.argv0.equal?(Process.argv0)]`, "[true, true, true]\n"}, diff --git a/internal/vm/statdetail_internal_test.go b/internal/vm/statdetail_internal_test.go index 2e399c91..63c5f376 100644 --- a/internal/vm/statdetail_internal_test.go +++ b/internal/vm/statdetail_internal_test.go @@ -31,24 +31,38 @@ type fakeStat struct { // spelling, the BSD spelling, a name the struct does not carry, a name whose // field is not a struct, a non-struct argument, a nil pointer and a nil value. func TestStatTimeField(t *testing.T) { - st := &fakeStat{Atim: fakeTimespec{Sec: 11}, Ctimespec: fakeTimespec{Sec: 22}, Birthtimespec: fakeTimespec{Sec: 33}} + // The nanoseconds are carried too: a seconds-only carrier dropped them (#705). + st := &fakeStat{Atim: fakeTimespec{Sec: 11, Nsec: 7}, Ctimespec: fakeTimespec{Sec: 22, Nsec: 999_999_999}, Birthtimespec: fakeTimespec{Sec: 33}} for _, c := range []struct { names []string - want int64 + want time.Time wantOk bool comment string }{ - {[]string{"Atim", "Atimespec"}, 11, true, "the Linux spelling, found first"}, - {[]string{"Ctim", "Ctimespec"}, 22, true, "the BSD spelling, found second"}, - {[]string{"Birthtimespec", "Btim"}, 33, true, "a creation time"}, - {[]string{"Mtim", "Mtimespec"}, 0, false, "a name the struct does not carry"}, - {[]string{"NotATime"}, 0, false, "a field that is not a timespec"}, + {[]string{"Atim", "Atimespec"}, time.Unix(11, 7), true, "the Linux spelling, found first"}, + {[]string{"Ctim", "Ctimespec"}, time.Unix(22, 999_999_999), true, "the BSD spelling, found second"}, + {[]string{"Birthtimespec", "Btim"}, time.Unix(33, 0), true, "a creation time"}, + {[]string{"Mtim", "Mtimespec"}, time.Time{}, false, "a name the struct does not carry"}, + {[]string{"NotATime"}, time.Time{}, false, "a field that is not a timespec"}, } { got, ok := statTimeField(st, c.names...) - if got != c.want || ok != c.wantOk { - t.Errorf("%s: got %d,%v want %d,%v", c.comment, got, ok, c.want, c.wantOk) + if !got.Equal(c.want) || ok != c.wantOk { + t.Errorf("%s: got %v,%v want %v,%v", c.comment, got, ok, c.want, c.wantOk) } } + // A timespec with no integer Nsec member keeps its whole seconds. + type secOnly struct{ Sec int64 } + if got, ok := statTimeField(&struct{ Atim secOnly }{Atim: secOnly{Sec: 5}}, "Atim"); !ok || !got.Equal(time.Unix(5, 0)) { + t.Errorf("a seconds-only timespec: got %v,%v", got, ok) + } + // A struct with no Sec is skipped, and the next name is tried. + type noSec struct{ Nsec int64 } + if got, ok := statTimeField(&struct { + Atim noSec + Atimespec fakeTimespec + }{Atimespec: fakeTimespec{Sec: 9, Nsec: 1}}, "Atim", "Atimespec"); !ok || !got.Equal(time.Unix(9, 1)) { + t.Errorf("a timespec without Sec must be skipped: got %v,%v", got, ok) + } if _, ok := statTimeField(nil, "Atim"); ok { t.Errorf("a nil Sys() must report nothing") } @@ -84,15 +98,15 @@ func (s stubInfo) Sys() any { return s.sys } // modification time stands in and no creation time is recorded, so // File::Stat#birthtime raises the way MRI does on Linux. func TestStatTimestamps(t *testing.T) { - mod := time.Unix(500, 0) + mod := time.Unix(500, 42) full := statTimestamps(stubInfo{mod: mod, sys: &fakeStat{ - Atim: fakeTimespec{Sec: 1}, Ctimespec: fakeTimespec{Sec: 2}, Birthtimespec: fakeTimespec{Sec: 3}, + Atim: fakeTimespec{Sec: 1, Nsec: 10}, Ctimespec: fakeTimespec{Sec: 2, Nsec: 20}, Birthtimespec: fakeTimespec{Sec: 3, Nsec: 30}, }}, statFields{}) - if full.atime != 1 || full.ctime != 2 || full.btime != 3 || !full.hasBtime { + if !full.atime.Equal(time.Unix(1, 10)) || !full.ctime.Equal(time.Unix(2, 20)) || !full.btime.Equal(time.Unix(3, 30)) || !full.hasBtime { t.Errorf("full stat: %+v", full) } bare := statTimestamps(stubInfo{mod: mod, sys: nil}, statFields{}) - if bare.atime != 500 || bare.ctime != 500 { + if !bare.atime.Equal(mod) || !bare.ctime.Equal(mod) { t.Errorf("a stat without timestamps must fall back to mtime: %+v", bare) } if bare.hasBtime { diff --git a/internal/vm/stdlib_puppet_batch_test.go b/internal/vm/stdlib_puppet_batch_test.go index af1dd8f6..adf26d86 100644 --- a/internal/vm/stdlib_puppet_batch_test.go +++ b/internal/vm/stdlib_puppet_batch_test.go @@ -115,7 +115,8 @@ func TestProcessStdlib(t *testing.T) { {"maxgroups", `p Process.maxgroups`, "16\n"}, {"maxgroups_set", `p(Process.maxgroups = 1024)`, "1024\n"}, {"clock_realtime_const", `p Process::CLOCK_REALTIME`, "0\n"}, - {"clock_monotonic_const", `p Process::CLOCK_MONOTONIC`, "6\n"}, + // The host's own clockid_t: 1 on Linux, 6 on Darwin (#705). + {"clock_monotonic_const", `p Process::CLOCK_MONOTONIC == (RUBY_PLATFORM.include?("linux") ? 1 : 6)`, "true\n"}, {"clock_default", `p Process.clock_gettime(Process::CLOCK_MONOTONIC).class`, "Float\n"}, {"clock_realtime", `p Process.clock_gettime(Process::CLOCK_REALTIME).class`, "Float\n"}, {"clock_float_second", `p Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second).class`, "Float\n"}, From 79392242899f799963d1cfe69925e38eedfb26ff Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 18:07:08 +0100 Subject: [PATCH 2/3] vm: File.utime converts a lone nil and names the class, as MRI does The ubuntu coverage ratchet failed on two functions. Fixing them showed three divergences from MRI 4.0.10, measured with rubydiff: - file.c utime_args_init leaves the timespec NULL ("now") only when BOTH times are nil; otherwise each goes through rb_time_timespec, atime first. rbgo read each nil as "now" on its own, so File.utime(nil, 5, f) succeeded where MRI raises "can't convert NilClass into time". - time.c time_timespec names the argument's class: "can't convert String into time". rbgo said "no implicit conversion of \"x\" into Time". - File.utime with fewer than two arguments reported a Go index panic ("utime: runtime error: index out of range") instead of "wrong number of arguments (given 1, expected 2+)". numFloat had a single caller, which already handled Integer first, so its Integer case was dead (85.7% on linux). It is folded into utimeArg. timeOf's recorded-birthtime branch runs only where the stat struct has a creation time, never on linux; a stub stat now drives it everywhere. Co-Authored-By: Claude Opus 5.5 --- internal/vm/file.go | 47 ++++++++++++++++--------- internal/vm/file_ops_internal_test.go | 12 +++++-- internal/vm/statdetail_internal_test.go | 13 +++++++ internal/vm/time.go | 16 --------- 4 files changed, 53 insertions(+), 35 deletions(-) diff --git a/internal/vm/file.go b/internal/vm/file.go index 3aa4ff46..a6c94070 100644 --- a/internal/vm/file.go +++ b/internal/vm/file.go @@ -339,7 +339,10 @@ func (vm *VM) registerFile() { return object.IntValue(int64(len(paths))) }) def("utime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - at, mt := utimeArgOrNow(args[0]), utimeArgOrNow(args[1]) + if len(args) < 2 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 2+)", len(args)) + } + at, mt := vm.utimeArgs(args[0], args[1]) paths := args[2:] for _, a := range paths { p := pathArg(vm, a) @@ -357,7 +360,7 @@ func (vm *VM) registerFile() { if len(args) < 2 { raise("ArgumentError", "wrong number of arguments (given %d, expected 2+)", len(args)) } - at, mt := utimeArgOrNow(args[0]), utimeArgOrNow(args[1]) + at, mt := vm.utimeArgs(args[0], args[1]) paths := args[2:] for _, a := range paths { p := pathArg(vm, a) @@ -1028,26 +1031,36 @@ func chownID(v object.Value) int { // seconds-since-epoch) to the instant it names, nanoseconds included, as // rb_time_timespec does. It used to return whole seconds, so File.utime // dropped the sub-second part MRI writes (#705). -func utimeArg(v object.Value) stdtime.Time { - if t, ok := v.(*Time); ok { - return t.t - } - if i, ok := v.(object.Integer); ok { - return stdtime.Unix(int64(i), 0) +func (vm *VM) utimeArg(v object.Value) stdtime.Time { + var f float64 + switch n := v.(type) { + case *Time: + return n.t + case object.Integer: + return stdtime.Unix(int64(n), 0) + case object.Float: + f = float64(n) + case *object.Rational: + f, _ = n.R.Float64() + default: + raise("TypeError", "can't convert %s into time", vm.objClassName(v)) } - f := numFloat(v) sec := math.Floor(f) return stdtime.Unix(int64(sec), int64(math.Round((f-sec)*1e9))) } -// utimeArgOrNow is utimeArg with MRI's nil handling for File.utime / -// File.lutime: a nil atime/mtime means "use the current time" (file.c -// utime_internal leaves the timespec NULL, which utimensat reads as UTIME_NOW). -func utimeArgOrNow(v object.Value) stdtime.Time { - if v == object.NilV { - return stdtime.Now() - } - return utimeArg(v) +// utimeArgs is file.c utime_args_init for File.utime / File.lutime: only when +// BOTH times are nil is the timespec left NULL (utimensat's "now"); otherwise +// each goes through rb_time_timespec, atime first, so a lone nil raises +// "can't convert NilClass into time". It used to read each nil as "now" on its +// own, which MRI 4.0.10 refuses. +func (vm *VM) utimeArgs(atime, mtime object.Value) (stdtime.Time, stdtime.Time) { + if atime == object.NilV && mtime == object.NilV { + now := stdtime.Now() + return now, now + } + at := vm.utimeArg(atime) + return at, vm.utimeArg(mtime) } // registerErrnoClasses installs the Errno::Exxx hierarchy under the Errno module diff --git a/internal/vm/file_ops_internal_test.go b/internal/vm/file_ops_internal_test.go index 53f4a82d..7201249f 100644 --- a/internal/vm/file_ops_internal_test.go +++ b/internal/vm/file_ops_internal_test.go @@ -29,10 +29,18 @@ func TestFileMetaOps(t *testing.T) { // chmod returns the number of paths; multiple paths sum. {`p File.chmod(0o600, "` + f + `")`, "1\n"}, // utime returns the count; accepts a Time, and Integer/Float/Rational - // second counts (each coerced to whole Unix seconds). + // second counts (the fractions kept to the nanosecond). {`p File.utime(Time.now, Time.now, "` + f + `")`, "1\n"}, {`p File.utime(0, 0, "` + f + `")`, "1\n"}, {`p File.utime(Rational(3, 2), 2.0, "` + f + `")`, "1\n"}, + // Measured on MRI 4.0.10 (file.c utime_args_init, time.c time_timespec): + // only a nil PAIR means "now"; a lone nil is converted like any other + // argument, atime first, and the message names the argument's class. + {`begin; File.utime(nil, 5, "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert NilClass into time\n"}, + {`begin; File.utime(Object.new, nil, "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert Object into time\n"}, + {`begin; File.lutime(5, "x", "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert String into time\n"}, + {`p File.utime(1, 2)`, "0\n"}, + {`begin; File.utime(1); rescue ArgumentError => e; puts e.message; end`, "wrong number of arguments (given 1, expected 2+)\n"}, // chown with nil ids leaves them unchanged and still reports the count. {`p File.chown(nil, nil, "` + f + `")`, "1\n"}, {`p File.lchown(nil, nil, "` + f + `")`, "1\n"}, @@ -50,7 +58,7 @@ func TestFileMetaOps(t *testing.T) { t.Errorf("src=%q got=%q want=%q", c.src, got, c.want) } } - // A non-numeric utime second count is a TypeError (numFloat rejects it). + // A non-numeric utime second count is a TypeError (utimeArg rejects it). if got := runFSErr(t, `File.utime(:bad, 0, "`+f+`")`); got != "TypeError" { t.Errorf("utime(:bad): got %q want TypeError", got) } diff --git a/internal/vm/statdetail_internal_test.go b/internal/vm/statdetail_internal_test.go index 63c5f376..5a19baf1 100644 --- a/internal/vm/statdetail_internal_test.go +++ b/internal/vm/statdetail_internal_test.go @@ -114,6 +114,19 @@ func TestStatTimestamps(t *testing.T) { } } +// TestFileStatBirthtimeRecorded drives the other side of timeOf's birthtime +// branch: a stat struct that carries a creation time answers it, nanoseconds +// included. A Linux host never builds one (no statx here), so without this stub +// the branch is covered on darwin only and the ubuntu coverage ratchet fails. +func TestFileStatBirthtimeRecorded(t *testing.T) { + info := stubInfo{mod: time.Unix(7, 0), sys: &fakeStat{Birthtimespec: fakeTimespec{Sec: 3, Nsec: 30}}} + st := &FileStat{fi: info, sys: statTimestamps(info, statFields{})} + got, ok := New(nil).send(st, "birthtime", nil, nil).(*Time) + if !ok || !got.t.Equal(time.Unix(3, 30)) { + t.Errorf("birthtime with a recorded creation time = %v, want 3s+30ns", got) + } +} + // TestFileStatBirthtimeUnsupported drives the NotImplementedError branch through // the Ruby surface by handing newFileStat a stat struct with no creation time — // the state a Linux host is always in. diff --git a/internal/vm/time.go b/internal/vm/time.go index 8673b063..100d7559 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -857,22 +857,6 @@ func splitSeconds(f float64) (int64, int64) { return whole, ns } -// numFloat marshals a Ruby Integer / Float / Rational to a float64, raising -// TypeError otherwise. -func numFloat(v object.Value) float64 { - switch n := v.(type) { - case object.Integer: - return float64(n) - case object.Float: - return float64(n) - case *object.Rational: - f, _ := n.R.Float64() - return f - } - raise("TypeError", "no implicit conversion of %s into Time", v.Inspect()) - return 0 -} - // timeInt coerces a calendar field to an int the way MRI does: an Integer or // Float directly, otherwise via #to_int (whose result must itself be an // Integer), else a class-named TypeError. From 556f8b5827deb939867396e5abd53ea973d5f448 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 30 Nov 2026 20:59:37 +0100 Subject: [PATCH 3/3] vm: CPU-time clocks read GetProcessTimes on Windows The windows test lane failed TestProcessClockSymbolic with a nil pointer dereference: Process.clock_gettime(:CLOCK_BASED_CLOCK_PROCESS_ CPUTIME_ID), the one CPU-time emulation process.c compiles with no #ifdef guard, reads procRusage, and spawn_windows.go and spawn_wasm.go declared that seam without ever assigning it. Windows now reads GetProcessTimes, where MRI's win32 clock() and Process.times read the process's CPU time; a FILETIME duration counts 100 ns ticks. wasm has no getrusage and reports zero, as Plan 9 does. Co-Authored-By: Claude Opus 5.5 --- internal/vm/spawn_wasm.go | 5 ++++- internal/vm/spawn_windows.go | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/internal/vm/spawn_wasm.go b/internal/vm/spawn_wasm.go index fa016b2b..2c53abba 100644 --- a/internal/vm/spawn_wasm.go +++ b/internal/vm/spawn_wasm.go @@ -47,9 +47,12 @@ var ( procSetpgid func(pid, pgid int) error procGetsid func(pid int) (int, error) procKill func(pid, sig int) error - procRusage func() (utime, stime float64) ) +// procRusage reports no CPU time: wasm has no getrusage, as Plan 9 has none. +// It was left nil, so the CPU-time clocks were a nil dereference here. +var procRusage = func() (utime, stime float64) { return 0, 0 } + // runSpawnProc has no meaning under wasm (no subprocesses), so Process.spawn // raises NotImplementedError there rather than silently succeeding. var runSpawnProc = func(*spawnReq) int { diff --git a/internal/vm/spawn_windows.go b/internal/vm/spawn_windows.go index 2c3c73dd..4fc3e6d0 100644 --- a/internal/vm/spawn_windows.go +++ b/internal/vm/spawn_windows.go @@ -8,6 +8,8 @@ package vm import ( "os/exec" + + "golang.org/x/sys/windows" ) // runCaptured runs cmd on Windows, returning its combined output and exit code. A @@ -87,9 +89,24 @@ var ( procSetpgid func(pid, pgid int) error procGetsid func(pid int) (int, error) procKill func(pid, sig int) error - procRusage func() (utime, stime float64) ) +// procRusage reports this process's user and system CPU time in seconds from +// GetProcessTimes, which is where MRI's Windows clock() and Process.times read +// it (win32/win32.c). It was left nil here, so every CPU-time clock +// (CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID, the one with no #ifdef guard) was a +// nil dereference on Windows. A FILETIME duration counts 100 ns ticks. +var procRusage = func() (utime, stime float64) { + var creation, exit, kernel, user windows.Filetime + if windows.GetProcessTimes(windows.CurrentProcess(), &creation, &exit, &kernel, &user) != nil { + return 0, 0 + } + ticks := func(f windows.Filetime) float64 { + return float64(uint64(f.HighDateTime)<<32|uint64(f.LowDateTime)) / 1e7 + } + return ticks(user), ticks(kernel) +} + // runSpawnProc runs one prepared child to completion (see spawn_native.go for // the shape and why it is a package var); the shell wrapper is cmd.exe here. var runSpawnProc = func(r *spawnReq) int {