// mmap memory maps a DB's data file. // Based on: https://github.com/edsrzf/mmap-go func mmap(db *DB, sz int) error { if !db.readOnly { // Truncate the database to the size of the mmap. if err := db.file.Truncate(int64(sz)); err != nil { return fmt.Errorf("truncate: %s", err) } } // Open a file mapping handle. sizelo := uint32(sz >> 32) sizehi := uint32(sz) & 0xffffffff h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil) if h == 0 { return os.NewSyscallError("CreateFileMapping", errno) } // Create the memory map. addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) if addr == 0 { return os.NewSyscallError("MapViewOfFile", errno) } // Close mapping handle. if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { return os.NewSyscallError("CloseHandle", err) } // Convert to a byte array. db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr))) db.datasz = sz return nil }
// NewLiner initializes a new *State, and sets the terminal into raw mode. To // restore the terminal to its previous state, call State.Close(). func NewLiner() *State { var s State hIn, _, _ := procGetStdHandle.Call(uintptr(std_input_handle)) s.handle = syscall.Handle(hIn) hOut, _, _ := procGetStdHandle.Call(uintptr(std_output_handle)) s.hOut = syscall.Handle(hOut) s.terminalSupported = true if m, err := TerminalMode(); err == nil { s.origMode = m.(inputMode) mode := s.origMode mode &^= enableEchoInput mode &^= enableInsertMode mode &^= enableLineInput mode &^= enableMouseInput mode |= enableWindowInput mode.ApplyMode() } else { s.inputRedirected = true s.r = bufio.NewReader(os.Stdin) } s.getColumns() s.outputRedirected = s.columns <= 0 return &s }
func (file *file) close() error { if file == nil { return syscall.EINVAL } if file.isdir() && file.dirinfo.isempty { // "special" empty directories return nil } if file.fd == syscall.InvalidHandle { return syscall.EINVAL } var e error if file.isdir() { e = syscall.FindClose(syscall.Handle(file.fd)) } else { e = syscall.CloseHandle(syscall.Handle(file.fd)) } var err error if e != nil { err = &PathError{"close", file.name, e} } file.fd = syscall.InvalidHandle // so it can't be closed again // no need for a finalizer anymore runtime.SetFinalizer(file, nil) return err }
func TtyReady() error { var err error _stdin, err := os.Open("CONIN$") if err != nil { return err } _stdout, err := os.Open("CONOUT$") if err != nil { return err } stdin = os.Stdin stdout = os.Stdout os.Stdin = _stdin os.Stdout = _stdout syscall.Stdin = syscall.Handle(os.Stdin.Fd()) err = setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin) if err != nil { return err } syscall.Stdout = syscall.Handle(os.Stdout.Fd()) err = setStdHandle(syscall.STD_OUTPUT_HANDLE, syscall.Stdout) if err != nil { return err } return nil }
func (process *jobProcess) Wait() (int, error) { s, e := syscall.WaitForSingleObject(syscall.Handle(process.processHandle), syscall.INFINITE) switch s { case syscall.WAIT_OBJECT_0: break case syscall.WAIT_FAILED: return -1, os.NewSyscallError("WaitForSingleObject", e) default: return -1, errors.New("os: unexpected result from WaitForSingleObject") } var ec uint32 e = syscall.GetExitCodeProcess(syscall.Handle(process.processHandle), &ec) if e != nil { return -1, os.NewSyscallError("GetExitCodeProcess", e) } var u syscall.Rusage e = syscall.GetProcessTimes(syscall.Handle(process.processHandle), &u.CreationTime, &u.ExitTime, &u.KernelTime, &u.UserTime) if e != nil { return -1, os.NewSyscallError("GetProcessTimes", e) } // NOTE(brainman): It seems that sometimes process is not dead // when WaitForSingleObject returns. But we do not know any // other way to wait for it. Sleeping for a while seems to do // the trick sometimes. So we will sleep and smell the roses. defer time.Sleep(5 * time.Millisecond) defer syscall.CloseHandle(syscall.Handle(process.processHandle)) return int(ec), nil }
func openSCManager() (syscall.Handle, error) { r0, _, e1 := openSCManagerProc.Call(uintptr(0), uintptr(0), uintptr(uint32(_SC_MANAGER_ALL_ACCESS))) if r0 == 0 { return syscall.Handle(0), e1 } return syscall.Handle(r0), nil }
func XAudio2Create(ppXAudio2 **IXAudio2) (ret int32) { libole32, _ := syscall.LoadLibrary("ole32.dll") ptrcoInitializeEx, _ = syscall.GetProcAddress(syscall.Handle(libole32), "CoInitializeEx") ptrcoCreateInstance, _ = syscall.GetProcAddress(syscall.Handle(libole32), "CoCreateInstance") coInitializeEx(nil, 0) // XAudio 2.7 GUIDs clsid := guid{0x5a508685, 0xa254, 0x4fba, [8]byte{0x9b, 0x82, 0x9a, 0x24, 0xb0, 0x03, 0x06, 0xaf}} iid := guid{0x8bcf1f58, 0x9fe7, 0x4583, [8]byte{0x8a, 0xc6, 0xe2, 0xad, 0xc4, 0x65, 0xc8, 0xbb}} var com unsafe.Pointer ret = coCreateInstance(&clsid, nil, 1, &iid, &com) if ret < 0 { return } pXAudio2 := (*IXAudio2)(com) ret = pXAudio2.Initialize(0, 0xffffffff) if ret < 0 { pXAudio2.Release() return } *ppXAudio2 = pXAudio2 return }
func openService(scManager syscall.Handle, serviceName string) (syscall.Handle, error) { r0, _, e1 := openServiceProc.Call(uintptr(scManager), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(serviceName))), uintptr(uint32(_SC_MANAGER_ALL_ACCESS))) if r0 == 0 { return syscall.Handle(0), e1 } return syscall.Handle(r0), nil }
func mmapFile(f *os.File) mmapData { st, err := f.Stat() if err != nil { log.Fatal(err) } size := st.Size() if int64(int(size+4095)) != size+4095 { log.Fatalf("%s: too large for mmap", f.Name()) } if size == 0 { return mmapData{f, nil, nil} } h, err := syscall.CreateFileMapping(syscall.Handle(f.Fd()), nil, syscall.PAGE_READONLY, uint32(size>>32), uint32(size), nil) if err != nil { log.Fatalf("CreateFileMapping %s: %v", f.Name(), err) } defer syscall.CloseHandle(syscall.Handle(h)) addr, err := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, 0) if err != nil { log.Fatalf("MapViewOfFile %s: %v", f.Name(), err) } data := (*[1 << 30]byte)(unsafe.Pointer(addr)) return mmapData{f, data[:size], data[:]} }
func (p *Process) wait() (ps *ProcessState, err error) { handle := atomic.LoadUintptr(&p.handle) s, e := syscall.WaitForSingleObject(syscall.Handle(handle), syscall.INFINITE) switch s { case syscall.WAIT_OBJECT_0: break case syscall.WAIT_FAILED: return nil, NewSyscallError("WaitForSingleObject", e) default: return nil, errors.New("os: unexpected result from WaitForSingleObject") } var ec uint32 e = syscall.GetExitCodeProcess(syscall.Handle(handle), &ec) if e != nil { return nil, NewSyscallError("GetExitCodeProcess", e) } var u syscall.Rusage e = syscall.GetProcessTimes(syscall.Handle(handle), &u.CreationTime, &u.ExitTime, &u.KernelTime, &u.UserTime) if e != nil { return nil, NewSyscallError("GetProcessTimes", e) } p.setDone() // NOTE(brainman): It seems that sometimes process is not dead // when WaitForSingleObject returns. But we do not know any // other way to wait for it. Sleeping for a while seems to do // the trick sometimes. So we will sleep and smell the roses. defer time.Sleep(5 * time.Millisecond) defer p.Release() return &ProcessState{p.Pid, syscall.WaitStatus{ExitCode: ec}, &u}, nil }
func getTuntapComponentId() (string, error) { adapters, err := registry.OpenKey(registry.LOCAL_MACHINE, ADAPTER_KEY, registry.READ) if err != nil { return "", err } var i uint32 for ; i < 1000; i++ { var name_length uint32 = TAPWIN32_MAX_REG_SIZE buf := make([]uint16, name_length) if err = syscall.RegEnumKeyEx( syscall.Handle(adapters), i, &buf[0], &name_length, nil, nil, nil, nil); err != nil { return "", err } key_name := syscall.UTF16ToString(buf[:]) adapter, err := registry.OpenKey(adapters, key_name, registry.READ) if err != nil { return "", err } name := syscall.StringToUTF16("ComponentId") name2 := syscall.StringToUTF16("NetCfgInstanceId") var valtype uint32 var component_id = make([]byte, TAPWIN32_MAX_REG_SIZE) var componentLen = uint32(len(component_id)) if err = syscall.RegQueryValueEx( syscall.Handle(adapter), &name[0], nil, &valtype, &component_id[0], &componentLen); err != nil { return "", err } if unicodeTostring(component_id) == TUNTAP_COMPONENT_ID { var valtype uint32 var netCfgInstanceId = make([]byte, TAPWIN32_MAX_REG_SIZE) var netCfgInstanceIdLen = uint32(len(netCfgInstanceId)) if err = syscall.RegQueryValueEx( syscall.Handle(adapter), &name2[0], nil, &valtype, &netCfgInstanceId[0], &netCfgInstanceIdLen); err != nil { return "", err } fmt.Println("Device:", unicodeTostring(netCfgInstanceId)) return unicodeTostring(netCfgInstanceId), nil } } return "", errors.New("not found component id") }
func setupCommMapping(cmd *exec.Cmd, comm *Mapping, rOut, wIn *os.File) { syscall.SetHandleInformation(syscall.Handle(comm.mapping), syscall.HANDLE_FLAG_INHERIT, 1) syscall.SetHandleInformation(syscall.Handle(rOut.Fd()), syscall.HANDLE_FLAG_INHERIT, 1) syscall.SetHandleInformation(syscall.Handle(wIn.Fd()), syscall.HANDLE_FLAG_INHERIT, 1) cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_COMM_FD=%v", comm.mapping)) cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_IN_FD=%v", rOut.Fd())) cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_OUT_FD=%v", wIn.Fd())) }
func TtyTerm() { os.Stdin = stdin syscall.Stdin = syscall.Handle(os.Stdin.Fd()) setStdHandle(syscall.STD_INPUT_HANDLE, syscall.Stdin) os.Stdout = stdout syscall.Stdout = syscall.Handle(os.Stdout.Fd()) setStdHandle(syscall.STD_OUTPUT_HANDLE, syscall.Stdout) }
func registerEventSource(title string) (syscall.Handle, error) { r0, _, e1 := registerEventSourceProc.Call( 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(title)))) if r0 == 0 { return syscall.Handle(0), e1 } return syscall.Handle(r0), nil }
func init() { var nStdHandle = -11 kernel32, _ = syscall.LoadLibrary("Kernel32.dll") GetStdHandle, _ = syscall.GetProcAddress(syscall.Handle(kernel32), "GetStdHandle") SetConsoleTextAttribute, _ = syscall.GetProcAddress(syscall.Handle(kernel32), "SetConsoleTextAttribute") // ReadConsoleOutputAttribute, _ := syscall.GetProcAddress(syscall.Handle(kernel32), "ReadConsoleOutputAttribute") GetConsoleScreenBufferInfo, _ = syscall.GetProcAddress(syscall.Handle(kernel32), "GetConsoleScreenBufferInfo") hnd, _, _ = syscall.Syscall(uintptr(GetStdHandle), 1, uintptr(nStdHandle), 0, 0) }
func FileConn(f *os.File) (net.Conn, error) { err := getNamedPipeInfo(syscall.Handle(f.Fd()), nil, nil, nil, nil) if err != nil { return nil, err } return &PipeConn{ addr: PipeAddr(f.Name()), handle: syscall.Handle(f.Fd()), }, nil }
func (k Key) setValue(name string, valtype uint32, data []byte) error { p, err := syscall.UTF16PtrFromString(name) if err != nil { return err } if len(data) == 0 { return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0) } return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data))) }
func FindWindow(lpClassName, lpWindowName *uint16) (syscall.Handle, error) { ret, _, err := syscall.Syscall(findWindow, 2, uintptr(unsafe.Pointer(lpClassName)), uintptr(unsafe.Pointer(lpWindowName)), 0) if err > 0 || ret == 0 { return syscall.Handle(ret), errors.New("pgagent not found") } return syscall.Handle(ret), nil }
func LocalFree(mem syscall.Handle) (syscall.Handle, error) { // LocalFree returns NULL to indicate success! r1, _, e1 := syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) if r1 != 0 { if e1 != 0 { return syscall.Handle(r1), e1 } else { return syscall.Handle(r1), syscall.EINVAL } } return 0, nil }
func createEvent() (syscall.Handle, error) { r0, _, e0 := syscall.Syscall6(procCreateEvent.Addr(), 4, 0, 0, 0, 0, 0, 0) if r0 == 0 { return 0, syscall.Errno(e0) } return syscall.Handle(r0), nil }
// NewFile returns a new File with the given file descriptor and name. func NewFile(fd uintptr, name string) *File { h := syscall.Handle(fd) if h == syscall.InvalidHandle { return nil } return newFile(h, name) }
func enableCurrentThreadPrivilege(privilegeName string) error { ct, err := windows.GetCurrentThread() if err != nil { return err } var t syscall.Token err = windows.OpenThreadToken(ct, syscall.TOKEN_QUERY|windows.TOKEN_ADJUST_PRIVILEGES, false, &t) if err != nil { return err } defer syscall.CloseHandle(syscall.Handle(t)) var tp windows.TOKEN_PRIVILEGES privStr, err := syscall.UTF16PtrFromString(privilegeName) if err != nil { return err } err = windows.LookupPrivilegeValue(nil, privStr, &tp.Privileges[0].Luid) if err != nil { return err } tp.PrivilegeCount = 1 tp.Privileges[0].Attributes = windows.SE_PRIVILEGE_ENABLED return windows.AdjustTokenPrivileges(t, false, &tp, 0, nil, nil) }
func (pr passwordReader) PromptForPassword(promptText string, args ...interface{}) (passwd string) { hStdin := syscall.Handle(os.Stdin.Fd()) var originalMode uint32 err := syscall.GetConsoleMode(hStdin, &originalMode) if err != nil { return } var newMode uint32 = (originalMode &^ ENABLE_ECHO_INPUT) err = setConsoleMode(hStdin, newMode) defer setConsoleMode(hStdin, originalMode) if err != nil { return } // Display the prompt. fmt.Printf(promptText+": ", args...) defer fmt.Println("") rd := bufio.NewReader(os.Stdin) line, err := rd.ReadString('\r') if err == nil { return strings.TrimSpace(line) } return "" }
// Stat returns the FileInfo structure describing file. // If there is an error, it will be of type *PathError. func (file *File) Stat() (fi FileInfo, err error) { if file == nil || file.fd < 0 { return nil, syscall.EINVAL } if file.isdir() { // I don't know any better way to do that for directory return Stat(file.name) } if file.name == DevNull { return &devNullStat, nil } var d syscall.ByHandleFileInformation e := syscall.GetFileInformationByHandle(syscall.Handle(file.fd), &d) if e != nil { return nil, &PathError{"GetFileInformationByHandle", file.name, e} } return &fileStat{ name: basename(file.name), sys: syscall.Win32FileAttributeData{ FileAttributes: d.FileAttributes, CreationTime: d.CreationTime, LastAccessTime: d.LastAccessTime, LastWriteTime: d.LastWriteTime, FileSizeHigh: d.FileSizeHigh, FileSizeLow: d.FileSizeLow, }, vol: d.VolumeSerialNumber, idxhi: d.FileIndexHigh, idxlo: d.FileIndexLow, }, nil }
// sendFile copies the contents of r to c using the TransmitFile // system call to minimize copies. // // if handled == true, sendFile returns the number of bytes copied and any // non-EOF error. // // if handled == false, sendFile performed no work. // // Note that sendfile for windows does not suppport >2GB file. func sendFile(fd *netFD, r io.Reader) (written int64, err error, handled bool) { var n int64 = 0 // by default, copy until EOF lr, ok := r.(*io.LimitedReader) if ok { n, r = lr.N, lr.R if n <= 0 { return 0, nil, true } } f, ok := r.(*os.File) if !ok { return 0, nil, false } if err := fd.writeLock(); err != nil { return 0, err, true } defer fd.writeUnlock() o := &fd.wop o.qty = uint32(n) o.handle = syscall.Handle(f.Fd()) done, err := wsrv.ExecIO(o, "TransmitFile", func(o *operation) error { return syscall.TransmitFile(o.fd.sysfd, o.handle, o.qty, 0, &o.o, nil, syscall.TF_WRITE_BEHIND) }) if err != nil { return 0, err, false } if lr != nil { lr.N -= int64(done) } return int64(done), nil, true }
func (s *winSys) loadFileId() error { if s.path == "" { // already done return nil } s.Lock() defer s.Unlock() pathp, e := syscall.UTF16PtrFromString(s.path) if e != nil { return e } h, e := syscall.CreateFile(pathp, 0, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) if e != nil { return e } defer syscall.CloseHandle(h) var i syscall.ByHandleFileInformation e = syscall.GetFileInformationByHandle(syscall.Handle(h), &i) if e != nil { return e } s.path = "" s.vol = i.VolumeSerialNumber s.idxhi = i.FileIndexHigh s.idxlo = i.FileIndexLow return nil }
func getProcessEntry(pid int) (pe *processEntry32, err error) { snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) if snapshot == uintptr(syscall.InvalidHandle) { err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) return } defer syscall.CloseHandle(syscall.Handle(snapshot)) var processEntry processEntry32 processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) if ok == 0 { err = fmt.Errorf("Process32First: %v", e1) return } for { if processEntry.th32ProcessID == uint32(pid) { pe = &processEntry return } ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) if ok == 0 { err = fmt.Errorf("Process32Next: %v", e1) return } } }
func initScreenWindow() (err error) { swc, err := syscall.UTF16PtrFromString(screenWindowClass) if err != nil { return err } emptyString, err := syscall.UTF16PtrFromString("") if err != nil { return err } wc := _WNDCLASS{ LpszClassName: swc, LpfnWndProc: syscall.NewCallback(screenWindowWndProc), HIcon: hDefaultIcon, HCursor: hDefaultCursor, HInstance: hThisInstance, HbrBackground: syscall.Handle(_COLOR_BTNFACE + 1), } _, err = _RegisterClass(&wc) if err != nil { return err } screenHWND, err = _CreateWindowEx(0, swc, emptyString, _WS_OVERLAPPEDWINDOW, _CW_USEDEFAULT, _CW_USEDEFAULT, _CW_USEDEFAULT, _CW_USEDEFAULT, _HWND_MESSAGE, 0, hThisInstance, 0) if err != nil { return err } return nil }
func init() { // Library libkernel32 = MustLoadLibrary("kernel32.dll") // Functions closeHandle = MustGetProcAddress(libkernel32, "CloseHandle") fileTimeToSystemTime = MustGetProcAddress(libkernel32, "FileTimeToSystemTime") getConsoleTitle = MustGetProcAddress(libkernel32, "GetConsoleTitleW") getConsoleWindow = MustGetProcAddress(libkernel32, "GetConsoleWindow") getLastError = MustGetProcAddress(libkernel32, "GetLastError") getLocaleInfo = MustGetProcAddress(libkernel32, "GetLocaleInfoW") getLogicalDriveStrings = MustGetProcAddress(libkernel32, "GetLogicalDriveStringsW") getModuleHandle = MustGetProcAddress(libkernel32, "GetModuleHandleW") getNumberFormat = MustGetProcAddress(libkernel32, "GetNumberFormatW") getProfileString = MustGetProcAddress(libkernel32, "GetProfileStringW") getThreadLocale = MustGetProcAddress(libkernel32, "GetThreadLocale") getThreadUILanguage, _ = syscall.GetProcAddress(syscall.Handle(libkernel32), "GetThreadUILanguage") getVersion = MustGetProcAddress(libkernel32, "GetVersion") globalAlloc = MustGetProcAddress(libkernel32, "GlobalAlloc") globalFree = MustGetProcAddress(libkernel32, "GlobalFree") globalLock = MustGetProcAddress(libkernel32, "GlobalLock") globalUnlock = MustGetProcAddress(libkernel32, "GlobalUnlock") moveMemory = MustGetProcAddress(libkernel32, "RtlMoveMemory") mulDiv = MustGetProcAddress(libkernel32, "MulDiv") setLastError = MustGetProcAddress(libkernel32, "SetLastError") systemTimeToFileTime = MustGetProcAddress(libkernel32, "SystemTimeToFileTime") }
func getModuleHandle() (syscall.Handle, error) { ret, _, err := pGetModuleHandleW.Call(uintptr(0)) if ret == 0 { return 0, err } return syscall.Handle(ret), nil }