github.com/camlistore/go4@v0.0.0-20200104003542-c7e774b10ea0/osutil/exec_windows.go (about) 1 /* 2 Copyright 2015 The go4 Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package osutil 18 19 import ( 20 "path/filepath" 21 "syscall" 22 "unsafe" 23 ) 24 25 var ( 26 modkernel32 = syscall.MustLoadDLL("kernel32.dll") 27 procGetModuleFileNameW = modkernel32.MustFindProc("GetModuleFileNameW") 28 ) 29 30 func getModuleFileName(handle syscall.Handle) (string, error) { 31 n := uint32(1024) 32 var buf []uint16 33 for { 34 buf = make([]uint16, n) 35 r, err := syscallGetModuleFileName(handle, &buf[0], n) 36 if err != nil { 37 return "", err 38 } 39 if r < n { 40 break 41 } 42 // r == n means n not big enough 43 n += 1024 44 } 45 return syscall.UTF16ToString(buf), nil 46 } 47 48 func executable() (string, error) { 49 p, err := getModuleFileName(0) 50 return filepath.Clean(p), err 51 } 52 53 func syscallGetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) { 54 r0, _, e1 := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, uintptr(module), uintptr(unsafe.Pointer(fn)), uintptr(len)) 55 n = uint32(r0) 56 if n == 0 { 57 if e1 != 0 { 58 err = error(e1) 59 } else { 60 err = syscall.EINVAL 61 } 62 } 63 return 64 }