1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/os/os_windows.c.v

360 lines
9.6 KiB
V
Raw Normal View History

module os
2020-02-03 06:01:39 +03:00
import strings
#flag -lws2_32
#include <winsock2.h>
2019-10-24 12:36:57 +03:00
pub const (
2019-10-12 22:18:19 +03:00
path_separator = '\\'
2019-09-14 23:48:30 +03:00
)
2019-07-16 02:57:03 +03:00
// Ref - https://docs.microsoft.com/en-us/windows/desktop/winprog/windows-data-types
// A handle to an object.
2020-02-09 17:40:32 +03:00
pub type HANDLE voidptr
2019-08-17 16:17:43 +03:00
// win: FILETIME
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime
struct Filetime {
2019-08-17 16:17:43 +03:00
dwLowDateTime u32
dwHighDateTime u32
}
// win: WIN32_FIND_DATA
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-_win32_find_dataw
struct Win32finddata {
2019-08-17 16:17:43 +03:00
mut:
dwFileAttributes u32
2019-09-29 04:16:15 +03:00
ftCreationTime Filetime
ftLastAccessTime Filetime
ftLastWriteTime Filetime
2019-08-17 16:17:43 +03:00
nFileSizeHigh u32
nFileSizeLow u32
dwReserved0 u32
dwReserved1 u32
2019-09-14 23:48:30 +03:00
cFileName [260]u16 // MAX_PATH = 260
2019-08-17 16:17:43 +03:00
cAlternateFileName [14]u16 // 14
dwFileType u32
dwCreatorType u32
wFinderFlags u16
}
2019-11-07 16:01:17 +03:00
struct ProcessInformation {
mut:
hProcess voidptr
hThread voidptr
dwProcessId u32
dwThreadId u32
}
struct StartupInfo {
mut:
2019-11-07 16:01:17 +03:00
cb u32
lpReserved &u16
lpDesktop &u16
lpTitle &u16
dwX u32
dwY u32
dwXSize u32
dwYSize u32
dwXCountChars u32
dwYCountChars u32
dwFillAttribute u32
dwFlags u32
wShowWindow u16
cbReserved2 u16
lpReserved2 byteptr
hStdInput voidptr
hStdOutput voidptr
hStdError voidptr
}
struct SecurityAttributes {
mut:
nLength u32
lpSecurityDescriptor voidptr
bInheritHandle bool
}
2019-08-17 16:17:43 +03:00
fn init_os_args_wide(argc int, argv &byteptr) []string {
2020-04-26 14:49:31 +03:00
mut args := []string{}
for i in 0..argc {
args << string_from_wide(&u16(argv[i]))
2019-09-14 23:48:30 +03:00
}
return args
}
2019-10-17 14:30:05 +03:00
pub fn ls(path string) ?[]string {
mut find_file_data := Win32finddata{}
2020-04-26 14:49:31 +03:00
mut dir_files := []string{}
// We can also check if the handle is valid. but using is_dir instead
2019-08-16 15:05:11 +03:00
// h_find_dir := C.FindFirstFile(path.str, &find_file_data)
// if (INVALID_HANDLE_VALUE == h_find_dir) {
// return dir_files
// }
// C.FindClose(h_find_dir)
if !is_dir(path) {
2019-11-02 22:37:29 +03:00
return error('ls() couldnt open dir "$path": directory does not exist')
2019-08-16 15:05:11 +03:00
}
// NOTE: Should eventually have path struct & os dependant path seperator (eg os.PATH_SEPERATOR)
// we need to add files to path eg. c:\windows\*.dll or :\windows\*
2019-09-14 23:48:30 +03:00
path_files := '$path\\*'
2019-08-16 15:05:11 +03:00
// NOTE:TODO: once we have a way to convert utf16 wide character to utf8
// we should use FindFirstFileW and FindNextFileW
2019-11-16 02:30:50 +03:00
h_find_files := C.FindFirstFile(path_files.to_wide(), voidptr(&find_file_data))
2019-08-16 15:05:11 +03:00
first_filename := string_from_wide(&u16(find_file_data.cFileName))
if first_filename != '.' && first_filename != '..' {
dir_files << first_filename
}
2020-03-28 12:19:38 +03:00
for C.FindNextFile(h_find_files, voidptr(&find_file_data)) > 0 {
2019-08-16 15:05:11 +03:00
filename := string_from_wide(&u16(find_file_data.cFileName))
if filename != '.' && filename != '..' {
dir_files << filename.clone()
}
}
C.FindClose(h_find_files)
return dir_files
2019-09-14 23:48:30 +03:00
}
2019-08-16 15:05:11 +03:00
/*
pub fn is_dir(path string) bool {
2019-08-17 16:17:43 +03:00
_path := path.replace('/', '\\')
2019-11-16 02:30:50 +03:00
attr := C.GetFileAttributesW(_path.to_wide())
if int(attr) == int(C.INVALID_FILE_ATTRIBUTES) {
2019-08-17 16:17:43 +03:00
return false
}
2019-11-16 02:30:50 +03:00
if (int(attr) & C.FILE_ATTRIBUTE_DIRECTORY) != 0 {
2019-08-17 16:17:43 +03:00
return true
}
return false
2019-09-14 23:48:30 +03:00
}
*/
2019-08-17 16:17:43 +03:00
2019-12-31 10:53:53 +03:00
pub fn open(path string) ?File {
2020-04-02 14:24:23 +03:00
mode := 'rb'
2020-02-23 22:46:13 +03:00
file := File {
2020-04-02 14:24:23 +03:00
cfile: C._wfopen(path.to_wide(), mode.to_wide())
2020-02-23 22:46:13 +03:00
opened: true
2019-12-31 10:53:53 +03:00
}
if isnil(file.cfile) {
return error('failed to open file "$path"')
}
return file
}
// create creates a file at a specified location and returns a writable `File` object.
pub fn create(path string) ?File {
2020-04-02 14:24:23 +03:00
mode := 'wb'
2020-02-23 22:46:13 +03:00
file := File {
2020-04-02 14:24:23 +03:00
cfile: C._wfopen(path.to_wide(), mode.to_wide())
2019-12-31 10:53:53 +03:00
opened: true
}
if isnil(file.cfile) {
return error('failed to create file "$path"')
}
return file
}
pub fn (f mut File) write(s string) {
if !f.opened {
return
}
C.fputs(s.str, f.cfile)
}
pub fn (f mut File) writeln(s string) {
if !f.opened {
return
}
// TODO perf
C.fputs(s.str, f.cfile)
C.fputs('\n', f.cfile)
}
2019-11-25 04:35:41 +03:00
2019-11-23 21:40:32 +03:00
2019-08-17 16:17:43 +03:00
// mkdir creates a new directory with the specified path.
2019-11-23 19:55:18 +03:00
pub fn mkdir(path string) ?bool {
if path == '.' { return true }
2020-03-20 18:41:18 +03:00
apath := os.real_path( path )
2019-11-23 21:40:32 +03:00
if !C.CreateDirectory(apath.to_wide(), 0) {
2019-11-23 19:55:18 +03:00
return error('mkdir failed for "$apath", because CreateDirectory returned ' + get_error_msg(int(C.GetLastError())))
2019-08-17 16:17:43 +03:00
}
2019-11-23 21:40:32 +03:00
return true
2019-09-14 23:48:30 +03:00
}
2019-08-17 16:17:43 +03:00
2019-07-14 23:59:25 +03:00
// Ref - https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=vs-2019
// get_file_handle retrieves the operating-system file handle that is associated with the specified file descriptor.
pub fn get_file_handle(path string) HANDLE {
mode := 'rb'
2019-07-24 13:16:45 +03:00
_fd := C._wfopen(path.to_wide(), mode.to_wide())
2019-07-14 23:59:25 +03:00
if _fd == 0 {
return HANDLE(INVALID_HANDLE_VALUE)
}
2019-11-16 02:30:50 +03:00
_handle := HANDLE(C._get_osfhandle(C._fileno(_fd))) // CreateFile? - hah, no -_-
return _handle
}
2019-07-14 23:59:25 +03:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
2019-09-14 23:48:30 +03:00
// get_module_filename retrieves the fully qualified path for the file that contains the specified module.
2019-07-14 23:59:25 +03:00
// The module must have been loaded by the current process.
pub fn get_module_filename(handle HANDLE) ?string {
2020-02-22 14:41:24 +03:00
unsafe {
mut sz := 4096 // Optimized length
mut buf := &u16(malloc(4096))
for {
status := int(C.GetModuleFileNameW(handle, voidptr(&buf), sz))
match status {
2020-04-02 15:00:28 +03:00
success {
2020-02-22 14:41:24 +03:00
_filename := string_from_wide2(buf, sz)
return _filename
}
else {
// Must handled with GetLastError and converted by FormatMessage
return error('Cannot get file name from handle')
}
}
}
}
panic('this should be unreachable') // TODO remove unreachable after loop
2019-07-14 23:59:25 +03:00
}
2019-07-15 20:30:40 +03:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagea#parameters
const (
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000
FORMAT_MESSAGE_FROM_HMODULE = 0x00000800
FORMAT_MESSAGE_FROM_STRING = 0x00000400
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
)
// Ref - winnt.h
const (
SUBLANG_NEUTRAL = 0x00
SUBLANG_DEFAULT = 0x01
LANG_NEUTRAL = (SUBLANG_NEUTRAL)
2019-09-14 23:48:30 +03:00
)
2019-07-15 20:30:40 +03:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--12000-15999-
const (
MAX_ERROR_CODE = 15841 // ERROR_API_UNAVAILABLE
)
2019-09-14 23:48:30 +03:00
// ptr_win_get_error_msg return string (voidptr)
// representation of error, only for windows.
fn ptr_win_get_error_msg(code u32) voidptr {
2019-07-15 20:30:40 +03:00
mut buf := voidptr(0)
// Check for code overflow
if code > u32(MAX_ERROR_CODE) {
return buf
}
2019-07-15 20:30:40 +03:00
C.FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
2019-11-16 02:30:50 +03:00
0, code, C.MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), voidptr(&buf), 0, 0)
2019-07-15 20:30:40 +03:00
return buf
}
// get_error_msg return error code representation in string.
pub fn get_error_msg(code int) string {
if code < 0 { // skip negative
return ''
}
_ptr_text := ptr_win_get_error_msg(u32(code))
if _ptr_text == 0 { // compare with null
return ''
}
2019-10-26 14:58:05 +03:00
return string_from_wide(_ptr_text)
2019-07-29 19:21:36 +03:00
}
2019-11-07 16:01:17 +03:00
// exec starts the specified command, waits for it to complete, and returns its output.
pub fn exec(cmd string) ?Result {
if cmd.contains(';') || cmd.contains('&&') || cmd.contains('||') || cmd.contains('\n') {
return error(';, &&, || and \\n are not allowed in shell commands')
}
mut child_stdin := &u32(0)
mut child_stdout_read := &u32(0)
mut child_stdout_write := &u32(0)
mut sa := SecurityAttributes {}
sa.nLength = sizeof(C.SECURITY_ATTRIBUTES)
sa.bInheritHandle = true
2019-11-23 21:40:32 +03:00
create_pipe_ok := C.CreatePipe(voidptr(&child_stdout_read),
voidptr(&child_stdout_write), voidptr(&sa), 0)
if !create_pipe_ok {
2019-11-07 16:01:17 +03:00
error_msg := get_error_msg(int(C.GetLastError()))
return error('exec failed (CreatePipe): $error_msg')
}
2019-11-23 21:40:32 +03:00
set_handle_info_ok := C.SetHandleInformation(child_stdout_read, C.HANDLE_FLAG_INHERIT, 0)
if !set_handle_info_ok {
2019-11-07 16:01:17 +03:00
error_msg := get_error_msg(int(C.GetLastError()))
panic('exec failed (SetHandleInformation): $error_msg')
}
proc_info := ProcessInformation{}
2020-04-04 12:59:25 +03:00
start_info := StartupInfo{
lpReserved: 0
lpDesktop: 0
lpTitle: 0
cb: sizeof(C.PROCESS_INFORMATION)
hStdInput: child_stdin
hStdOutput: child_stdout_write
hStdError: child_stdout_write
dwFlags: u32(C.STARTF_USESTDHANDLES)
}
2019-11-07 16:01:17 +03:00
command_line := [32768]u16
2019-11-16 02:30:50 +03:00
C.ExpandEnvironmentStringsW(cmd.to_wide(), voidptr(&command_line), 32768)
2019-11-23 21:40:32 +03:00
create_process_ok := C.CreateProcessW(0, command_line, 0, 0, C.TRUE, 0, 0, 0, voidptr(&start_info), voidptr(&proc_info))
if !create_process_ok {
2019-11-07 16:01:17 +03:00
error_msg := get_error_msg(int(C.GetLastError()))
return error('exec failed (CreateProcess): $error_msg')
}
C.CloseHandle(child_stdin)
C.CloseHandle(child_stdout_write)
2020-02-03 06:01:39 +03:00
buf := [4096]byte
2019-11-16 02:30:50 +03:00
mut bytes_read := u32(0)
2020-02-03 06:01:39 +03:00
mut read_data := strings.new_builder(1024)
2019-11-07 16:01:17 +03:00
for {
2019-11-16 02:30:50 +03:00
readfile_result := C.ReadFile(child_stdout_read, buf, 1000, voidptr(&bytes_read), 0)
2020-02-03 06:01:39 +03:00
read_data.write_bytes(buf, int(bytes_read))
2019-11-23 21:40:32 +03:00
if readfile_result == false || int(bytes_read) == 0 {
break
}
2019-11-07 16:01:17 +03:00
}
2020-02-03 06:01:39 +03:00
soutput := read_data.str().trim_space()
read_data.free()
2019-11-16 02:30:50 +03:00
exit_code := u32(0)
2019-11-07 16:01:17 +03:00
C.WaitForSingleObject(proc_info.hProcess, C.INFINITE)
2019-11-16 02:30:50 +03:00
C.GetExitCodeProcess(proc_info.hProcess, voidptr(&exit_code))
2019-11-07 16:01:17 +03:00
C.CloseHandle(proc_info.hProcess)
C.CloseHandle(proc_info.hThread)
return Result {
2020-02-03 06:01:39 +03:00
output: soutput
2019-11-16 02:30:50 +03:00
exit_code: int(exit_code)
2019-11-07 16:01:17 +03:00
}
2019-11-10 03:08:53 +03:00
}
2019-12-27 21:10:06 +03:00
fn C.CreateSymbolicLinkW(&u16, &u16, u32) int
pub fn symlink(origin, target string) ?bool {
flags := if os.is_dir(origin) { 1 } else { 0 }
if C.CreateSymbolicLinkW(origin.to_wide(), target.to_wide(), u32(flags)) != 0 {
return true
}
return error(get_error_msg(int(C.GetLastError())))
}
pub fn (f mut File) write_bytes(data voidptr, size int) {
C.fwrite(data, 1, size, f.cfile)
}
pub fn (f mut File) close() {
if !f.opened {
return
}
f.opened = false
C.fflush(f.cfile)
C.fclose(f.cfile)
}