File: windows.lisp

package info (click to toggle)
acl2 8.6%2Bdfsg-2
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 1,111,420 kB
  • sloc: lisp: 17,818,294; java: 125,359; python: 28,122; javascript: 23,458; cpp: 18,851; ansic: 11,569; perl: 7,678; xml: 5,591; sh: 3,976; makefile: 3,833; ruby: 2,633; yacc: 1,126; ml: 763; awk: 295; csh: 233; lex: 197; php: 178; tcl: 49; asm: 23; haskell: 17
file content (352 lines) | stat: -rw-r--r-- 14,814 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; windows.lisp --- Low-level interface to the windows API.
;;;
;;; Copyright (c) 2007, Luis Oliveira  <loliveira@common-lisp.net>
;;; Copyright (c) 2021, Eric Timmons   <eric@timmons.dev>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.

(in-package #:osicat-windows)

(load-foreign-library "Kernel32.dll")

;;; Error Handling

(defrawwinapi ("GetLastError" get-last-error) dword)

(defwinapi ("FormatMessageW" %format-message-w) dword
  (flags format-message-flags)
  (source :pointer)
  (message-id dword)
  (language-id dword)
  (buffer :pointer)
  (size dword)
  &rest)

(defun get-error-message (error-code)
  (with-foreign-object (buffer-pointer :uint16 (* 64 1024))
    (%format-message-w '(:ignore-inserts :from-system)
                       (null-pointer)
                       error-code
                       0
                       buffer-pointer
                       (* 64 1024))
    (wstring-to-string buffer-pointer)))

;;; Performance Counter

(defwinapi ("QueryPerformanceCounter" %query-perf-counter) bool
  (count (:pointer large-integer)))

(defun query-performance-counter ()
  (with-foreign-object (ptr 'large-integer)
    (assert (%query-perf-counter ptr))
    (mem-ref ptr 'large-integer)))

;;; Wide string translation.
;;;
;;; Many windows functions have an ASCII version and a Unicode/Wide String
;;; version. We typically want to use the Unicode versions because they have
;;; fewer restrictions. Unfortunately, Windows has standardized on UTF-16 using
;;; :uint32s instead of :chars. To also guard against any other shenanigans,
;;; just use Windows' built in functionality to create wide strings.

(defwinapi ("WideCharToMultiByte" wide-char-to-multi-byte) :int
  (code-page :uint)
  (flags dword)
  (wide-char-str :pointer)
  (wide-char :int)
  (multi-byte-str :pointer)
  (multi-byte :int)
  (default-char :pointer)
  (used-default-char :pointer))

(defwinapi ("MultiByteToWideChar" multi-byte-to-wide-char) :int
  (code-page :uint)
  (flags dword)
  (multi-byte-str :pointer)
  (multi-byte :int)
  (wide-char-str :pointer)
  (wide-char :int))

(defun string-to-wstring (string)
  "Convert a Lisp string to a Windows wide string. Returns a pointer to the
newly allocated string."
  (with-foreign-string (foreign-string string :encoding :utf-8)
    ;; Compute the size needed to hold the wide string, then actually do the
    ;; conversion.
    (let* ((num-chars (multi-byte-to-wide-char +cp-utf-8+ 0 foreign-string -1 (null-pointer) 0))
           (wide-string (foreign-alloc :uint16 :count num-chars)))
      (multi-byte-to-wide-char +cp-utf-8+ 0 foreign-string -1 wide-string num-chars)
      wide-string)))

(defun wstring-to-string (wstring &optional length)
  "Given a pointer to a Windows wide string, return a Lisp string with its contents.

If LENGTH is provided, it is how many characters to read from the wide
string. If it is not provided, the wide string must be null terminated.
"
  (let ((num-bytes (wide-char-to-multi-byte +cp-utf-8+ 0
                                            wstring (or length -1)
                                            (null-pointer) 0
                                            (null-pointer) (null-pointer))))
    (with-foreign-object (foreign-string :uchar num-bytes)
      (wide-char-to-multi-byte +cp-utf-8+ 0
                               wstring (or length -1)
                               foreign-string num-bytes
                               (null-pointer) (null-pointer))
      (foreign-string-to-lisp foreign-string :encoding :utf-8
                                             :count (unless (null length) num-bytes)))))

(defmethod translate-to-foreign (string (type wide-string))
  (string-to-wstring string))

(defmethod translate-from-foreign (pointer (type wide-string))
  (wstring-to-string pointer))

(defmethod free-translated-object (pointer (type wide-string) param)
  (declare (ignore param))
  (foreign-free pointer))

(defmethod translate-to-foreign ((filename string) (type wide-filename))
  (string-to-wstring filename))

(defmethod translate-to-foreign ((filename pathname) (type wide-filename))
  (when (wild-pathname-p filename)
    (system-error "Pathname is wild: ~S." filename))
  (string-to-wstring (native-namestring (translate-logical-pathname filename))))

(defmethod free-translated-object (pointer (type wide-filename) param)
  (declare (ignore param))
  (foreign-free pointer))

;;; readdir/opendir equivalents

(defwinapi ("FindFirstFileW" find-first-file-w) search-handle
  (file-name wide-string)
  (find-file-data :pointer))

(defwinapi ("FindNextFileW" find-next-file-w) bool
  (find-file search-handle)
  (find-file-data :pointer))

(defwinapi ("FindClose" find-close) bool
  (find-file search-handle))

(define-c-struct-wrapper find-data ())

(defmethod print-object ((object find-data) stream)
  (print-unreadable-object (object stream :type t :identity t)
    (format stream "~S ~S" (find-data-file-name object) (find-data-file-attributes object))))

(defun find-first-file (path)
  "Calls FindFirstFileW with the PATH. Returns one or two VALUES.

If there are no matches for PATH, then NIL is returned as the only value.

If there are matches, a FIND-DATA instance containing the first match is the
first value and a handle for subsequent use with FIND-NEXT-FILE is the second
value.

When finished, the handle must be passed to FIND-CLOSE."
  (with-foreign-object (buf '(:struct find-data))
    (handler-bind ((win32-error (lambda (c)
                                  (when (= (system-error-code c) +error-file-not-found+)
                                    (return-from find-first-file nil)))))
      (let ((handle (find-first-file-w path buf)))
        (values (make-instance 'find-data :pointer buf) handle)))))

(defun find-next-file (handle)
  "Calls FindNextFileW to continue the search represented by HANDLE. Returns a
FIND-DATA instance or NIL."
  (with-foreign-object (buf '(:struct find-data))
    (handler-bind ((win32-error (lambda (c)
                                  (when (= (system-error-code c) +error-no-more-files+)
                                    (return-from find-next-file nil)))))
      (find-next-file-w handle buf)
      (make-instance 'find-data :pointer buf))))

;;; Symbolic links

(defwinapi ("CreateSymbolicLinkW" create-symbolic-link) bool
  (symlink-file-name wide-filename)
  (target-file-name wide-filename)
  (flags symbolic-link-flags))

;;; Hard links

(defwinapi ("CreateHardLinkW" create-hard-link) bool
  (file-name wide-filename)
  (existing-file-name wide-filename)
  (security-attributes :pointer))

;;; File handle creation

(defwinapi ("CreateFileW" create-file-w) handle
  (file-name wide-filename)
  (desired-access dword)
  (share-mode share-mode-flags)
  (security-attributes :pointer)
  (creation-disposition creation-disposition)
  (flags-and-attributes file-attributes-and-flags)
  (template-file :pointer))

(defun create-file (file-name desired-access share-mode security-attributes
                    creation-disposition flags-and-attributes
                    &key (template-file (null-pointer)))
  (create-file-w file-name desired-access share-mode security-attributes creation-disposition
                 flags-and-attributes template-file))

(defun call-with-create-file (thunk file-name desired-access share-mode security-attributes
                              creation-disposition flags-and-attributes
                              &key (template-file (null-pointer)))
  (let ((handle (create-file file-name desired-access share-mode security-attributes
                             creation-disposition flags-and-attributes
                             :template-file template-file)))
    (unwind-protect
         (funcall thunk handle)
      (close-handle handle))))

(defmacro with-create-file ((handle-name
                             file-name desired-access share-mode security-attributes
                             creation-disposition flags-and-attributes
                             &key (template-file '(null-pointer)))
                            &body body)
  `(call-with-create-file (lambda (,handle-name) ,@body)
                          ,file-name ,desired-access ,share-mode ,security-attributes
                          ,creation-disposition ,flags-and-attributes
                          :template-file ,template-file))

(defwinapi ("CloseHandle" close-handle) bool
  (object handle))

(defwinapi ("GetFinalPathNameByHandleW" %get-final-path-name-by-handle-w) dword
  (file handle)
  (file-path :pointer)
  (file-path-size dword)
  (flags dword))

(defun get-final-path-name-by-handle (handle)
  (with-foreign-object (wstring :uint16 +max-path+)
    (%get-final-path-name-by-handle-w handle wstring +max-path+ 0)
    (wstring-to-string wstring)))

;; this function has funky error semantics.
(defrawwinapi ("GetFileType" %get-file-type) file-type
  (file handle))

(defun get-file-type (file)
  (let ((result (%get-file-type file)))
    (when (eql result :unknown)
      (let ((error-code (get-last-error)))
        (unless (= error-code +error-success+)
          (win32-error error-code 'get-file-type))))
    result))

(defwinapi ("GetFileInformationByHandle" %get-file-information-by-handle) bool
  (file handle)
  (file-information :pointer))

(define-c-struct-wrapper by-handle-file-information ())

(defun get-file-information-by-handle (handle)
  (with-foreign-object (buff '(:struct by-handle-file-information))
    (%get-file-information-by-handle handle buff)
    (make-instance 'by-handle-file-information :pointer buff)))

(defun filetime-to-int (filetime)
  "Returns the number of 100-nanosecond intervals since January 1, 1601 (UTC)."
  (+ (ash (getf filetime 'high-date-time) (* 8 (foreign-type-size 'dword)))
     (getf filetime 'low-date-time)))

(defun file-information-creation-time (file-information)
  (filetime-to-int (slot-value file-information 'creation-time)))

(defun file-information-last-access-time (file-information)
  (filetime-to-int (slot-value file-information 'last-access-time)))

(defun file-information-last-write-time (file-information)
  (filetime-to-int (slot-value file-information 'last-write-time)))

(defun file-information-volume-serial-number (file-information)
  (slot-value file-information 'volume-serial-number))

(defun file-information-number-of-links (file-information)
  (slot-value file-information 'number-of-links))

(defun file-information-file-index (file-information)
  (logior (ash (slot-value file-information 'file-index-high) (* 8 (foreign-type-size 'dword)))
          (slot-value file-information 'file-index-low)))

(defun file-information-file-attributes (file-information)
  (slot-value file-information 'file-attributes))

;;; IO Control

(defun reparse-data-buffer-is-symbolic-link-p (buffer)
  (let ((reparse-tag (foreign-slot-value buffer '(:struct reparse-data-buffer) 'reparse-tag)))
    (= reparse-tag (foreign-enum-value 'io-reparse-tag :symlink))))

(defun handle-is-symbolic-link-p (handle)
  (and (member :attribute-reparse-point
               (file-information-file-attributes (get-file-information-by-handle handle)))
       (with-foreign-object (buffer '(:struct reparse-data-buffer))
         (device-io-control handle :fsctl-get-reparse-point
                            (null-pointer) 0
                            buffer (foreign-type-size '(:struct reparse-data-buffer))
                            (null-pointer) (null-pointer))
         (reparse-data-buffer-is-symbolic-link-p buffer))))

(defun get-symbolic-link-target-by-handle (handle)
  "Given the handle to a symlink (must be opened with
:FLAG-OPEN-REPARSE-POINT), return the target."
  ;; win32 API provides no nice way to do this, so we use an ioctl.
  (assert (member :attribute-reparse-point
                  (file-information-file-attributes (get-file-information-by-handle handle))))
  (with-foreign-object (buffer '(:struct reparse-data-buffer))
    (device-io-control handle :fsctl-get-reparse-point
                       (null-pointer) 0
                       buffer (foreign-type-size '(:struct reparse-data-buffer))
                       (null-pointer) (null-pointer))
    (assert (reparse-data-buffer-is-symbolic-link-p buffer))
    (let* ((buffer-pointer (foreign-slot-pointer buffer '(:struct reparse-data-buffer) 'buffer))
           (path-buffer-pointer (foreign-slot-pointer buffer-pointer
                                                      '(:struct symbolic-link-reparse-buffer)
                                                      'path-buffer))
           (name-offset (foreign-slot-value buffer-pointer '(:struct symbolic-link-reparse-buffer)
                                            'substitute-name-offset))
           (name-length (foreign-slot-value buffer-pointer '(:struct symbolic-link-reparse-buffer)
                                            'substitute-name-length))
           (raw-target (wstring-to-string (mem-aptr path-buffer-pointer 'wchar
                                                    (/ name-offset (foreign-type-size 'wchar)))
                                          (/ name-length (foreign-type-size 'wchar)))))
      ;; If the target is absolute, it may start with \??\. If that exists,
      ;; strip it off.
      (when (and (>= (length raw-target) 4)
                 (string= "\\??\\" (subseq raw-target 0 4)))
          (setf raw-target (subseq raw-target 4)))
      ;; Furthermore, the target may start with \\?\ if the pathname is very
      ;; long. Strip that off as well.
      (when (and (>= (length raw-target) 4)
                 (string= "\\\\?\\" (subseq raw-target 0 4)))
        (setf raw-target (subseq raw-target 4)))
      raw-target)))