From 042013bb04819f931e5ebd3d784e7282821833bd Mon Sep 17 00:00:00 2001 From: Ophestra Date: Thu, 6 Nov 2025 00:57:32 +0900 Subject: container/std: syscall JSON adapter This provides cross-platform JSON adapter for syscall number. Signed-off-by: Ophestra --- container/std/seccomp.go | 50 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 6 deletions(-) (limited to 'container/std/seccomp.go') diff --git a/container/std/seccomp.go b/container/std/seccomp.go index f3189ca5..05bc4269 100644 --- a/container/std/seccomp.go +++ b/container/std/seccomp.go @@ -1,5 +1,10 @@ package std +import ( + "encoding/json" + "strconv" +) + type ( // ScmpUint is equivalent to C.uint. ScmpUint uint32 @@ -19,20 +24,53 @@ type ( // ScmpArgCmp is equivalent to struct scmp_arg_cmp. ScmpArgCmp struct { // argument number, starting at 0 - Arg ScmpUint + Arg ScmpUint `json:"arg"` // the comparison op, e.g. SCMP_CMP_* - Op ScmpCompare + Op ScmpCompare `json:"op"` - DatumA, DatumB ScmpDatum + DatumA ScmpDatum `json:"a,omitempty"` + DatumB ScmpDatum `json:"b,omitempty"` } // A NativeRule specifies an arch-specific action taken by seccomp under certain conditions. NativeRule struct { // Syscall is the arch-dependent syscall number to act against. - Syscall ScmpSyscall + Syscall ScmpSyscall `json:"syscall"` // Errno is the errno value to return when the condition is satisfied. - Errno ScmpErrno + Errno ScmpErrno `json:"errno"` // Arg is the optional struct scmp_arg_cmp passed to libseccomp. - Arg *ScmpArgCmp + Arg *ScmpArgCmp `json:"arg,omitempty"` } ) + +// MarshalJSON resolves the name of [ScmpSyscall] and encodes it as a [json] string. +// If such a name does not exist, the syscall number is encoded instead. +func (num *ScmpSyscall) MarshalJSON() ([]byte, error) { + n := int(*num) + for name, cur := range Syscalls() { + if cur == n { + return json.Marshal(name) + } + } + return json.Marshal(n) +} + +// SyscallNameError is returned when trying to unmarshal an invalid syscall name into [ScmpSyscall]. +type SyscallNameError string + +func (e SyscallNameError) Error() string { return "invalid syscall name " + strconv.Quote(string(e)) } + +// UnmarshalJSON looks up the syscall number corresponding to name encoded in data +// by calling [SyscallResolveName]. +func (num *ScmpSyscall) UnmarshalJSON(data []byte) error { + var name string + if err := json.Unmarshal(data, &name); err != nil { + return err + } + if n, ok := SyscallResolveName(name); !ok { + return SyscallNameError(name) + } else { + *num = ScmpSyscall(n) + return nil + } +} -- cgit v1.3.1