Skip to content

Commit 9f648dc

Browse files
committed
Bug 1448426 - Wrap windows.h to avoid problematic define statements, r=froydnj,glandium
By default, windows.h exposes a large number of problematic define statements which are UpperCamelCase, such as a define from `CreateWindow` to `CreateWindow{A,W}`. As many of these names are generic (e.g. CreateFile, CreateWindow), they can mess up Gecko code that may legitimately have its own methods with the same names. The header also defines some traditional SCREAMING_SNAKE_CASE defines which can mess up our code by conflicting with local values. This patch adds a simple code generator which generates wrappers for these defines, and uses them to wrap the windows.h wrapper using the `stl_wrappers` mechanism, allowing us to use windows.h in more places. Differential Revision: https://phabricator.services.mozilla.com/D10932
1 parent 693b3e6 commit 9f648dc

File tree

14 files changed

+1301
-28
lines changed

14 files changed

+1301
-28
lines changed

config/make-stl-wrappers.py

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,9 @@
55
import os
66
import string
77
from mozbuild.util import FileAvoidWrite
8+
from system_header_util import header_path
89

910

10-
def find_in_path(file, searchpath):
11-
for dir in searchpath.split(os.pathsep):
12-
f = os.path.join(dir, file)
13-
if os.path.exists(f):
14-
return f
15-
return ''
16-
17-
18-
def header_path(header, compiler):
19-
if compiler == 'gcc':
20-
# we use include_next on gcc
21-
return header
22-
elif compiler == 'msvc':
23-
return find_in_path(header, os.environ.get('INCLUDE', ''))
24-
else:
25-
# hope someone notices this ...
26-
raise NotImplementedError(compiler)
27-
2811
# The 'unused' arg is the output file from the file_generate action. We actually
2912
# generate all the files in header_list
3013

config/make-windows-h-wrapper.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# This Source Code Form is subject to the terms of the Mozilla Public
2+
# License, v. 2.0. If a copy of the MPL was not distributed with this
3+
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4+
5+
import re
6+
import textwrap
7+
import string
8+
from system_header_util import header_path
9+
10+
comment_re = re.compile(r'//[^\n]*\n|/\*.*\*/', re.S)
11+
decl_re = re.compile(r'''^(.+)\s+ # type
12+
(\w+)\s* # name
13+
(?:\((.*)\))?$ # optional param tys
14+
''', re.X | re.S)
15+
16+
17+
def read_decls(filename):
18+
"""Parse & yield C-style decls from an input file"""
19+
with open(filename, 'r') as fd:
20+
# Strip comments from the source text.
21+
text = comment_re.sub('', fd.read())
22+
23+
# Parse individual declarations.
24+
raw_decls = [d.strip() for d in text.split(';') if d.strip()]
25+
for raw in raw_decls:
26+
match = decl_re.match(raw)
27+
if match is None:
28+
raise "Invalid decl: %s" % raw
29+
30+
ty, name, params = match.groups()
31+
if params is not None:
32+
params = [a.strip() for a in params.split(',') if a.strip()]
33+
yield ty, name, params
34+
35+
36+
def generate(fd, consts_path, unicodes_path, template_path, compiler):
37+
# Parse the template
38+
with open(template_path, 'r') as template_fd:
39+
template = string.Template(template_fd.read())
40+
41+
decls = ''
42+
43+
# Each constant should be saved to a temporary, and then re-assigned to a
44+
# constant with the correct name, allowing the value to be determined by
45+
# the actual definition.
46+
for ty, name, args in read_decls(consts_path):
47+
assert args is None, "parameters in const decl!"
48+
49+
decls += textwrap.dedent("""
50+
#ifdef {name}
51+
constexpr {ty} _tmp_{name} = {name};
52+
#undef {name}
53+
constexpr {ty} {name} = _tmp_{name};
54+
#endif
55+
""".format(ty=ty, name=name))
56+
57+
# Each unicode declaration defines a static inline function with the
58+
# correct types which calls the 'A' or 'W'-suffixed versions of the
59+
# function. Full types are required here to ensure that '0' to 'nullptr'
60+
# coersions are preserved.
61+
for ty, name, args in read_decls(unicodes_path):
62+
assert args is not None, "argument list required for unicode decl"
63+
64+
# Parameter & argument string list
65+
params = ', '.join('%s a%d' % (ty, i) for i, ty in enumerate(args))
66+
args = ', '.join('a%d' % i for i in range(len(args)))
67+
68+
decls += textwrap.dedent("""
69+
#ifdef {name}
70+
#undef {name}
71+
static inline {ty} WINAPI
72+
{name}({params})
73+
{{
74+
#ifdef UNICODE
75+
return {name}W({args});
76+
#else
77+
return {name}A({args});
78+
#endif
79+
}}
80+
#endif
81+
""".format(ty=ty, name=name, params=params, args=args))
82+
83+
path = header_path('windows.h', compiler)
84+
85+
# Write out the resulting file
86+
fd.write(template.substitute(header_path=path, decls=decls))

config/moz.build

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@ if CONFIG['WRAP_STL_INCLUDES']:
6363
stl.flags = [output_dir, stl_compiler, template_file]
6464
stl.flags.extend(stl_headers)
6565

66+
# Wrap <windows.h> to make it easier to use correctly
67+
# NOTE: If we aren't wrapping STL includes, we're building part of the browser
68+
# which won't need this wrapper, such as L10N. Just don't try to generate the
69+
# wrapper in that case.
70+
if CONFIG['OS_ARCH'] == 'WINNT':
71+
GENERATED_FILES += ['../dist/stl_wrappers/windows.h']
72+
windows_h = GENERATED_FILES['../dist/stl_wrappers/windows.h']
73+
windows_h.script = 'make-windows-h-wrapper.py:generate'
74+
windows_h.inputs = ['windows-h-constant.decls.h',
75+
'windows-h-unicode.decls.h',
76+
'windows-h-wrapper.template.h']
77+
windows_h.flags = [stl_compiler]
78+
6679
if CONFIG['WRAP_SYSTEM_INCLUDES']:
6780
include('system-headers.mozbuild')
6881
output_dir = '../dist/system_wrappers'

config/system_header_util.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import os
2+
3+
4+
def find_in_path(file, searchpath):
5+
for dir in searchpath.split(os.pathsep):
6+
f = os.path.join(dir, file)
7+
if os.path.exists(f):
8+
return f
9+
return ''
10+
11+
12+
def header_path(header, compiler):
13+
if compiler == 'gcc':
14+
# we use include_next on gcc
15+
return header
16+
elif compiler == 'msvc':
17+
return find_in_path(header, os.environ.get('INCLUDE', ''))
18+
else:
19+
# hope someone notices this ...
20+
raise NotImplementedError(compiler)

config/windows-h-constant.decls.h

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2+
/* vim: set ts=2 et sw=2 tw=80: */
3+
/* This Source Code Form is subject to the terms of the Mozilla Public
4+
* License, v. 2.0. If a copy of the MPL was not distributed with this
5+
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6+
7+
/*
8+
* This file contains a series of C-style declarations for constants defined in
9+
* windows.h using #define. Adding a new constant should be a simple as adding
10+
* its name (and optionally type) to this file.
11+
*
12+
* This file is processed by generate-windows-h-wrapper.py to generate a wrapper
13+
* for the header which removes the defines usually implementing these constants.
14+
*
15+
* Wrappers defined in this file will be declared as `constexpr` values,
16+
* and will have their value derived from the windows.h define.
17+
*
18+
* NOTE: This is *NOT* a real C header, but rather an input to the avove script.
19+
* Only basic declarations in the form found here are allowed.
20+
*/
21+
22+
// XXX(nika): There are a lot of these (>30k)!
23+
// This is just a set of ones I saw in a quick scan which looked problematic.
24+
25+
auto CREATE_NEW;
26+
auto CREATE_ALWAYS;
27+
auto OPEN_EXISTING;
28+
auto OPEN_ALWAYS;
29+
auto TRUNCATE_EXISTING;
30+
auto INVALID_FILE_SIZE;
31+
auto INVALID_SET_FILE_POINTER;
32+
auto INVALID_FILE_ATTRIBUTES;
33+
34+
auto ANSI_NULL;
35+
auto UNICODE_NULL;
36+
37+
auto MINCHAR;
38+
auto MAXCHAR;
39+
auto MINSHORT;
40+
auto MAXSHORT;
41+
auto MINLONG;
42+
auto MAXLONG;
43+
auto MAXBYTE;
44+
auto MAXWORD;
45+
auto MAXDWORD;
46+
47+
auto DELETE;
48+
auto READ_CONTROL;
49+
auto WRITE_DAC;
50+
auto WRITE_OWNER;
51+
auto SYNCHRONIZE;
52+
53+
auto MAXIMUM_ALLOWED;
54+
auto GENERIC_READ;
55+
auto GENERIC_WRITE;
56+
auto GENERIC_EXECUTE;
57+
auto GENERIC_ALL;

0 commit comments

Comments
 (0)