Landin library reference discuss source

platform/windows/windows.ldn

1--  Windows' own interface, kernel32, declared as extern(c) imports under
2--  the Windows x64 convention, raw.  Windows is not POSIX, so there is no
3--  platform/posix beneath a Windows program: this module is the system's
4--  interface, as platform/linux is Linux's, and a Windows provider builds
5--  on it directly.  A program reaches kernel32, never ntdll, whose calls
6--  Windows does not promise.
7--
8--  The module holds the process entry, `_landin_start`, which every
9--  Windows executable starts at: refine links each one with this module,
10--  whether or not its own imports reach it, as C's startup object is linked
11--  into every C program, and links kernel32, which the module names below.
12--  No C runtime is linked.  The entry reads the command line and the
13--  environment, converts each to a host string, WTF-8 (D2268), and keeps
14--  them as the process's argument root, which `arguments` and
15--  `environment` read as platform/posix's do on a POSIX system (D2269).
16--
17--  Each facility has a file of its own: this one the entry, the root, the
18--  handles and the calls every other file shares; wide.ldn the conversion
19--  between host strings and the system's 16-bit units; files.ldn files,
20--  directories and the console; processes.ldn pipes and child processes;
21--  time.ldn the clocks; threads.ldn threads, their storage and waiting on
22--  an address; memory.ldn the address space; completion.ldn completion
23--  ports, jobs and console control events.  Windows Sockets is the module
24--  platform/windows/sockets, which only a program that imports it links,
25--  since its calls' C names are ones a program may give its own (D2281).
26--  A call that fails returns the system's failure value and leaves the
27--  reason for `last_error`, as kernel32 does.
28--
29--  Its scope is every hosted system, so that a provider written for every
30--  hosted system imports it beside platform/posix; off Windows it declares
31--  nothing (D439, D2267).
32
33import core/mem
34import core/text
35
36compiler.assert(compiler.os == linux or compiler.os == darwin
37                or compiler.os == freebsd or compiler.os == windows)
38
39fixed if compiler.os == windows then
40    linker.library("kernel32")
41
42    --- A kernel object's handle, `HANDLE`: one word, which names an open
43    --- file, pipe, console, process, thread or event until it is closed.
44    public handle: type = usize
45
46    --- `INVALID_HANDLE_VALUE`, what `create_file` and `get_std_handle` give
47    --- when they fail: all ones.
48    public invalid_handle: handle = 0xFFFFFFFFFFFFFFFF
49
50    --- No handle: the null a call gives when it fails, and what a parent
51    --- that gave a process no standard stream leaves in its place.
52    public no_handle: handle = 0
53
54    --  A Win32 BOOL is 32 bits, nonzero for success.
55    --- The reason the calling thread's last failing call gave, `GetLastError`:
56    --- a Win32 error code, zero for none.  Read it at once after the call that
57    --- failed, before any other.
58    public extern(c) link(symbol: "GetLastError") last_error: () -> (code: u32)
59
60    --- Close `object`, `CloseHandle`: nonzero, or zero with the reason in
61    --- `last_error`.
62    public extern(c) link(symbol: "CloseHandle") close_handle:
63        (object: handle) -> (done: i32)
64
65    --- `STD_INPUT_HANDLE`, `STD_OUTPUT_HANDLE` and `STD_ERROR_HANDLE`, what
66    --- `get_std_handle` takes.
67    public std_input: u32 = 0xFFFFFFF6
68    --- `STD_OUTPUT_HANDLE`.
69    public std_output: u32 = 0xFFFFFFF5
70    --- `STD_ERROR_HANDLE`.
71    public std_error: u32 = 0xFFFFFFF4
72
73    --- One of the process's standard handles, `GetStdHandle`: the handle,
74    --- `no_handle` when the process has none, or `invalid_handle` with the
75    --- reason in `last_error`.
76    public extern(c) link(symbol: "GetStdHandle") get_std_handle:
77        (which: u32) -> (result: handle)
78
79    --- Read up to `count` bytes from `source` into `into`, `ReadFile`, without
80    --- overlapping: nonzero with the count read in `got`, zero at the end of
81    --- a file, or zero with the reason in `last_error`.  `overlapped` is zero
82    --- or an `overlapped` record's address for a handle opened to overlap.
83    public extern(c) link(symbol: "ReadFile") read_file:
84        (source: handle, into: ptr mut u8, count: u32, got: ptr mut u32,
85         overlapped: usize) -> (done: i32)
86
87    --- Write `count` bytes from `bytes` to `to`, `WriteFile`: nonzero with the
88    --- count written in `put`, or zero with the reason in `last_error`.
89    public extern(c) link(symbol: "WriteFile") write_file:
90        (to: handle, bytes: ptr u8, count: u32, put: ptr mut u32,
91         overlapped: usize) -> (done: i32)
92
93    --- End the process with `status` as its exit code, after every DLL's
94    --- detach routine has run.  Windows reads the code as a DWORD: a negative
95    --- `status` is the same 32 bits, so -1 is 4294967295.
96    public extern(c) link(symbol: "ExitProcess") exit_process: (status: i32)
97                                                               -> noreturn
98
99    --- The Win32 error codes the providers tell apart: `ERROR_*`.
100    public error_file_not_found: u32 = 2
101    --- `ERROR_PATH_NOT_FOUND`.
102    public error_path_not_found: u32 = 3
103    --- `ERROR_ACCESS_DENIED`.
104    public error_access_denied: u32 = 5
105    --- `ERROR_NOT_ENOUGH_MEMORY`.
106    public error_not_enough_memory: u32 = 8
107    --- `ERROR_INVALID_DRIVE`.
108    public error_invalid_drive: u32 = 15
109    --- `ERROR_NO_MORE_FILES`.
110    public error_no_more_files: u32 = 18
111    --- `ERROR_WRITE_PROTECT`.
112    public error_write_protect: u32 = 19
113    --- `ERROR_SHARING_VIOLATION`.
114    public error_sharing_violation: u32 = 32
115    --- `ERROR_LOCK_VIOLATION`.
116    public error_lock_violation: u32 = 33
117    --- `ERROR_HANDLE_EOF`.
118    public error_handle_eof: u32 = 38
119    --- `ERROR_NOT_SUPPORTED`.
120    public error_not_supported: u32 = 50
121    --- `ERROR_BAD_NETPATH`.
122    public error_bad_netpath: u32 = 53
123    --- `ERROR_FILE_EXISTS`.
124    public error_file_exists: u32 = 80
125    --- `ERROR_INVALID_PARAMETER`.
126    public error_invalid_parameter: u32 = 87
127    --- `ERROR_BROKEN_PIPE`.
128    public error_broken_pipe: u32 = 109
129    --- `ERROR_INVALID_NAME`.
130    public error_invalid_name: u32 = 123
131    --- `ERROR_ALREADY_EXISTS`.
132    public error_already_exists: u32 = 183
133    --- `ERROR_FILENAME_EXCED_RANGE`.
134    public error_filename_exceeds_range: u32 = 206
135    --- `ERROR_PIPE_NOT_CONNECTED`.
136    public error_pipe_not_connected: u32 = 233
137    --- `ERROR_MORE_DATA`.
138    public error_more_data: u32 = 234
139    --- `ERROR_DIRECTORY`.
140    public error_directory: u32 = 267
141    --- `ERROR_OPERATION_ABORTED`.
142    public error_operation_aborted: u32 = 995
143    --- `ERROR_IO_PENDING`.
144    public error_io_pending: u32 = 997
145
146    --- Reserve and commit `size` bytes of the address space, readable and
147    --- writable and zeroed, `VirtualAlloc` with `MEM_RESERVE | MEM_COMMIT`
148    --- and `PAGE_READWRITE`: their address, or zero with the reason in
149    --- `last_error`.  `wanted` is zero or the address to place them at.
150    public extern(c) link(symbol: "VirtualAlloc") virtual_alloc:
151        (wanted: usize, size: usize, kind: u32, protection: u32)
152        -> (address: usize)
153
154    --- Release, `MEM_RELEASE` with a size of zero, or decommit what
155    --- `virtual_alloc` gave, `VirtualFree`: nonzero, or zero with the reason
156    --- in `last_error`.
157    public extern(c) link(symbol: "VirtualFree") virtual_free:
158        (address: usize, size: usize, kind: u32) -> (done: i32)
159
160    --- `virtual_alloc`'s and `virtual_free`'s kinds and protections.
161    public mem_commit: u32 = 0x1000
162    --- `MEM_RESERVE`: reserve addresses.
163    public mem_reserve: u32 = 0x2000
164    --- `MEM_DECOMMIT`: give the memory back and keep the addresses.
165    public mem_decommit: u32 = 0x4000
166    --- `MEM_RELEASE`: give the memory and the addresses back.
167    public mem_release: u32 = 0x8000
168    --- `PAGE_READWRITE`: the pages may be read and written.
169    public page_readwrite: u32 = 0x04
170
171    --  The command line as the system keeps it for the process:
172    --  `GetCommandLineW`, its units ending in a NUL.
173    extern(c) link(symbol: "GetCommandLineW") command_line: () -> (units: ptr u16)
174
175    --  The environment block, `GetEnvironmentStringsW`: each `NAME=value`
176    --  ending in a NUL, and an empty one after the last.  Zero when the
177    --  system has no memory for the copy it makes.
178    extern(c) link(symbol: "GetEnvironmentStringsW") environment_strings:
179        () -> (block: usize)
180
181    --  Free the copy `environment_strings` made.
182    extern(c) link(symbol: "FreeEnvironmentStringsW") free_environment_strings:
183        (block: usize) -> (done: i32)
184
185    --  C's view of the program's hosted entry: the process entry calls it
186    --  as C's runtime would, with the argument and environment tables it
187    --  built and has already kept as the root; a program that defines
188    --  `_landin_host_initialize_arguments` is given them there too.
189    extern(c) link(symbol: "main") program_main:
190        (count: i32, values: ptr ptr u8, environment: ptr ptr u8)
191        -> (code: i32)
192
193    word: usize = sizeof usize
194
195    --  A unit of the command line.
196    unit_at: (first: ptr u16, index: usize) -> (unit: u16) =
197        at: ptr u16 = ptr(usize(first) + index * 2)
198        unit = at.val
199    end unit_at
200
201    blank: (unit: u16) -> (yes: bool) =
202        yes = unit == 32 or unit == 9
203    end blank
204
205    --  What the command line's arguments take: their count, the program's
206    --  name among them, and the units they hold after quoting is undone.
207    measure: type = struct
208        count: usize
209        units: usize
210    end measure
211
212    --  Walk the command line by the rules Microsoft's C runtime splits it
213    --  by, which every Windows program's parent quotes for: the program's
214    --  name runs to the next blank, or between the quotes it starts with,
215    --  with no escapes; after it blanks separate arguments, a quote begins
216    --  or ends a quoted run in which blanks are kept, `""` inside a run is
217    --  one quote, and backslashes are literal except before a quote, where
218    --  each pair is one backslash and an odd one left over makes the quote
219    --  literal.  With `into` empty it only measures; otherwise it writes
220    --  each argument's units followed by a NUL unit, which `into` has room
221    --  for.
222    split: (line: ptr u16, into: []mut u16) -> (found: measure) =
223        writing: bool = lenof into > 0
224        mut at: usize = 0
225        mut put: usize = 0
226        mut count: usize = 0
227        --  The program's name.
228        if unit_at(line, 0) == 34 then
229            inc at
230            while unit_at(line, at) <> 0 and unit_at(line, at) <> 34 do
231                if writing then into[put] = unit_at(line, at) end if
232                inc put
233                inc at
234            end while
235            if unit_at(line, at) == 34 then inc at end if
236        else
237            while unit_at(line, at) <> 0 and not blank(unit_at(line, at)) do
238                if writing then into[put] = unit_at(line, at) end if
239                inc put
240                inc at
241            end while
242        end if
243        if writing then into[put] = 0 end if
244        inc put
245        inc count
246        loop do
247            while blank(unit_at(line, at)) do inc at end while
248            break when unit_at(line, at) == 0
249            mut quoted: bool = false
250            loop do
251                unit: u16 = unit_at(line, at)
252                break when unit == 0
253                break when blank(unit) and not quoted
254                if unit == 92 then
255                    mut slashes: usize = 0
256                    while unit_at(line, at) == 92 do
257                        inc slashes
258                        inc at
259                    end while
260                    if unit_at(line, at) == 34 then
261                        mut pairs: usize = slashes / 2
262                        while pairs > 0 do
263                            if writing then into[put] = 92 end if
264                            inc put
265                            dec pairs
266                        end while
267                        if slashes % 2 == 1 then
268                            if writing then into[put] = 34 end if
269                            inc put
270                            inc at
271                        end if
272                    else
273                        while slashes > 0 do
274                            if writing then into[put] = 92 end if
275                            inc put
276                            dec slashes
277                        end while
278                    end if
279                elsif unit == 34 then
280                    inc at
281                    if quoted and unit_at(line, at) == 34 then
282                        if writing then into[put] = 34 end if
283                        inc put
284                        inc at
285                    else
286                        quoted = not quoted
287                    end if
288                else
289                    if writing then into[put] = unit end if
290                    inc put
291                    inc at
292                end if
293            end loop
294            if writing then into[put] = 0 end if
295            inc put
296            inc count
297        end loop
298        found = (count: count, units: put)
299    end split
300
301    --  Memory the entry takes for good, or an end with the reason when the
302    --  system has none.
303    taken: (size: usize) -> (address: usize) =
304        address = virtual_alloc(0, size, mem_reserve | mem_commit,
305                                page_readwrite)
306        if address == 0 then exit_process(i32(error_not_enough_memory)) end if
307    end taken
308
309    --  The `count` units at `first`, which the system or the process keeps.
310    units_at: (first: usize, count: usize) -> (units: []u16) =
311        whole: ptr [1]u16 = ptr(first)
312        units = whole.val[0..<0]
313        if count > 0 then
314            unchecked begin
315                units = whole.val[0..<count]
316            end unchecked
317        end if
318    end units_at
319
320    --  The `count` bytes at `first`, writable, which the entry took.
321    bytes_at: (first: usize, count: usize) -> (bytes: []mut u8) =
322        whole: ptr mut [1]u8 = ptr(first)
323        bytes = whole.val[0..<0]
324        if count > 0 then
325            unchecked begin
326                bytes = whole.val[0..<count]
327            end unchecked
328        end if
329    end bytes_at
330
331    --  Units ending in NUL units, one string after another, as a table of
332    --  `count` host strings, each ending in a NUL, and a null entry after
333    --  the last: a C-style vector, which the entry gives `main`.
334    vector: (strings: []u16, count: usize) -> (table: ptr ptr u8) =
335        bytes: usize = host_length(strings)
336        table_bytes: usize = (count + 1) * word
337        base: usize = taken(table_bytes + bytes)
338        text_room: []mut u8 = bytes_at(base + table_bytes, bytes)
339        mut written: usize = 0
340        mut begun: usize = 0
341        mut index: usize = 0
342        for at in usize(0)..<lenof strings do
343            if strings[at] == 0 then
344                slot: ptr mut usize = ptr(base + index * word)
345                slot.val = base + table_bytes + written
346                written += to_host(strings[begun..<at],
347                                   text_room[written..<lenof text_room])
348                text_room[written] = 0
349                inc written
350                inc index
351                begun = at + 1
352            end if
353        end for
354        table = ptr(base)
355    end vector
356
357    --  The arguments and environment as C vectors, and the argument count.
358    start_tables: type = struct
359        count: usize
360        values: ptr ptr u8
361        environment: ptr ptr u8
362    end start_tables
363
364    --  Read the command line and the environment, and convert both to host
365    --  strings in storage the process keeps.
366    read_start: () -> (tables: start_tables) =
367        line: ptr u16 = command_line()
368        size: measure = split(line, no_units[0..<0])
369        room: usize = taken(size.units * 2)
370        whole: ptr mut [1]u16 = ptr(room)
371        mut units: []mut u16 = whole.val[0..<0]
372        unchecked begin
373            units = whole.val[0..<size.units]
374        end unchecked
375        _ = split(line, units)
376        values: ptr ptr u8 = vector(units, size.count)
377        block: usize = environment_strings()
378        mut environment: ptr ptr u8 = ptr(usize(addr no_entries[0]))
379        if block <> 0 then
380            mut length: usize = 0
381            mut entries: usize = 0
382            loop do
383                break when unit_at(ptr(block), length) == 0
384                while unit_at(ptr(block), length) <> 0 do inc length end while
385                inc length
386                inc entries
387            end loop
388            environment = vector(units_at(block, length), entries)
389            _ = free_environment_strings(block)
390        end if
391        tables = (count: size.count, values: values, environment: environment)
392    end read_start
393
394    mut no_units: [1]u16 = [0]
395
396    --  The table of an empty environment: one null entry.
397    no_entries: [1]usize = [0]
398
399    --- The process entry.  Windows starts a process at the image's entry with
400    --- the stack aligned as after a call, which a routine's prologue expects,
401    --- so the entry is an ordinary routine: it reads the command line and the
402    --- environment, calls the program's `main` with them as C's runtime would,
403    --- and ends the process with main's result as the exit code.
404    public extern(c) _landin_start: () -> noreturn =
405        tables: start_tables = read_start()
406        keep_root(tables)
407        code: i32 = program_main(i32(tables.count), tables.values,
408                                 tables.environment)
409        exit_process(code)
410    end _landin_start
411
412    --  What the argument root holds before it is established, and what a
413    --  null pointer is in a vector's entry.
414    no_table: atom
415
416    no_string: atom
417
418    root_table: type = no_table | ptr ptr u8
419
420    argument_string: type = no_string | ptr u8
421
422    --  The argument root, the vectors the entry made, kept without copying.
423    mut root_values: root_table = no_table
424
425    mut root_count: i32
426
427    mut root_environment: root_table = no_table
428
429    --  Keep the vectors the entry made as the process's argument root, for
430    --  good.  The entry keeps them itself rather than defining
431    --  `_landin_host_initialize_arguments`, which this module, linked into
432    --  every Windows program, would then define for a program that defines
433    --  its own (D2269).
434    keep_root: (escaping tables: start_tables) -> none =
435        root_count = i32(tables.count)
436        root_values = tables.values
437        root_environment = tables.environment
438    end keep_root
439
440    --- The process's arguments: the vector after the program's name and
441    --- their count.  `argument` reads it.
442    public argument_table: type = struct
443        values: ptr ptr u8
444        count: usize
445    end argument_table
446
447    --- The process's arguments, the program's name not among them.  It traps
448    --- when no argument root has been established.
449    public arguments: () -> (table: argument_table) =
450        held: ptr ptr u8 = match root_values
451            no_table: compiler.unreachable()
452            ptr (found): found
453        end match
454        first: ptr ptr u8 = ptr(usize(held) + word)
455        table = (values: first,
456                 count: if root_count > 0 then usize(root_count - 1)
457                        else usize(0) end if)
458    end arguments
459
460    --  The bytes before the first NUL at `first`.
461    terminated_length: (first: ptr u8) -> (length: usize) =
462        length = 0
463        loop do
464            at: ptr u8 = ptr(usize(first) + length)
465            break when at.val == 0
466            inc length
467        end loop
468    end terminated_length
469
470    --  The `length` bytes at `first`, which the process keeps.
471    view: (first: ptr u8, length: usize) -> (bytes: []u8 from first) =
472        whole: ptr [1]u8 = ptr(usize(first))
473        bytes = whole.val[0..<0]
474        if length > 0 then
475            unchecked begin
476                bytes = whole.val[0..<length]
477            end unchecked
478        end if
479    end view
480
481    --- The argument `index`, from zero, as a host string lending the
482    --- process's own storage.  An index at or past the table's `count` traps.
483    public argument: (table: argument_table, index: usize)
484                     -> (value: text.os_string from table) =
485        if index >= table.count then
486            compiler.unreachable()
487        end if
488        entry: ptr argument_string = ptr(usize(table.values) + index * word)
489        match entry.val
490            no_string: compiler.unreachable()
491            ptr (data): value = text.os_string_over(view(data,
492                                                         terminated_length(data)))
493        end match
494    end argument
495
496    --- The process's environment as the entry read it, and the count of its
497    --- entries.  `variable` reads it.
498    public environment_table: type = struct
499        values: ptr ptr u8
500        count: usize
501    end environment_table
502
503    --- The process's environment, as the system gave it when the process
504    --- started, in its order: `NAME=value` entries, the hidden `=C:` entries
505    --- that keep each drive's working directory among them.  It traps before
506    --- the argument root exists, as `arguments` does.
507    public environment: () -> (table: environment_table) =
508        _ = arguments()
509        values: ptr ptr u8 = match root_environment
510            no_table: ptr(usize(addr no_entries[0]))
511            ptr (found): found
512        end match
513        mut count: usize = 0
514        loop do
515            entry: ptr usize = ptr(usize(values) + count * word)
516            break when entry.val == 0
517            inc count
518        end loop
519        table = (values: values, count: count)
520    end environment
521
522    --- The variable at `index`, from zero: the units of its entry before the
523    --- first `=` after its first unit as its name and those after it as its
524    --- value, so that a hidden `=C:` entry is named `=C:`.  An index at or
525    --- past the table's `count` traps.
526    public variable: (table: environment_table, index: usize)
527                     -> (item: text.os_variable from table) =
528        if index >= table.count then
529            compiler.unreachable()
530        end if
531        entry: ptr argument_string = ptr(usize(table.values) + index * word)
532        match entry.val
533            no_string: compiler.unreachable()
534            ptr (data): begin
535                whole: []u8 = view(data, terminated_length(data))
536                mut at: usize = 0
537                if lenof whole > 0 then
538                    at = 1 + mem.find(whole[1..<lenof whole], u8('='))
539                end if
540                value: []u8 = if at < lenof whole then whole[at + 1..<lenof whole]
541                              else whole[lenof whole..<lenof whole] end if
542                item = (name: text.os_string_over(whole[0..<at]),
543                        value: text.os_string_over(value))
544            end
545        end match
546    end variable
547end if