1## On Windows co-operative applications can be expected to open LLD's output
2## with FILE_SHARE_DELETE included in the sharing mode. This allows us to link
3## over the top of an existing file even if it is in use by another application.
4
5# REQUIRES: system-windows, x86
6# RUN: echo '.globl _start; _start:' > %t.s
7# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-unknown %t.s -o %t.o
8
9## FILE_SHARE_READ   = 1
10## FILE_SHARE_WRITE  = 2
11## FILE_SHARE_DELETE = 4
12
13# RUN:     %python %s %t.o 7
14# RUN: not %python %s %t.o 3 2>&1 | FileCheck %s
15# CHECK: error: failed to write to the output file
16
17import contextlib
18import ctypes
19from ctypes import wintypes as w
20import os
21import shutil
22import subprocess
23import platform
24import sys
25import time
26
27object_file = sys.argv[1]
28share_flags = int(sys.argv[2])
29
30@contextlib.contextmanager
31def open_with_share_flags(filename, share_flags):
32    GENERIC_READ          = 0x80000000
33    FILE_ATTRIBUTE_NORMAL = 0x80
34    OPEN_EXISTING         = 0x3
35    INVALID_HANDLE_VALUE = w.HANDLE(-1).value
36
37    CreateFileA = ctypes.windll.kernel32.CreateFileA
38    CreateFileA.restype = w.HANDLE
39    h = CreateFileA(filename.encode('mbcs'), GENERIC_READ, share_flags,
40                    None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None)
41
42    assert h != INVALID_HANDLE_VALUE, 'Failed to open ' + filename
43    try:
44        yield
45    finally:
46        ctypes.windll.kernel32.CloseHandle(h)
47
48## Ensure we have an empty directory for the output.
49outdir = os.path.basename(__file__) + '.dir'
50if os.path.exists(outdir):
51    shutil.rmtree(outdir)
52os.makedirs(outdir)
53
54## Link on top of an open file.
55elf = os.path.join(outdir, 'output_file.elf')
56open(elf, 'wb').close()
57with open_with_share_flags(elf, share_flags):
58    subprocess.check_call(['ld.lld.exe', object_file, '-o', elf])
59
60## Check the linker wrote the output file.
61with open(elf, 'rb') as f:
62    assert f.read(4) == b'\x7fELF', "linker did not write output file correctly"
63
64## Check no temp files are left around.
65## It might take a while for Windows to remove them, so loop.
66deleted = lambda: len(os.listdir(outdir)) == 1
67for _ in range(10):
68    if not deleted():
69        time.sleep (1)
70
71assert deleted(), "temp file(s) not deleted after grace period"
72