Beispiel #1
0
func main() {
	log.SetFlags(log.Lshortfile)

	c, err := fdrpc.Dial("/tmp/test.socket")
	if err != nil {
		log.Fatal(err)
	}

	var fd fdrpc.FD
	if err := c.Call("Obj.GetStdOut", struct{}{}, &fd); err != nil {
		log.Fatal(err)
	}
	syscall.Write(fd.FD, []byte("Hello from request 1\n"))

	if err := c.Call("Obj.GetStdOut", struct{}{}, &fd); err != nil {
		log.Fatal(err)
	}
	syscall.Write(fd.FD, []byte("Hello from request 2\n"))

	var streams []fdrpc.FD
	if err := c.Call("Obj.GetStreams", struct{}{}, &streams); err != nil {
		log.Fatal(err)
	}
	syscall.Write(streams[0].FD, []byte("Hello stdout\n"))
	syscall.Write(streams[1].FD, []byte("Hello stderr\n"))
}
Beispiel #2
0
func TestSelect(t *testing.T) {
	var p1, p2 [2]int
	mustNil(syscall.Pipe(p1[:]))
	mustNil(syscall.Pipe(p2[:]))
	fs := NewFdSet(p1[0], p2[0])
	var maxfd int
	if p1[0] > p2[0] {
		maxfd = p1[0] + 1
	} else {
		maxfd = p2[0] + 1
	}
	go func() {
		syscall.Write(p1[1], []byte("to p1"))
		syscall.Write(p2[1], []byte("to p2"))
		syscall.Close(p1[1])
		syscall.Close(p2[1])
	}()
	e := Select(maxfd+1, fs, nil, nil, nil)
	if e != nil {
		t.Errorf("Select(%v, %v, nil, nil, nil) => %v, want <nil>",
			maxfd+1, fs, e)
	}
	syscall.Close(p1[0])
	syscall.Close(p2[0])
}
Beispiel #3
0
func kmemleakScan(report bool) {
	fd, err := syscall.Open("/sys/kernel/debug/kmemleak", syscall.O_RDWR, 0)
	if err != nil {
		panic(err)
	}
	defer syscall.Close(fd)
	if _, err := syscall.Write(fd, []byte("scan")); err != nil {
		panic(err)
	}
	if report {
		if kmemleakBuf == nil {
			kmemleakBuf = make([]byte, 128<<10)
		}
		n, err := syscall.Read(fd, kmemleakBuf)
		if err != nil {
			panic(err)
		}
		if n != 0 {
			// BUG in output should be recognized by manager.
			logf(0, "BUG: memory leak:\n%s\n", kmemleakBuf[:n])
		}
	}
	if _, err := syscall.Write(fd, []byte("clear")); err != nil {
		panic(err)
	}
}
Beispiel #4
0
func screenio() (err error) {
	var (
		bytesread     int
		c_in, c_out   [1]byte
		up            []byte = []byte("\033[A")
		zed           []byte = []byte("Z")
		eightbitchars [256]byte
	)

	println("screenio")
	for i := range eightbitchars {
		eightbitchars[i] = byte(i)
	}

	for {
		println("Read")
		bytesread, err = syscall.Read(ttyfd, c_in[0:])
		println("bytesread", bytesread)
		if err != nil {
			return
		} else if bytesread < 0 {
			return errors.New("read error")
		}

		if bytesread == 0 {
			c_out[0] = 'T'
			_, err = syscall.Write(ttyfd, c_out[0:])
			if err != nil {
				return
			}
		} else {
			switch c_in[0] {
			case 'q':
				return nil
			case 'z':
				_, err = syscall.Write(ttyfd, zed[:1])
				if err != nil {
					return nil
				}
			case 'u':
				_, err = syscall.Write(ttyfd, up)
				if err != nil {
					return nil
				}
			default:
				c_out[0] = '*'
				_, err = syscall.Write(ttyfd, c_out[0:])
				if err != nil {
					return nil
				}
			}
		}
	}
}
Beispiel #5
0
func ScreenIO() (err error) {
	var (
		errno         error
		bytesread     int
		c_in, c_out   [1]byte
		up            []byte = []byte("\033[A")
		eightbitchars [256]byte
	)

	for i := range eightbitchars {
		eightbitchars[i] = byte(i)
	}

	for {
		bytesread, errno = syscall.Read(ttyfd, c_in[0:])
		if err = os.NewSyscallError("SYS_READ", errno); err != nil {
			return
		} else if bytesread < 0 {
			return errors.New("read error")
		}

		if bytesread == 0 {
			c_out[0] = 'T'
			_, errno = syscall.Write(ttyfd, c_out[0:])
			if err = os.NewSyscallError("SYS_WRITE", errno); err != nil {
				return
			}
		} else {
			switch c_in[0] {
			case 'q':
				return nil
			case 'z':
				_, errno = syscall.Write(ttyfd, []byte{'Z'})
				if err = os.NewSyscallError("SYS_WRITE", errno); err != nil {
					return nil
				}
			case 'u':
				_, errno = syscall.Write(ttyfd, up)
				if err = os.NewSyscallError("SYS_WRITE", errno); err != nil {
					return nil
				}
			default:
				c_out[0] = '*'
				_, errno = syscall.Write(ttyfd, c_out[0:])
				if err = os.NewSyscallError("SYS_WRITE", errno); err != nil {
					return nil
				}
			}
		}
	}

	return nil
}
Beispiel #6
0
// handle requests
func (nbd *NBD) handle() {
	buf := make([]byte, 2<<19)
	var x request

	for {
		syscall.Read(nbd.socket, buf[0:28])

		x.magic = binary.BigEndian.Uint32(buf)
		x.typus = binary.BigEndian.Uint32(buf[4:8])
		x.handle = binary.BigEndian.Uint64(buf[8:16])
		x.from = binary.BigEndian.Uint64(buf[16:24])
		x.len = binary.BigEndian.Uint32(buf[24:28])

		switch x.magic {
		case NBD_REPLY_MAGIC:
			fallthrough
		case NBD_REQUEST_MAGIC:
			switch x.typus {
			case NBD_CMD_READ:
				nbd.device.ReadAt(buf[16:16+x.len], int64(x.from))
				binary.BigEndian.PutUint32(buf[0:4], NBD_REPLY_MAGIC)
				binary.BigEndian.PutUint32(buf[4:8], 0)
				syscall.Write(nbd.socket, buf[0:16+x.len])
			case NBD_CMD_WRITE:
				n, _ := syscall.Read(nbd.socket, buf[28:28+x.len])
				for uint32(n) < x.len {
					m, _ := syscall.Read(nbd.socket, buf[28+n:28+x.len])
					n += m
				}
				nbd.device.WriteAt(buf[28:28+x.len], int64(x.from))
				binary.BigEndian.PutUint32(buf[0:4], NBD_REPLY_MAGIC)
				binary.BigEndian.PutUint32(buf[4:8], 0)
				syscall.Write(nbd.socket, buf[0:16])
			case NBD_CMD_DISC:
				panic("Disconnect")
			case NBD_CMD_FLUSH:
				nbd.device.Sync()
				binary.BigEndian.PutUint32(buf[0:4], NBD_REPLY_MAGIC)
				binary.BigEndian.PutUint32(buf[4:8], 1)
				syscall.Write(nbd.socket, buf[0:16])
			case NBD_CMD_TRIM:
				binary.BigEndian.PutUint32(buf[0:4], NBD_REPLY_MAGIC)
				binary.BigEndian.PutUint32(buf[4:8], 1)
				syscall.Write(nbd.socket, buf[0:16])
			default:
				panic("unknown command")
			}
		default:
			panic("Invalid packet")
		}
	}
}
Beispiel #7
0
func kmemleakScan(report bool) {
	fd, err := syscall.Open("/sys/kernel/debug/kmemleak", syscall.O_RDWR, 0)
	if err != nil {
		panic(err)
	}
	defer syscall.Close(fd)
	// Kmemleak has false positives. To mitigate most of them, it checksums
	// potentially leaked objects, and reports them only on the next scan
	// iff the checksum does not change. Because of that we do the following
	// intricate dance:
	// Scan, sleep, scan again. At this point we can get some leaks.
	// If there are leaks, we sleep and scan again, this can remove
	// false leaks. Then, read kmemleak again. If we get leaks now, then
	// hopefully these are true positives during the previous testing cycle.
	if _, err := syscall.Write(fd, []byte("scan")); err != nil {
		panic(err)
	}
	time.Sleep(time.Second)
	if _, err := syscall.Write(fd, []byte("scan")); err != nil {
		panic(err)
	}
	if report {
		if kmemleakBuf == nil {
			kmemleakBuf = make([]byte, 128<<10)
		}
		n, err := syscall.Read(fd, kmemleakBuf)
		if err != nil {
			panic(err)
		}
		if n != 0 {
			time.Sleep(time.Second)
			if _, err := syscall.Write(fd, []byte("scan")); err != nil {
				panic(err)
			}
			n, err := syscall.Read(fd, kmemleakBuf)
			if err != nil {
				panic(err)
			}
			if n != 0 {
				// BUG in output should be recognized by manager.
				Logf(0, "BUG: memory leak:\n%s\n", kmemleakBuf[:n])
			}
		}
	}
	if _, err := syscall.Write(fd, []byte("clear")); err != nil {
		panic(err)
	}
}
Beispiel #8
0
func main() {
	args := Arguments()

	infile, args, err := args.String("in-file", nil)
	Check(err)
	outfile, args, err := args.String("out-file", nil)
	Check(err)

	infd, err := syscall.Open(infile, int(ReadOnly), 0)
	Check(err)
	defer func() { Check(syscall.Close(infd)) }()

	flags := Create | WriteOnly | Truncate
	perms := 0 |
		UserRead | UserWrite |
		GroupRead | GroupWrite |
		OtherRead | OtherWrite
	outfd, err := syscall.Open(outfile, int(flags), uint32(perms))
	Check(err)
	defer func() { Check(syscall.Close(outfd)) }()

	bufSize := 1024
	buf := make([]byte, bufSize)
	var n int
	for {
		n, err = syscall.Read(infd, buf)
		Check(err)
		if n == 0 {
			break
		}
		_, err = syscall.Write(outfd, buf[:n])
		Check(err)
	}
}
Beispiel #9
0
func main() {
	acceptingFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
	check(err)

	addr := &syscall.SockaddrInet4{Port: 3000, Addr: [4]byte{0, 0, 0, 0}}
	err = syscall.Bind(acceptingFd, addr)
	check(err)

	err = syscall.Listen(acceptingFd, 100)
	check(err)

	for {
		connectionFd, _, err := syscall.Accept(acceptingFd)
		check(err)
		fmt.Println("Accepted new connectrion")

		data := make([]byte, 1024)
		_, err = syscall.Read(connectionFd, data)
		check(err)
		fmt.Printf("Received: %s\n", string(data))

		_, err = syscall.Write(connectionFd, data)
		check(err)

		err = syscall.Close(connectionFd)
		check(err)
	}
}
Beispiel #10
0
func CgcSyscall(u models.Usercorn) {
	// TODO: handle errors or something
	args, _ := u.ReadRegs(LinuxRegs)
	eax, _ := u.RegRead(uc.X86_REG_EAX)
	var ret uint64
	switch eax {
	case 1: // _terminate
		syscall.Exit(int(args[0]))
	case 2: // transmit
		mem, _ := u.MemRead(args[1], args[2])
		n, _ := syscall.Write(int(args[0]), mem)
		writeAddr(u, args[3], uint64(n))
	case 3: // receive
		tmp := make([]byte, args[2])
		n, _ := syscall.Read(int(args[0]), tmp)
		u.MemWrite(args[1], tmp[:n])
		writeAddr(u, args[3], uint64(n))
	case 5: // allocate
		addr, _ := u.Mmap(0, args[0])
		// args[1] == is executable
		writeAddr(u, args[2], addr)
	case 7: // random
		tmp := make([]byte, args[1])
		rand.Read(tmp)
		u.MemWrite(args[0], tmp)
		writeAddr(u, args[2], args[1])
	}
	u.RegWrite(uc.X86_REG_EAX, ret)
}
func (tfd testFd) put(t *testing.T) {
	buf := make([]byte, 10)
	_, errno := syscall.Write(tfd[1], buf)
	if errno != nil {
		t.Fatalf("Failed to write to pipe: %v", errno)
	}
}
Beispiel #12
0
func (file *File) Write(b []byte) (ret int, err error) {
	if file == nil {
		return -1, syscall.EINVAL
	}
	r, e := syscall.Write(file.fd, b)
	return int(r), e
}
Beispiel #13
0
// Write writes the contents of p into the buffer. It returns the number of
// bytes written. If nn < len(p), it also returns an error explaining why the
// write is short.
func (w *Writer) Write(p []byte) (nn int, err error) {
	if w.err != nil {
		return 0, w.err
	}

	var bcopied int
	var n int
	nn = 0

	for len(p) > 0 {
		bcopied = copy(w.buff[w.pbuff:], p)
		if bcopied < len(p) {
			p = p[bcopied:]
			n, w.err = syscall.Write(int(w.file.Fd()), w.buff)
			nn += n
			if w.err != nil {
				return nn, w.err
			}

			w.pbuff = 0
		} else { // Buffer not full
			w.pbuff += bcopied
		}
	}

	nn += bcopied
	return nn, nil
}
Beispiel #14
0
func fileWrite(args []interface{}) interface{} {
	ensureArity(2, len(args))
	fd := args[0].(int)
	data := args[1].(string)
	syscall.Write(fd, []byte(data))
	return nil
}
Beispiel #15
0
func (su *Supervise) Pause() {
	if su.AcquireLock() == nil {
		su.WriteLog("process is not running.")
	} else {
		syscall.Write(su.ctrlPipeFd, []byte("p"))
	}
}
Beispiel #16
0
func (f *evfd) Write(p []byte) (int, error) {
	if f.magic == 0 {
		return 0, ErrClosed
	}
	var nn int
	for nn < len(p) {
		n, err := syscall.Write(f.fd, p[nn:])
		if err != nil {
			n = 0
			switch err {
			case syscall.EINTR:
				continue
			case syscall.EAGAIN:
				semacquire(&f.wsema)
				continue
			default:
				return nn, err
			}
		}
		if n == 0 {
			return nn, io.ErrClosedPipe
		}
		nn += n
	}
	return nn, nil
}
Beispiel #17
0
func (fd *netFD) Write(p []byte) (nn int, err error) {
	if err := fd.writeLock(); err != nil {
		return 0, err
	}
	defer fd.writeUnlock()
	if err := fd.pd.prepareWrite(); err != nil {
		return 0, err
	}
	for {
		var n int
		n, err = syscall.Write(fd.sysfd, p[nn:])
		if n > 0 {
			nn += n
		}
		if nn == len(p) {
			break
		}
		if err == syscall.EAGAIN {
			if err = fd.pd.waitWrite(); err == nil {
				continue
			}
		}
		if err != nil {
			break
		}
		if n == 0 {
			err = io.ErrUnexpectedEOF
			break
		}
	}
	if _, ok := err.(syscall.Errno); ok {
		err = os.NewSyscallError("write", err)
	}
	return nn, err
}
Beispiel #18
0
// write writes len(b) bytes to the File.
// It returns the number of bytes written and an error, if any.
func (f *File) write(b []byte) (n int, err error) {
	for {
		bcap := b
		if needsMaxRW && len(bcap) > maxRW {
			bcap = bcap[:maxRW]
		}
		m, err := fixCount(syscall.Write(f.fd, bcap))
		n += m

		// If the syscall wrote some data but not all (short write)
		// or it returned EINTR, then assume it stopped early for
		// reasons that are uninteresting to the caller, and try again.
		if 0 < m && m < len(bcap) || err == syscall.EINTR {
			b = b[m:]
			continue
		}

		if needsMaxRW && len(bcap) != len(b) && err == nil {
			b = b[m:]
			continue
		}

		return n, err
	}
}
Beispiel #19
0
// Write writes len(p) bytes from p to the file-descriptor.  It
// returns the number of bytes written from p (0 <= n <= len(p)) and
// any error encountered that caused the write to stop early.  Write
// returns a non-nil error if it returns n < len(p). Write is formally
// and semantically compatible with the Write method of the io.Writer
// interface. See documentation of this interface method for more
// details. In addition Write honors the timeout set by
// (*FD).SetDeadline and (*FD).SetWriteDeadline. If less than len(p)
// data are writen before the timeout expires Write returns with err
// == ErrTimeout (and n < len(p)). If the write(2) system-call returns
// 0, Write returns with err == io.ErrUnexpectedEOF.
func (fd *FD) Write(p []byte) (nn int, err error) {
	if err := fd.writeLock(); err != nil {
		return 0, err
	}
	defer fd.writeUnlock()
	if err := fd.pd.PrepareWrite(); err != nil {
		return 0, err
	}
	for {
		var n int
		n, err = syscall.Write(fd.sysfd, p[nn:])
		if err != nil {
			n = 0
			if err != syscall.EAGAIN {
				break
			}
			err = fd.pd.WaitWrite()
			if err != nil {
				break
			}
			continue
		}
		if n == 0 {
			err = io.ErrUnexpectedEOF
			break
		}
		nn += n
		if nn == len(p) {
			break
		}
	}
	return nn, err
}
Beispiel #20
0
/* Write bytes to eventfd. Will be added to the current
 * value of the internal uint64 of the eventfd().
 */
func (e *EventFD) Write(p []byte) (int, error) {
	n, err := syscall.Write(e.fd, p[:])
	if err != nil {
		return 0, err
	}
	return n, nil
}
Beispiel #21
0
func (ms *Server) systemWrite(req *request, header []byte) Status {
	if req.flatDataSize() == 0 {
		err := handleEINTR(func() error {
			_, err := syscall.Write(ms.mountFd, header)
			return err
		})
		return ToStatus(err)
	}

	if req.fdData != nil {
		if ms.canSplice {
			err := ms.trySplice(header, req, req.fdData)
			if err == nil {
				req.readResult.Done()
				return OK
			}
			log.Println("trySplice:", err)
		}

		sz := req.flatDataSize()
		buf := ms.allocOut(req, uint32(sz))
		req.flatData, req.status = req.fdData.Bytes(buf)
		header = req.serializeHeader(len(req.flatData))
	}

	_, err := writev(ms.mountFd, [][]byte{header, req.flatData})
	if req.readResult != nil {
		req.readResult.Done()
	}
	return ToStatus(err)
}
Beispiel #22
0
/*
	c.sa = new(syscall.SockaddrInet4)
	c.sa.Addr = [4]byte{10, 1, 1, 131}
	c.sa.Port = port
*/
func (c *Worker) socket() {
	begin := time.Now()
	s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
	if err != nil {
		syscall.Close(s)
		return
	}

	err = syscall.Connect(s, nil) //TODO
	if err != nil {
		lg(err)
		syscall.Close(s)
		return
	}

	_, err = syscall.Write(s, message.content)
	if err != nil {
		syscall.Close(s)
		return
	}

	_, err = syscall.Read(s, c.data)
	if err != nil {
		syscall.Close(s)
		return
	}

	syscall.Close(s)
	time.Now().Sub(begin)
}
Beispiel #23
0
// ReadPassword reads a line of input from a terminal without local echo.  This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
func ReadPassword(prompt string, fd int) ([]byte, error) {
	if IsTerminal(fd) {
		var oldState syscall.Termios
		if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0); err != 0 {
			return nil, err
		}

		newState := oldState
		newState.Lflag &^= syscall.ECHO
		newState.Lflag |= syscall.ICANON | syscall.ISIG
		newState.Iflag |= syscall.ICRNL
		if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 {
			return nil, err
		}

		defer func() {
			syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlWriteTermios, uintptr(unsafe.Pointer(&oldState)), 0, 0, 0)
			syscall.Write(fd, []byte("\n"))
		}()

		syscall.Write(fd, []byte(prompt))
	}

	var buf [16]byte
	var ret []byte
	for {
		n, err := syscall.Read(fd, buf[:])
		if err != nil {
			return nil, err
		}
		if n == 0 {
			if len(ret) == 0 {
				return nil, io.EOF
			}
			break
		}
		if buf[n-1] == '\n' {
			n--
		}
		ret = append(ret, buf[:n]...)
		if n < len(buf) {
			break
		}
	}

	return ret, nil
}
Beispiel #24
0
// write writes len(b) bytes to the File.
// It returns the number of bytes written and an error, if any.
func (f *File) write(b []byte) (n int, err error) {
	f.l.Lock()
	defer f.l.Unlock()
	if f.isConsole {
		return f.writeConsole(b)
	}
	return syscall.Write(f.fd, b)
}
Beispiel #25
0
func writev(u U, a []uint64) uint64 {
	fd, iov, count := int(a[0]), a[1], a[2]
	for vec := range iovecIter(u.Mem().StreamAt(iov), count, int(u.Bits()), u.ByteOrder()) {
		data, _ := u.MemRead(vec.Base, vec.Len)
		syscall.Write(fd, data)
	}
	return 0
}
Beispiel #26
0
func (self Fdset) WriteWait(fd int) error {
	ch := make(chan error)
	go func() {
		self.wListener[fd] = fdChan(ch)
		syscall.Write(self.ctl, []byte{2})
	}()
	return <-ch
}
Beispiel #27
0
func (sc *selectCtx) Notify() {
	// Write 1 byte, don't care what
	_, err := syscall.Write(sc.pfdw, sc.b)
	// Don't care if it fails with EAGAIN
	if err != nil && err != syscall.EAGAIN {
		log.Panicf("poller: Cannot notify select: %s", err.Error())
	}
}
Beispiel #28
0
// write writes bytes b to the target program's file descriptor fd.
// The print/println built-ins and the write() system call funnel
// through here so they can be captured by the test driver.
func write(fd int, b []byte) (int, error) {
	if CapturedOutput != nil && (fd == 1 || fd == 2) {
		capturedOutputMu.Lock()
		CapturedOutput.Write(b) // ignore errors
		capturedOutputMu.Unlock()
	}
	return syscall.Write(fd, b)
}
Beispiel #29
0
func printstr(s string) {
	if utf8out {
		syscall.Write(syscall.Stdout, []byte(s))
	} else if oc != nil {
		oc.Write([]byte(s))
	} else {
		os.Stdout.WriteString(s)
	}
}
func ext۰syscall۰Write(fn *ssa.Function, args []value) value {
	p := args[1].([]value)
	b := make([]byte, 0, len(p))
	for i := range p {
		b = append(b, p[i].(byte))
	}
	n, err := syscall.Write(args[0].(int), b)
	return tuple{n, wrapError(err)}
}