...

Source file src/syscall/syscall_darwin.go

     1	// Copyright 2009,2010 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	// Darwin system calls.
     6	// This file is compiled as ordinary Go code,
     7	// but it is also input to mksyscall,
     8	// which parses the //sys lines and generates system call stubs.
     9	// Note that sometimes we use a lowercase //sys name and wrap
    10	// it in our own nicer implementation, either here or in
    11	// syscall_bsd.go or syscall_unix.go.
    12	
    13	package syscall
    14	
    15	import (
    16		errorspkg "errors"
    17		"unsafe"
    18	)
    19	
    20	const ImplementsGetwd = true
    21	
    22	func Getwd() (string, error) {
    23		buf := make([]byte, 2048)
    24		attrs, err := getAttrList(".", attrList{CommonAttr: attrCmnFullpath}, buf, 0)
    25		if err == nil && len(attrs) == 1 && len(attrs[0]) >= 2 {
    26			wd := string(attrs[0])
    27			// Sanity check that it's an absolute path and ends
    28			// in a null byte, which we then strip.
    29			if wd[0] == '/' && wd[len(wd)-1] == 0 {
    30				return wd[:len(wd)-1], nil
    31			}
    32		}
    33		// If pkg/os/getwd.go gets ENOTSUP, it will fall back to the
    34		// slow algorithm.
    35		return "", ENOTSUP
    36	}
    37	
    38	type SockaddrDatalink struct {
    39		Len    uint8
    40		Family uint8
    41		Index  uint16
    42		Type   uint8
    43		Nlen   uint8
    44		Alen   uint8
    45		Slen   uint8
    46		Data   [12]int8
    47		raw    RawSockaddrDatalink
    48	}
    49	
    50	// Translate "kern.hostname" to []_C_int{0,1,2,3}.
    51	func nametomib(name string) (mib []_C_int, err error) {
    52		const siz = unsafe.Sizeof(mib[0])
    53	
    54		// NOTE(rsc): It seems strange to set the buffer to have
    55		// size CTL_MAXNAME+2 but use only CTL_MAXNAME
    56		// as the size. I don't know why the +2 is here, but the
    57		// kernel uses +2 for its own implementation of this function.
    58		// I am scared that if we don't include the +2 here, the kernel
    59		// will silently write 2 words farther than we specify
    60		// and we'll get memory corruption.
    61		var buf [CTL_MAXNAME + 2]_C_int
    62		n := uintptr(CTL_MAXNAME) * siz
    63	
    64		p := (*byte)(unsafe.Pointer(&buf[0]))
    65		bytes, err := ByteSliceFromString(name)
    66		if err != nil {
    67			return nil, err
    68		}
    69	
    70		// Magic sysctl: "setting" 0.3 to a string name
    71		// lets you read back the array of integers form.
    72		if err = sysctl([]_C_int{0, 3}, p, &n, &bytes[0], uintptr(len(name))); err != nil {
    73			return nil, err
    74		}
    75		return buf[0 : n/siz], nil
    76	}
    77	
    78	func direntIno(buf []byte) (uint64, bool) {
    79		return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
    80	}
    81	
    82	func direntReclen(buf []byte) (uint64, bool) {
    83		return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
    84	}
    85	
    86	func direntNamlen(buf []byte) (uint64, bool) {
    87		return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))
    88	}
    89	
    90	func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) }
    91	func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) }
    92	
    93	const (
    94		attrBitMapCount = 5
    95		attrCmnModtime  = 0x00000400
    96		attrCmnAcctime  = 0x00001000
    97		attrCmnFullpath = 0x08000000
    98	)
    99	
   100	type attrList struct {
   101		bitmapCount uint16
   102		_           uint16
   103		CommonAttr  uint32
   104		VolAttr     uint32
   105		DirAttr     uint32
   106		FileAttr    uint32
   107		Forkattr    uint32
   108	}
   109	
   110	func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) {
   111		if len(attrBuf) < 4 {
   112			return nil, errorspkg.New("attrBuf too small")
   113		}
   114		attrList.bitmapCount = attrBitMapCount
   115	
   116		var _p0 *byte
   117		_p0, err = BytePtrFromString(path)
   118		if err != nil {
   119			return nil, err
   120		}
   121	
   122		_, _, e1 := syscall6(
   123			funcPC(libc_getattrlist_trampoline),
   124			uintptr(unsafe.Pointer(_p0)),
   125			uintptr(unsafe.Pointer(&attrList)),
   126			uintptr(unsafe.Pointer(&attrBuf[0])),
   127			uintptr(len(attrBuf)),
   128			uintptr(options),
   129			0,
   130		)
   131		if e1 != 0 {
   132			return nil, e1
   133		}
   134		size := *(*uint32)(unsafe.Pointer(&attrBuf[0]))
   135	
   136		// dat is the section of attrBuf that contains valid data,
   137		// without the 4 byte length header. All attribute offsets
   138		// are relative to dat.
   139		dat := attrBuf
   140		if int(size) < len(attrBuf) {
   141			dat = dat[:size]
   142		}
   143		dat = dat[4:] // remove length prefix
   144	
   145		for i := uint32(0); int(i) < len(dat); {
   146			header := dat[i:]
   147			if len(header) < 8 {
   148				return attrs, errorspkg.New("truncated attribute header")
   149			}
   150			datOff := *(*int32)(unsafe.Pointer(&header[0]))
   151			attrLen := *(*uint32)(unsafe.Pointer(&header[4]))
   152			if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) {
   153				return attrs, errorspkg.New("truncated results; attrBuf too small")
   154			}
   155			end := uint32(datOff) + attrLen
   156			attrs = append(attrs, dat[datOff:end])
   157			i = end
   158			if r := i % 4; r != 0 {
   159				i += (4 - r)
   160			}
   161		}
   162		return
   163	}
   164	
   165	func libc_getattrlist_trampoline()
   166	
   167	//go:linkname libc_getattrlist libc_getattrlist
   168	//go:cgo_import_dynamic libc_getattrlist getattrlist "/usr/lib/libSystem.B.dylib"
   169	
   170	//sysnb pipe(p *[2]int32) (err error)
   171	
   172	func Pipe(p []int) (err error) {
   173		if len(p) != 2 {
   174			return EINVAL
   175		}
   176		var q [2]int32
   177		err = pipe(&q)
   178		p[0] = int(q[0])
   179		p[1] = int(q[1])
   180		return
   181	}
   182	
   183	func Getfsstat(buf []Statfs_t, flags int) (n int, err error) {
   184		var _p0 unsafe.Pointer
   185		var bufsize uintptr
   186		if len(buf) > 0 {
   187			_p0 = unsafe.Pointer(&buf[0])
   188			bufsize = unsafe.Sizeof(Statfs_t{}) * uintptr(len(buf))
   189		}
   190		r0, _, e1 := syscall(funcPC(libc_getfsstat_trampoline), uintptr(_p0), bufsize, uintptr(flags))
   191		n = int(r0)
   192		if e1 != 0 {
   193			err = e1
   194		}
   195		return
   196	}
   197	
   198	func libc_getfsstat_trampoline()
   199	
   200	//go:linkname libc_getfsstat libc_getfsstat
   201	//go:cgo_import_dynamic libc_getfsstat getfsstat "/usr/lib/libSystem.B.dylib"
   202	
   203	func setattrlistTimes(path string, times []Timespec) error {
   204		_p0, err := BytePtrFromString(path)
   205		if err != nil {
   206			return err
   207		}
   208	
   209		var attrList attrList
   210		attrList.bitmapCount = attrBitMapCount
   211		attrList.CommonAttr = attrCmnModtime | attrCmnAcctime
   212	
   213		// order is mtime, atime: the opposite of Chtimes
   214		attributes := [2]Timespec{times[1], times[0]}
   215		const options = 0
   216		_, _, e1 := syscall6(
   217			funcPC(libc_setattrlist_trampoline),
   218			uintptr(unsafe.Pointer(_p0)),
   219			uintptr(unsafe.Pointer(&attrList)),
   220			uintptr(unsafe.Pointer(&attributes)),
   221			uintptr(unsafe.Sizeof(attributes)),
   222			uintptr(options),
   223			0,
   224		)
   225		if e1 != 0 {
   226			return e1
   227		}
   228		return nil
   229	}
   230	
   231	func libc_setattrlist_trampoline()
   232	
   233	//go:linkname libc_setattrlist libc_setattrlist
   234	//go:cgo_import_dynamic libc_setattrlist setattrlist "/usr/lib/libSystem.B.dylib"
   235	
   236	func utimensat(dirfd int, path string, times *[2]Timespec, flag int) error {
   237		// Darwin doesn't support SYS_UTIMENSAT
   238		return ENOSYS
   239	}
   240	
   241	/*
   242	 * Wrapped
   243	 */
   244	
   245	//sys	kill(pid int, signum int, posix int) (err error)
   246	
   247	func Kill(pid int, signum Signal) (err error) { return kill(pid, int(signum), 1) }
   248	
   249	/*
   250	 * Exposed directly
   251	 */
   252	//sys	Access(path string, mode uint32) (err error)
   253	//sys	Adjtime(delta *Timeval, olddelta *Timeval) (err error)
   254	//sys	Chdir(path string) (err error)
   255	//sys	Chflags(path string, flags int) (err error)
   256	//sys	Chmod(path string, mode uint32) (err error)
   257	//sys	Chown(path string, uid int, gid int) (err error)
   258	//sys	Chroot(path string) (err error)
   259	//sys	Close(fd int) (err error)
   260	//sys	closedir(dir uintptr) (err error)
   261	//sys	Dup(fd int) (nfd int, err error)
   262	//sys	Dup2(from int, to int) (err error)
   263	//sys	Exchangedata(path1 string, path2 string, options int) (err error)
   264	//sys	Fchdir(fd int) (err error)
   265	//sys	Fchflags(fd int, flags int) (err error)
   266	//sys	Fchmod(fd int, mode uint32) (err error)
   267	//sys	Fchown(fd int, uid int, gid int) (err error)
   268	//sys	Flock(fd int, how int) (err error)
   269	//sys	Fpathconf(fd int, name int) (val int, err error)
   270	//sys	Fsync(fd int) (err error)
   271	//  Fsync is not called for os.File.Sync(). Please see internal/poll/fd_fsync_darwin.go
   272	//sys	Ftruncate(fd int, length int64) (err error)
   273	//sys	Getdtablesize() (size int)
   274	//sysnb	Getegid() (egid int)
   275	//sysnb	Geteuid() (uid int)
   276	//sysnb	Getgid() (gid int)
   277	//sysnb	Getpgid(pid int) (pgid int, err error)
   278	//sysnb	Getpgrp() (pgrp int)
   279	//sysnb	Getpid() (pid int)
   280	//sysnb	Getppid() (ppid int)
   281	//sys	Getpriority(which int, who int) (prio int, err error)
   282	//sysnb	Getrlimit(which int, lim *Rlimit) (err error)
   283	//sysnb	Getrusage(who int, rusage *Rusage) (err error)
   284	//sysnb	Getsid(pid int) (sid int, err error)
   285	//sysnb	Getuid() (uid int)
   286	//sysnb	Issetugid() (tainted bool)
   287	//sys	Kqueue() (fd int, err error)
   288	//sys	Lchown(path string, uid int, gid int) (err error)
   289	//sys	Link(path string, link string) (err error)
   290	//sys	Listen(s int, backlog int) (err error)
   291	//sys	Mkdir(path string, mode uint32) (err error)
   292	//sys	Mkfifo(path string, mode uint32) (err error)
   293	//sys	Mknod(path string, mode uint32, dev int) (err error)
   294	//sys	Mlock(b []byte) (err error)
   295	//sys	Mlockall(flags int) (err error)
   296	//sys	Mprotect(b []byte, prot int) (err error)
   297	//sys	Munlock(b []byte) (err error)
   298	//sys	Munlockall() (err error)
   299	//sys	Open(path string, mode int, perm uint32) (fd int, err error)
   300	//sys	Pathconf(path string, name int) (val int, err error)
   301	//sys	Pread(fd int, p []byte, offset int64) (n int, err error)
   302	//sys	Pwrite(fd int, p []byte, offset int64) (n int, err error)
   303	//sys	read(fd int, p []byte) (n int, err error)
   304	//sys	readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno)
   305	//sys	Readlink(path string, buf []byte) (n int, err error)
   306	//sys	Rename(from string, to string) (err error)
   307	//sys	Revoke(path string) (err error)
   308	//sys	Rmdir(path string) (err error)
   309	//sys	Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_lseek
   310	//sys	Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
   311	//sys	Setegid(egid int) (err error)
   312	//sysnb	Seteuid(euid int) (err error)
   313	//sysnb	Setgid(gid int) (err error)
   314	//sys	Setlogin(name string) (err error)
   315	//sysnb	Setpgid(pid int, pgid int) (err error)
   316	//sys	Setpriority(which int, who int, prio int) (err error)
   317	//sys	Setprivexec(flag int) (err error)
   318	//sysnb	Setregid(rgid int, egid int) (err error)
   319	//sysnb	Setreuid(ruid int, euid int) (err error)
   320	//sysnb	Setrlimit(which int, lim *Rlimit) (err error)
   321	//sysnb	Setsid() (pid int, err error)
   322	//sysnb	Settimeofday(tp *Timeval) (err error)
   323	//sysnb	Setuid(uid int) (err error)
   324	//sys	Symlink(path string, link string) (err error)
   325	//sys	Sync() (err error)
   326	//sys	Truncate(path string, length int64) (err error)
   327	//sys	Umask(newmask int) (oldmask int)
   328	//sys	Undelete(path string) (err error)
   329	//sys	Unlink(path string) (err error)
   330	//sys	Unmount(path string, flags int) (err error)
   331	//sys	write(fd int, p []byte) (n int, err error)
   332	//sys	writev(fd int, iovecs []Iovec) (cnt uintptr, err error)
   333	//sys   mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
   334	//sys   munmap(addr uintptr, length uintptr) (err error)
   335	//sysnb fork() (pid int, err error)
   336	//sysnb ioctl(fd int, req int, arg int) (err error)
   337	//sysnb ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_ioctl
   338	//sysnb execve(path *byte, argv **byte, envp **byte) (err error)
   339	//sysnb exit(res int) (err error)
   340	//sys	sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error)
   341	//sys	fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) = SYS_fcntl
   342	//sys   unlinkat(fd int, path string, flags int) (err error)
   343	//sys   openat(fd int, path string, flags int, perm uint32) (fdret int, err error)
   344	
   345	func init() {
   346		execveDarwin = execve
   347	}
   348	
   349	func fdopendir(fd int) (dir uintptr, err error) {
   350		r0, _, e1 := syscallPtr(funcPC(libc_fdopendir_trampoline), uintptr(fd), 0, 0)
   351		dir = uintptr(r0)
   352		if e1 != 0 {
   353			err = errnoErr(e1)
   354		}
   355		return
   356	}
   357	
   358	func libc_fdopendir_trampoline()
   359	
   360	//go:linkname libc_fdopendir libc_fdopendir
   361	//go:cgo_import_dynamic libc_fdopendir fdopendir "/usr/lib/libSystem.B.dylib"
   362	
   363	func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
   364		r0, _, e1 := syscall(funcPC(libc_read_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
   365		n = int(r0)
   366		if e1 != 0 {
   367			err = errnoErr(e1)
   368		}
   369		return
   370	}
   371	
   372	func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
   373		r0, _, e1 := syscall(funcPC(libc_write_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
   374		n = int(r0)
   375		if e1 != 0 {
   376			err = errnoErr(e1)
   377		}
   378		return
   379	}
   380	
   381	func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
   382		// Simulate Getdirentries using fdopendir/readdir_r/closedir.
   383		const ptrSize = unsafe.Sizeof(uintptr(0))
   384	
   385		// We store the number of entries to skip in the seek
   386		// offset of fd. See issue #31368.
   387		// It's not the full required semantics, but should handle the case
   388		// of calling Getdirentries or ReadDirent repeatedly.
   389		// It won't handle assigning the results of lseek to *basep, or handle
   390		// the directory being edited underfoot.
   391		skip, err := Seek(fd, 0, 1 /* SEEK_CUR */)
   392		if err != nil {
   393			return 0, err
   394		}
   395	
   396		// We need to duplicate the incoming file descriptor
   397		// because the caller expects to retain control of it, but
   398		// fdopendir expects to take control of its argument.
   399		// Just Dup'ing the file descriptor is not enough, as the
   400		// result shares underlying state. Use openat to make a really
   401		// new file descriptor referring to the same directory.
   402		fd2, err := openat(fd, ".", O_RDONLY, 0)
   403		if err != nil {
   404			return 0, err
   405		}
   406		d, err := fdopendir(fd2)
   407		if err != nil {
   408			Close(fd2)
   409			return 0, err
   410		}
   411		defer closedir(d)
   412	
   413		var cnt int64
   414		for {
   415			var entry Dirent
   416			var entryp *Dirent
   417			e := readdir_r(d, &entry, &entryp)
   418			if e != 0 {
   419				return n, errnoErr(e)
   420			}
   421			if entryp == nil {
   422				break
   423			}
   424			if skip > 0 {
   425				skip--
   426				cnt++
   427				continue
   428			}
   429			reclen := int(entry.Reclen)
   430			if reclen > len(buf) {
   431				// Not enough room. Return for now.
   432				// The counter will let us know where we should start up again.
   433				// Note: this strategy for suspending in the middle and
   434				// restarting is O(n^2) in the length of the directory. Oh well.
   435				break
   436			}
   437			// Copy entry into return buffer.
   438			s := struct {
   439				ptr unsafe.Pointer
   440				siz int
   441				cap int
   442			}{ptr: unsafe.Pointer(&entry), siz: reclen, cap: reclen}
   443			copy(buf, *(*[]byte)(unsafe.Pointer(&s)))
   444			buf = buf[reclen:]
   445			n += reclen
   446			cnt++
   447		}
   448		// Set the seek offset of the input fd to record
   449		// how many files we've already returned.
   450		_, err = Seek(fd, cnt, 0 /* SEEK_SET */)
   451		if err != nil {
   452			return n, err
   453		}
   454	
   455		return n, nil
   456	}
   457	
   458	// Implemented in the runtime package (runtime/sys_darwin.go)
   459	func syscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
   460	func syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
   461	func syscall6X(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
   462	func rawSyscall(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
   463	func rawSyscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
   464	func syscallPtr(fn, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
   465	
   466	// Find the entry point for f. See comments in runtime/proc.go for the
   467	// function of the same name.
   468	//go:nosplit
   469	func funcPC(f func()) uintptr {
   470		return **(**uintptr)(unsafe.Pointer(&f))
   471	}
   472	

View as plain text