v/vlib/os/os_windows.c.v

396 lines
11 KiB
V
Raw Normal View History

module os
2020-02-03 04:01:39 +01:00
import strings
#flag -lws2_32
#include <winsock2.h>
2020-08-05 08:09:18 +02:00
#include <process.h>
2019-10-24 11:36:57 +02:00
pub const (
2019-10-12 21:18:19 +02:00
path_separator = '\\'
2020-05-26 03:17:52 +02:00
path_delimiter = ';'
2019-09-14 22:48:30 +02:00
)
2019-07-16 01:57:03 +02:00
// Ref - https://docs.microsoft.com/en-us/windows/desktop/winprog/windows-data-types
// A handle to an object.
2020-02-09 15:40:32 +01:00
pub type HANDLE voidptr
2019-08-17 15:17:43 +02:00
// win: FILETIME
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime
struct Filetime {
2020-05-16 16:12:23 +02:00
dw_low_date_time u32
dw_high_date_time u32
2019-08-17 15:17:43 +02:00
}
// win: WIN32_FIND_DATA
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-win32_find_dataw
struct Win32finddata {
2019-08-17 15:17:43 +02:00
mut:
2020-05-16 16:12:23 +02:00
dw_file_attributes u32
ft_creation_time Filetime
ft_last_access_time Filetime
ft_last_write_time Filetime
n_file_size_high u32
n_file_size_low u32
dw_reserved0 u32
dw_reserved1 u32
2020-05-22 17:36:09 +02:00
c_file_name [260]u16 // max_path_len = 260
2020-05-16 16:12:23 +02:00
c_alternate_file_name [14]u16 // 14
dw_file_type u32
dw_creator_type u32
w_finder_flags u16
2019-08-17 15:17:43 +02:00
}
2019-11-07 14:01:17 +01:00
struct ProcessInformation {
mut:
2020-05-16 16:12:23 +02:00
h_process voidptr
h_thread voidptr
dw_process_id u32
dw_thread_id u32
2019-11-07 14:01:17 +01:00
}
struct StartupInfo {
mut:
2019-11-07 14:01:17 +01:00
cb u32
2020-05-16 16:12:23 +02:00
lp_reserved &u16
lp_desktop &u16
lp_title &u16
dw_x u32
dw_y u32
dw_x_size u32
dw_y_size u32
dw_x_count_chars u32
dw_y_count_chars u32
dw_fill_attributes u32
dw_flags u32
w_show_window u16
cb_reserved2 u16
lp_reserved2 byteptr
h_std_input voidptr
h_std_output voidptr
h_std_error voidptr
2019-11-07 14:01:17 +01:00
}
struct SecurityAttributes {
mut:
2020-05-16 16:12:23 +02:00
n_length u32
lp_security_descriptor voidptr
b_inherit_handle bool
2019-11-07 14:01:17 +01:00
}
2019-08-17 15:17:43 +02:00
fn init_os_args_wide(argc int, argv &byteptr) []string {
2020-04-26 13:49:31 +02:00
mut args := []string{}
for i in 0..argc {
args << string_from_wide(unsafe {&u16(argv[i])})
2019-09-14 22:48:30 +02:00
}
return args
}
2019-10-17 13:30:05 +02:00
pub fn ls(path string) ?[]string {
mut find_file_data := Win32finddata{}
2020-04-26 13:49:31 +02:00
mut dir_files := []string{}
// We can also check if the handle is valid. but using is_dir instead
2019-08-16 14:05:11 +02:00
// h_find_dir := C.FindFirstFile(path.str, &find_file_data)
2020-05-22 17:36:09 +02:00
// if (invalid_handle_value == h_find_dir) {
2019-08-16 14:05:11 +02:00
// return dir_files
// }
// C.FindClose(h_find_dir)
if !is_dir(path) {
2019-11-02 20:37:29 +01:00
return error('ls() couldnt open dir "$path": directory does not exist')
2019-08-16 14:05:11 +02: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 22:48:30 +02:00
path_files := '$path\\*'
2019-08-16 14:05:11 +02:00
// NOTE:TODO: once we have a way to convert utf16 wide character to utf8
// we should use FindFirstFileW and FindNextFileW
2019-11-16 00:30:50 +01:00
h_find_files := C.FindFirstFile(path_files.to_wide(), voidptr(&find_file_data))
2020-05-16 16:12:23 +02:00
first_filename := string_from_wide(&u16(find_file_data.c_file_name))
2019-08-16 14:05:11 +02:00
if first_filename != '.' && first_filename != '..' {
dir_files << first_filename
}
2020-03-28 10:19:38 +01:00
for C.FindNextFile(h_find_files, voidptr(&find_file_data)) > 0 {
2020-05-16 16:12:23 +02:00
filename := string_from_wide(&u16(find_file_data.c_file_name))
2019-08-16 14:05:11 +02:00
if filename != '.' && filename != '..' {
dir_files << filename.clone()
}
}
C.FindClose(h_find_files)
return dir_files
2019-09-14 22:48:30 +02:00
}
2019-08-16 14:05:11 +02:00
/*
pub fn is_dir(path string) bool {
2019-08-17 15:17:43 +02:00
_path := path.replace('/', '\\')
2019-11-16 00:30:50 +01:00
attr := C.GetFileAttributesW(_path.to_wide())
if int(attr) == int(C.INVALID_FILE_ATTRIBUTES) {
2019-08-17 15:17:43 +02:00
return false
}
2019-11-16 00:30:50 +01:00
if (int(attr) & C.FILE_ATTRIBUTE_DIRECTORY) != 0 {
2019-08-17 15:17:43 +02:00
return true
}
return false
2019-09-14 22:48:30 +02:00
}
*/
2019-08-17 15:17:43 +02:00
2019-11-23 19:40:32 +01:00
2019-08-17 15:17:43 +02:00
// mkdir creates a new directory with the specified path.
2019-11-23 17:55:18 +01:00
pub fn mkdir(path string) ?bool {
if path == '.' { return true }
2020-03-20 16:41:18 +01:00
apath := os.real_path( path )
2019-11-23 19:40:32 +01:00
if !C.CreateDirectory(apath.to_wide(), 0) {
2019-11-23 17:55:18 +01:00
return error('mkdir failed for "$apath", because CreateDirectory returned ' + get_error_msg(int(C.GetLastError())))
2019-08-17 15:17:43 +02:00
}
2019-11-23 19:40:32 +01:00
return true
2019-09-14 22:48:30 +02:00
}
2019-08-17 15:17:43 +02:00
2019-07-14 22:59:25 +02: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 {
cfile := vfopen(path, 'rb')
if cfile == voidptr(0) {
2020-05-22 17:36:09 +02:00
return HANDLE(invalid_handle_value)
}
handle := HANDLE(C._get_osfhandle(fileno(cfile))) // CreateFile? - hah, no -_-
2020-05-16 16:12:23 +02:00
return handle
}
2019-07-14 22:59:25 +02:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
2019-09-14 22:48:30 +02:00
// get_module_filename retrieves the fully qualified path for the file that contains the specified module.
2019-07-14 22:59:25 +02:00
// The module must have been loaded by the current process.
pub fn get_module_filename(handle HANDLE) ?string {
2020-02-22 12:41:24 +01: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 14:00:28 +02:00
success {
2020-05-16 16:12:23 +02:00
return string_from_wide2(buf, sz)
2020-02-22 12:41:24 +01:00
}
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 22:59:25 +02:00
}
2019-07-15 19:30:40 +02:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagea#parameters
const (
2020-05-22 17:36:09 +02:00
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
2019-07-15 19:30:40 +02:00
)
// Ref - winnt.h
const (
2020-05-22 17:36:09 +02:00
sublang_neutral = 0x00
sublang_default = 0x01
lang_neutral = (sublang_neutral)
2019-09-14 22:48:30 +02:00
)
2019-07-15 19:30:40 +02:00
// Ref - https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--12000-15999-
const (
2020-05-22 17:36:09 +02:00
max_error_code = 15841 // ERROR_API_UNAVAILABLE
)
2019-09-14 22:48:30 +02: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 19:30:40 +02:00
mut buf := voidptr(0)
// Check for code overflow
2020-05-22 17:36:09 +02:00
if code > u32(max_error_code) {
return buf
}
2019-07-15 19:30:40 +02:00
C.FormatMessage(
2020-05-22 17:36:09 +02:00
format_message_allocate_buffer
| format_message_from_system
| format_message_ignore_inserts,
0, code, C.MAKELANGID(lang_neutral, sublang_default), voidptr(&buf), 0, 0)
2019-07-15 19:30:40 +02: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 ''
}
2020-05-16 16:12:23 +02:00
ptr_text := ptr_win_get_error_msg(u32(code))
if ptr_text == 0 { // compare with null
return ''
}
2020-05-16 16:12:23 +02:00
return string_from_wide(ptr_text)
2019-07-29 18:21:36 +02:00
}
2019-11-07 14:01:17 +01: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 {}
2020-05-16 16:12:23 +02:00
sa.n_length = sizeof(C.SECURITY_ATTRIBUTES)
sa.b_inherit_handle = true
2019-11-07 14:01:17 +01:00
2019-11-23 19:40:32 +01:00
create_pipe_ok := C.CreatePipe(voidptr(&child_stdout_read),
voidptr(&child_stdout_write), voidptr(&sa), 0)
if !create_pipe_ok {
error_num := int(C.GetLastError())
error_msg := get_error_msg(error_num)
return error_with_code('exec failed (CreatePipe): $error_msg', error_num)
2019-11-07 14:01:17 +01:00
}
2019-11-23 19:40:32 +01:00
set_handle_info_ok := C.SetHandleInformation(child_stdout_read, C.HANDLE_FLAG_INHERIT, 0)
if !set_handle_info_ok {
error_num := int(C.GetLastError())
error_msg := get_error_msg(error_num)
return error_with_code('exec failed (SetHandleInformation): $error_msg', error_num)
2019-11-07 14:01:17 +01:00
}
proc_info := ProcessInformation{}
2020-04-04 11:59:25 +02:00
start_info := StartupInfo{
2020-05-16 16:12:23 +02:00
lp_reserved: 0
lp_desktop: 0
lp_title: 0
2020-04-04 11:59:25 +02:00
cb: sizeof(C.PROCESS_INFORMATION)
2020-05-16 16:12:23 +02:00
h_std_input: child_stdin
h_std_output: child_stdout_write
h_std_error: child_stdout_write
dw_flags: u32(C.STARTF_USESTDHANDLES)
2020-04-04 11:59:25 +02:00
}
command_line := [32768]u16{}
2019-11-16 00:30:50 +01:00
C.ExpandEnvironmentStringsW(cmd.to_wide(), voidptr(&command_line), 32768)
2019-11-23 19:40:32 +01: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 {
error_num := int(C.GetLastError())
error_msg := get_error_msg(error_num)
return error_with_code('exec failed (CreateProcess) with code $error_num: $error_msg cmd: $cmd', error_num)
2019-11-07 14:01:17 +01:00
}
C.CloseHandle(child_stdin)
C.CloseHandle(child_stdout_write)
buf := [4096]byte{}
2019-11-16 00:30:50 +01:00
mut bytes_read := u32(0)
2020-02-03 04:01:39 +01:00
mut read_data := strings.new_builder(1024)
2019-11-07 14:01:17 +01:00
for {
2019-11-16 00:30:50 +01:00
readfile_result := C.ReadFile(child_stdout_read, buf, 1000, voidptr(&bytes_read), 0)
2020-02-03 04:01:39 +01:00
read_data.write_bytes(buf, int(bytes_read))
2019-11-23 19:40:32 +01:00
if readfile_result == false || int(bytes_read) == 0 {
break
}
2019-11-07 14:01:17 +01:00
}
2020-02-03 04:01:39 +01:00
soutput := read_data.str().trim_space()
read_data.free()
2019-11-16 00:30:50 +01:00
exit_code := u32(0)
2020-05-16 16:12:23 +02:00
C.WaitForSingleObject(proc_info.h_process, C.INFINITE)
C.GetExitCodeProcess(proc_info.h_process, voidptr(&exit_code))
C.CloseHandle(proc_info.h_process)
C.CloseHandle(proc_info.h_thread)
2019-11-07 14:01:17 +01:00
return Result {
2020-02-03 04:01:39 +01:00
output: soutput
2019-11-16 00:30:50 +01:00
exit_code: int(exit_code)
2019-11-07 14:01:17 +01:00
}
2019-11-10 01:08:53 +01:00
}
2019-12-27 19:10:06 +01: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())))
}
2020-05-17 13:51:18 +02:00
pub fn (mut f File) close() {
2020-08-01 23:07:37 +02:00
if !f.is_opened {
return
}
2020-08-01 23:07:37 +02:00
f.is_opened = false
C.fflush(f.cfile)
C.fclose(f.cfile)
}
pub struct ExceptionRecord {
pub:
// status_ constants
code u32
flags u32
2020-06-14 15:46:30 +02:00
record &ExceptionRecord
address voidptr
param_count u32
// params []voidptr
}
pub struct ContextRecord {
// TODO
}
pub struct ExceptionPointers {
pub:
exception_record &ExceptionRecord
context_record &ContextRecord
}
pub type VectoredExceptionHandler fn(&ExceptionPointers)u32
// This is defined in builtin because we use vectored exception handling
// for our unhandled exception handler on windows
// As a result this definition is commented out to prevent
// duplicate definitions from displeasing the compiler
// fn C.AddVectoredExceptionHandler(u32, VectoredExceptionHandler)
pub fn add_vectored_exception_handler(first bool, handler VectoredExceptionHandler) {
C.AddVectoredExceptionHandler(u32(first), handler)
2020-05-31 12:57:26 +02:00
}
// this is defined in builtin_windows.c.v in builtin
// fn C.IsDebuggerPresent() bool
pub fn debugger_present() bool {
return C.IsDebuggerPresent()
}
2020-06-14 15:46:30 +02:00
pub fn uname() Uname {
// TODO: implement `os.uname()` for windows
unknown := 'unknown'
return Uname{
sysname: unknown
nodename: unknown
release: unknown
version: unknown
machine: unknown
}
}
// `is_writable_folder` - `folder` exists and is writable to the process
pub fn is_writable_folder(folder string) ?bool {
if !os.exists(folder) {
return error('`$folder` does not exist')
}
if !os.is_dir(folder) {
return error('`folder` is not a folder')
}
tmp_perm_check := os.join_path(folder, 'tmp_perm_check_pid_' + getpid().str())
mut f := os.open_file(tmp_perm_check, 'w+', 0o700) or {
return error('cannot write to folder $folder: $err')
}
f.close()
os.rm(tmp_perm_check)
return true
}
fn C._getpid() int
[inline]
pub fn getpid() int {
return C._getpid()
}