xref: /reactos/sdk/cmake/msvc.cmake (revision 37b2c145)
1
2#if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
3if(CMAKE_BUILD_TYPE STREQUAL "Debug")
4    # no optimization
5    add_compile_flags("/Ob0 /Od")
6elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
7    add_compile_flags("/Ox /Ob2 /Ot /Oy /GT")
8    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /OPT:REF /OPT:ICF")
9elseif(OPTIMIZE STREQUAL "1")
10    add_compile_flags("/O1")
11elseif(OPTIMIZE STREQUAL "2")
12    add_compile_flags("/O2")
13elseif(OPTIMIZE STREQUAL "3")
14    add_compile_flags("/Ot /Ox /GS-")
15elseif(OPTIMIZE STREQUAL "4")
16    add_compile_flags("/Os /Ox /GS-")
17elseif(OPTIMIZE STREQUAL "5")
18    add_compile_flags("/Gy /Ob2 /Os /Ox /GS-")
19endif()
20
21# Always use string pooling: this helps reducing the binaries size since a lot
22# of redundancy come from the usage of __FILE__ / __RELFILE__ in the debugging
23# helper macros. Note also that GCC builds use string pooling by default.
24add_compile_flags("/GF")
25
26# Enable function level linking and comdat folding
27add_compile_flags("/Gy")
28set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /OPT:REF /OPT:ICF")
29set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /OPT:REF /OPT:ICF")
30set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /OPT:REF /OPT:ICF")
31
32if(ARCH STREQUAL "i386")
33    add_definitions(/DWIN32 /D_WINDOWS)
34endif()
35
36add_definitions(/Dinline=__inline /D__STDC__=1)
37
38# Ignore any "standard" include paths, and do not use any default CRT library.
39if(NOT USE_CLANG_CL)
40    add_compile_flags("/X /Zl")
41endif()
42
43# Disable RTTI, exception handling and buffer security checks by default.
44# These require run-time support that may not always be available.
45add_compile_flags("/GR- /EHs-c- /GS-")
46
47if(USE_CLANG_CL)
48    set(CMAKE_CL_SHOWINCLUDES_PREFIX "Note: including file: ")
49endif()
50
51# HACK: for VS 11+ we need to explicitly disable SSE, which is off by
52# default for older compilers. See CORE-6507
53if(MSVC_VERSION GREATER 1699 AND ARCH STREQUAL "i386")
54    add_compile_flags("/arch:IA32")
55endif ()
56
57# VS 12+ requires /FS when used in parallel compilations
58if(MSVC_VERSION GREATER 1799 AND NOT MSVC_IDE)
59    add_compile_flags("/FS")
60endif ()
61
62# VS14+ tries to use thread-safe initialization
63if(MSVC_VERSION GREATER 1899)
64    add_compile_flags("/Zc:threadSafeInit-")
65endif ()
66
67# HACK: Disable use of __CxxFrameHandler4 on VS 16.3+ (x64 only)
68# See https://developercommunity.visualstudio.com/content/problem/746534/visual-c-163-runtime-uses-an-unsupported-api-for-u.html
69if(ARCH STREQUAL "amd64" AND MSVC_VERSION GREATER 1922)
70    add_compile_flags("/d2FH4-")
71    add_link_options("/d2:-FH4-")
72endif ()
73
74# Generate Warnings Level 3
75add_compile_flags("/W3")
76
77# Disable overly sensitive warnings as well as those that generally aren't
78# useful to us.
79# - C4244: implicit integer truncation
80# - C4290: C++ exception specification ignored
81# - C4800: forcing value to bool 'true' or 'false' (performance warning)
82# - C4200: nonstandard extension used : zero-sized array in struct/union
83# - C4214: nonstandard extension used : bit field types other than int
84add_compile_flags("/wd4244 /wd4290 /wd4800 /wd4200 /wd4214")
85
86# FIXME: Temporarily disable C4018 until we fix more of the others. CORE-10113
87add_compile_flags("/wd4018")
88
89# The following warnings are treated as errors:
90# - C4013: implicit function declaration
91# - C4020: too many actual parameters
92# - C4022: pointer type mismatch for parameter
93# - C4028: formal parameter different from declaration
94# - C4047: different level of indirection
95# - TODO: C4090: different 'modifier' qualifiers (for C programs only;
96#          for C++ programs, the compiler error C2440 is issued)
97# - C4098: void function returning a value
98# - C4101: unreferenced local variable
99# - C4113: parameter lists differ
100# - C4129: unrecognized escape sequence
101# - C4133: incompatible types - from '<x> *' to '<y> *'
102# - C4163: 'identifier': not available as an intrinsic function
103# - C4229: modifiers on data are ignored
104# - C4311: pointer truncation from '<pointer>' to '<integer>'
105# - C4312: conversion from '<integer>' to '<pointer>' of greater size
106# - C4313: 'fprintf': '%x' in format string conflicts with argument n of type 'HANDLE'
107# - C4477: '_snprintf' : format string '%ld' requires an argument of type 'long', but variadic argument 1 has type 'DWORD_PTR'
108# - C4603: macro is not defined or definition is different after precompiled header use
109# - C4700: uninitialized variable usage
110# - C4715: 'function': not all control paths return a value
111# - C4716: function must return a value
112add_compile_flags("/we4013 /we4020 /we4022 /we4028 /we4047 /we4098 /we4101 /we4113 /we4129 /we4133 /we4163 /we4229 /we4311 /we4312 /we4313 /we4477 /we4603 /we4700 /we4715 /we4716")
113
114# - C4189: local variable initialized but not referenced
115# Not in Release mode and not with MSVC 2010
116if((NOT CMAKE_BUILD_TYPE STREQUAL "Release") AND (NOT MSVC_VERSION LESS 1700))
117    add_compile_flags("/we4189")
118endif()
119
120# Enable warnings above the default level, but don't treat them as errors:
121# - C4115: named type definition in parentheses
122add_compile_flags("/w14115")
123
124if(USE_CLANG_CL)
125    add_compile_flags_language("-nostdinc -Wno-multichar -Wno-char-subscripts -Wno-microsoft-enum-forward-reference -Wno-pragma-pack -Wno-microsoft-anon-tag -Wno-parentheses-equality -Wno-unknown-pragmas" "C")
126    add_compile_flags_language("-nostdinc -Wno-multichar -Wno-char-subscripts -Wno-microsoft-enum-forward-reference -Wno-pragma-pack -Wno-microsoft-anon-tag -Wno-parentheses-equality -Wno-unknown-pragmas" "CXX")
127endif()
128
129# Debugging
130#if(${CMAKE_BUILD_TYPE} STREQUAL "Debug")
131if(CMAKE_BUILD_TYPE STREQUAL "Debug")
132    if(NOT (_PREFAST_ OR _VS_ANALYZE_))
133        add_compile_flags("/Zi")
134    endif()
135#elseif(${CMAKE_BUILD_TYPE} STREQUAL "Release")
136elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
137    add_definitions("/D NDEBUG")
138endif()
139
140# Hotpatchable images
141if(ARCH STREQUAL "i386")
142    if(NOT USE_CLANG_CL)
143        add_compile_flags("/hotpatch")
144    endif()
145    set(_hotpatch_link_flag "/FUNCTIONPADMIN:5")
146elseif(ARCH STREQUAL "amd64")
147    set(_hotpatch_link_flag "/FUNCTIONPADMIN:6")
148endif()
149
150if(MSVC_IDE AND (NOT DEFINED USE_FOLDER_STRUCTURE))
151    set(USE_FOLDER_STRUCTURE TRUE)
152endif()
153
154if(RUNTIME_CHECKS)
155    add_definitions(-D__RUNTIME_CHECKS__)
156    add_compile_flags("/RTC1")
157endif()
158
159set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /MANIFEST:NO /INCREMENTAL:NO /SAFESEH:NO /NODEFAULTLIB /RELEASE ${_hotpatch_link_flag} /IGNORE:4039")
160set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /MANIFEST:NO /INCREMENTAL:NO /SAFESEH:NO /NODEFAULTLIB /RELEASE ${_hotpatch_link_flag} /IGNORE:4104 /IGNORE:4039")
161set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} /MANIFEST:NO /INCREMENTAL:NO /SAFESEH:NO /NODEFAULTLIB /RELEASE ${_hotpatch_link_flag} /IGNORE:4039")
162
163# HACK: Remove the /implib argument, implibs are generated separately
164string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE}")
165string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE}")
166string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
167string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY}")
168string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_C_CREATE_SHARED_MODULE "${CMAKE_C_CREATE_SHARED_MODULE}")
169string(REPLACE "/implib:<TARGET_IMPLIB>" "" CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE}")
170
171if(CMAKE_DISABLE_NINJA_DEPSLOG)
172    set(cl_includes_flag "")
173else()
174    set(cl_includes_flag "/showIncludes")
175endif()
176
177if(MSVC_IDE AND (CMAKE_VERSION MATCHES "ReactOS"))
178    # For VS builds we'll only have en-US in resource files
179    add_definitions(/DLANGUAGE_EN_US)
180else()
181    if(CMAKE_VERSION VERSION_LESS 3.4.0)
182        set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> /nologo <FLAGS> <DEFINES> ${I18N_DEFS} /fo<OBJECT> <SOURCE>")
183        if(ARCH STREQUAL "arm")
184            set(CMAKE_ASM_COMPILE_OBJECT
185                "cl ${cl_includes_flag} /nologo /X /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm <FLAGS> <DEFINES> /D__ASM__ /D_USE_ML /EP /c <SOURCE> > <OBJECT>.tmp"
186                "<CMAKE_ASM_COMPILER> -nologo -o <OBJECT> <OBJECT>.tmp")
187        else()
188            set(CMAKE_ASM_COMPILE_OBJECT
189                "cl ${cl_includes_flag} /nologo /X /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm <FLAGS> <DEFINES> /D__ASM__ /D_USE_ML /EP /c <SOURCE> > <OBJECT>.tmp"
190                "<CMAKE_ASM_COMPILER> /nologo /Cp /Fo<OBJECT> /c /Ta <OBJECT>.tmp")
191        endif()
192    else()
193        set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> /nologo <INCLUDES> <FLAGS> <DEFINES> ${I18N_DEFS} /fo<OBJECT> <SOURCE>")
194        if(ARCH STREQUAL "arm")
195            set(CMAKE_ASM_COMPILE_OBJECT
196                "cl ${cl_includes_flag} /nologo /X /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm <INCLUDES> <FLAGS> <DEFINES> /D__ASM__ /D_USE_ML /EP /c <SOURCE> > <OBJECT>.tmp"
197                "<CMAKE_ASM_COMPILER> -nologo -o <OBJECT> <OBJECT>.tmp")
198        else()
199            set(CMAKE_ASM_COMPILE_OBJECT
200                "cl ${cl_includes_flag} /nologo /X /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm <INCLUDES> <FLAGS> <DEFINES> /D__ASM__ /D_USE_ML /EP /c <SOURCE> > <OBJECT>.tmp"
201                "<CMAKE_ASM_COMPILER> /nologo /Cp /Fo<OBJECT> /c /Ta <OBJECT>.tmp")
202        endif()
203    endif()
204endif()
205
206if(_VS_ANALYZE_)
207    message("VS static analysis enabled!")
208    add_compile_flags("/analyze")
209elseif(_PREFAST_)
210    message("PREFAST enabled!")
211    if(CMAKE_VERSION VERSION_LESS 3.4.0)
212        set(CMAKE_C_COMPILE_OBJECT "prefast <CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_CL_NOLOGO} <FLAGS> <DEFINES> /Fo<OBJECT> -c <SOURCE>${CMAKE_END_TEMP_FILE}"
213        "prefast LIST")
214        set(CMAKE_CXX_COMPILE_OBJECT "prefast <CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_CL_NOLOGO} <FLAGS> <DEFINES> /TP /Fo<OBJECT> -c <SOURCE>${CMAKE_END_TEMP_FILE}"
215        "prefast LIST")
216        set(CMAKE_C_LINK_EXECUTABLE
217        "<CMAKE_C_COMPILER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} <FLAGS> /Fe<TARGET> -link /implib:<TARGET_IMPLIB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
218        set(CMAKE_CXX_LINK_EXECUTABLE
219        "<CMAKE_CXX_COMPILER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} <FLAGS> /Fe<TARGET> -link /implib:<TARGET_IMPLIB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
220    else()
221        set(CMAKE_C_COMPILE_OBJECT "prefast <CMAKE_C_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_CL_NOLOGO} <INCLUDES> <FLAGS> <DEFINES> /Fo<OBJECT> -c <SOURCE>${CMAKE_END_TEMP_FILE}"
222        "prefast LIST")
223        set(CMAKE_CXX_COMPILE_OBJECT "prefast <CMAKE_CXX_COMPILER> ${CMAKE_START_TEMP_FILE} ${CMAKE_CL_NOLOGO} <INCLUDES> <FLAGS> <DEFINES> /TP /Fo<OBJECT> -c <SOURCE>${CMAKE_END_TEMP_FILE}"
224        "prefast LIST")
225        set(CMAKE_C_LINK_EXECUTABLE
226        "<CMAKE_C_COMPILER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} <INCLUDES> <FLAGS> /Fe<TARGET> -link /implib:<TARGET_IMPLIB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
227        set(CMAKE_CXX_LINK_EXECUTABLE
228        "<CMAKE_CXX_COMPILER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} <INCLUDES> <FLAGS> /Fe<TARGET> -link /implib:<TARGET_IMPLIB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
229    endif()
230endif()
231
232set(CMAKE_RC_CREATE_SHARED_LIBRARY ${CMAKE_C_CREATE_SHARED_LIBRARY})
233set(CMAKE_ASM_CREATE_SHARED_LIBRARY ${CMAKE_C_CREATE_SHARED_LIBRARY})
234set(CMAKE_RC_CREATE_SHARED_MODULE ${CMAKE_C_CREATE_SHARED_MODULE})
235set(CMAKE_ASM_CREATE_SHARED_MODULE ${CMAKE_C_CREATE_SHARED_MODULE})
236set(CMAKE_ASM_CREATE_STATIC_LIBRARY ${CMAKE_C_CREATE_STATIC_LIBRARY})
237
238if(PCH)
239    macro(add_pch _target _pch _sources)
240
241        # Workaround for the MSVC toolchain (MSBUILD) /MP bug
242        set(_temp_gch ${CMAKE_CURRENT_BINARY_DIR}/${_target}.pch)
243        if(MSVC_IDE)
244            file(TO_NATIVE_PATH ${_temp_gch} _gch)
245        else()
246            set(_gch ${_temp_gch})
247        endif()
248
249        if(IS_CPP)
250            set(_pch_language CXX)
251            if(NOT USE_CLANG_CL)
252                set(_cl_lang_flag "/TP")
253            endif()
254        else()
255            set(_pch_language C)
256            set(_cl_lang_flag "/TC")
257        endif()
258
259        if(MSVC_IDE)
260            set(_pch_path_name_flag "/Fp${_gch}")
261        endif()
262
263        if(USE_CLANG_CL)
264            set(_pch_compile_flags "${_cl_lang_flag} /Yc${_pch} /FI${_pch} /Fp${_gch}")
265        else()
266            set(_pch_compile_flags "${_cl_lang_flag} /Yc /Fp${_gch}")
267        endif()
268
269        # Build the precompiled header
270        # HEADER_FILE_ONLY FALSE: force compiling the header
271        set_source_files_properties(${_pch} PROPERTIES
272            HEADER_FILE_ONLY FALSE
273            LANGUAGE ${_pch_language}
274            COMPILE_FLAGS ${_pch_compile_flags}
275            OBJECT_OUTPUTS ${_gch})
276
277        # Prevent a race condition related to writing to the PDB files between the PCH and the excluded list of source files
278        get_target_property(_target_sources ${_target} SOURCES)
279        list(REMOVE_ITEM _target_sources ${_pch})
280        foreach(_target_src ${_target_sources})
281            set_property(SOURCE ${_target_src} APPEND PROPERTY OBJECT_DEPENDS ${_gch})
282        endforeach()
283
284        # Use the precompiled header with the specified source files, skipping the pch itself
285        list(REMOVE_ITEM ${_sources} ${_pch})
286        foreach(_src ${${_sources}})
287            set_property(SOURCE ${_src} APPEND_STRING PROPERTY COMPILE_FLAGS " /FI${_gch} /Yu${_gch} ${_pch_path_name_flag}")
288        endforeach()
289    endmacro()
290else()
291    macro(add_pch _target _pch _sources)
292    endmacro()
293endif()
294
295function(set_entrypoint _module _entrypoint)
296    if(${_entrypoint} STREQUAL "0")
297        add_target_link_flags(${_module} "/NOENTRY")
298    elseif(ARCH STREQUAL "i386")
299        set(_entrysymbol ${_entrypoint})
300        if(${ARGC} GREATER 2)
301            set(_entrysymbol ${_entrysymbol}@${ARGV2})
302        endif()
303        add_target_link_flags(${_module} "/ENTRY:${_entrysymbol}")
304    else()
305        add_target_link_flags(${_module} "/ENTRY:${_entrypoint}")
306    endif()
307endfunction()
308
309function(set_subsystem MODULE SUBSYSTEM)
310    string(TOUPPER ${SUBSYSTEM} _subsystem)
311    if(ARCH STREQUAL "amd64")
312        add_target_link_flags(${MODULE} "/SUBSYSTEM:${_subsystem},5.02")
313    elseif(ARCH STREQUAL "arm")
314        add_target_link_flags(${MODULE} "/SUBSYSTEM:${_subsystem},6.02")
315    else()
316        add_target_link_flags(${MODULE} "/SUBSYSTEM:${_subsystem},5.01")
317    endif()
318endfunction()
319
320function(set_image_base MODULE IMAGE_BASE)
321    add_target_link_flags(${MODULE} "/BASE:${IMAGE_BASE}")
322endfunction()
323
324function(set_module_type_toolchain MODULE TYPE)
325    if(CPP_USE_STL)
326        if((${TYPE} STREQUAL "kernelmodedriver") OR (${TYPE} STREQUAL "wdmdriver"))
327            message(FATAL_ERROR "Use of STL in kernelmodedriver or wdmdriver type module prohibited")
328        endif()
329        target_link_libraries(${MODULE} cpprt stlport oldnames)
330    elseif(CPP_USE_RT)
331        target_link_libraries(${MODULE} cpprt)
332    endif()
333    if((${TYPE} STREQUAL "win32dll") OR (${TYPE} STREQUAL "win32ocx") OR (${TYPE} STREQUAL "cpl"))
334        add_target_link_flags(${MODULE} "/DLL")
335    elseif(${TYPE} STREQUAL "kernelmodedriver")
336        # Disable linker warning 4078 (multiple sections found with different attributes) for INIT section use
337        add_target_link_flags(${MODULE} "/DRIVER /IGNORE:4078 /SECTION:INIT,D")
338    elseif(${TYPE} STREQUAL "wdmdriver")
339        add_target_link_flags(${MODULE} "/DRIVER:WDM /IGNORE:4078 /SECTION:INIT,D")
340    endif()
341
342    if(RUNTIME_CHECKS)
343        target_link_libraries(${MODULE} runtmchk)
344    endif()
345
346endfunction()
347
348# Define those for having real libraries
349set(CMAKE_IMPLIB_CREATE_STATIC_LIBRARY "LINK /LIB /NOLOGO <LINK_FLAGS> /OUT:<TARGET> <OBJECTS>")
350
351if(ARCH STREQUAL "arm")
352    set(CMAKE_STUB_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -nologo -o <OBJECT> <SOURCE>")
353else()
354    set(CMAKE_STUB_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> /nologo /Cp /Fo<OBJECT> /c /Ta <SOURCE>")
355endif()
356
357function(add_delay_importlibs _module)
358    get_target_property(_module_type ${_module} TYPE)
359    if(_module_type STREQUAL "STATIC_LIBRARY")
360        message(FATAL_ERROR "Cannot add delay imports to a static library")
361    endif()
362    foreach(_lib ${ARGN})
363        get_filename_component(_basename "${_lib}" NAME_WE)
364        get_filename_component(_ext "${_lib}" EXT)
365        if(NOT _ext)
366            set(_ext ".dll")
367        endif()
368        add_target_link_flags(${_module} "/DELAYLOAD:${_basename}${_ext}")
369        target_link_libraries(${_module} "lib${_basename}")
370    endforeach()
371    target_link_libraries(${_module} delayimp)
372endfunction()
373
374function(generate_import_lib _libname _dllname _spec_file)
375
376    set(_def_file ${CMAKE_CURRENT_BINARY_DIR}/${_libname}_exp.def)
377    set(_asm_stubs_file ${CMAKE_CURRENT_BINARY_DIR}/${_libname}_stubs.asm)
378
379    # Generate the asm stub file and the def file for import library
380    add_custom_command(
381        OUTPUT ${_asm_stubs_file} ${_def_file}
382        COMMAND native-spec2def --ms -a=${SPEC2DEF_ARCH} --implib -n=${_dllname} -d=${_def_file} -l=${_asm_stubs_file} ${CMAKE_CURRENT_SOURCE_DIR}/${_spec_file}
383        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${_spec_file} native-spec2def)
384
385    if(MSVC_IDE)
386        # Compile the generated asm stub file
387        if(ARCH STREQUAL "arm")
388            set(_asm_stub_command ${CMAKE_ASM_COMPILER} -nologo -o ${_asm_stubs_file}.obj ${_asm_stubs_file})
389        else()
390            set(_asm_stub_command ${CMAKE_ASM_COMPILER} /Cp /Fo${_asm_stubs_file}.obj /c /Ta ${_asm_stubs_file})
391        endif()
392        add_custom_command(
393            OUTPUT ${_asm_stubs_file}.obj
394            COMMAND ${_asm_stub_command}
395            DEPENDS ${_asm_stubs_file})
396    else()
397        # Be clear about the "language"
398        # Thanks MS for creating a stupid linker
399        set_source_files_properties(${_asm_stubs_file} PROPERTIES LANGUAGE "STUB_ASM")
400    endif()
401
402    # Add our library
403    if(MSVC_IDE)
404        add_library(${_libname} STATIC EXCLUDE_FROM_ALL ${_asm_stubs_file}.obj)
405        set_source_files_properties(${_asm_stubs_file}.obj PROPERTIES EXTERNAL_OBJECT TRUE)
406        set_target_properties(${_libname} PROPERTIES LINKER_LANGUAGE "C")
407    else()
408        # NOTE: as stub file and def file are generated in one pass, depending on one is like depending on the other
409        add_library(${_libname} STATIC EXCLUDE_FROM_ALL ${_asm_stubs_file})
410        # set correct "link rule"
411        set_target_properties(${_libname} PROPERTIES LINKER_LANGUAGE "IMPLIB")
412    endif()
413    set_target_properties(${_libname} PROPERTIES STATIC_LIBRARY_FLAGS "/DEF:${_def_file}")
414endfunction()
415
416if(ARCH STREQUAL "amd64")
417    # This is NOT a typo.
418    # See https://software.intel.com/en-us/forums/topic/404643
419    add_definitions(/D__x86_64)
420    set(SPEC2DEF_ARCH x86_64)
421elseif(ARCH STREQUAL "arm")
422    add_definitions(/D__arm__)
423    set(SPEC2DEF_ARCH arm)
424else()
425    set(SPEC2DEF_ARCH i386)
426endif()
427function(spec2def _dllname _spec_file)
428
429    cmake_parse_arguments(__spec2def "ADD_IMPORTLIB;NO_PRIVATE_WARNINGS;WITH_RELAY" "VERSION" "" ${ARGN})
430
431    # Get library basename
432    get_filename_component(_file ${_dllname} NAME_WE)
433
434    # Error out on anything else than spec
435    if(NOT ${_spec_file} MATCHES ".*\\.spec")
436        message(FATAL_ERROR "spec2def only takes spec files as input.")
437    endif()
438
439    if (__spec2def_WITH_RELAY)
440        set(__with_relay_arg "--with-tracing")
441    endif()
442
443    if(__spec2def_VERSION)
444        set(__version_arg "--version=0x${__spec2def_VERSION}")
445    endif()
446
447    # Generate exports def and C stubs file for the DLL
448    add_custom_command(
449        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${_file}.def ${CMAKE_CURRENT_BINARY_DIR}/${_file}_stubs.c
450        COMMAND native-spec2def --ms -a=${SPEC2DEF_ARCH} -n=${_dllname} -d=${CMAKE_CURRENT_BINARY_DIR}/${_file}.def -s=${CMAKE_CURRENT_BINARY_DIR}/${_file}_stubs.c ${__with_relay_arg} ${__version_arg} ${CMAKE_CURRENT_SOURCE_DIR}/${_spec_file}
451        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${_spec_file} native-spec2def)
452
453    if(__spec2def_ADD_IMPORTLIB)
454        generate_import_lib(lib${_file} ${_dllname} ${_spec_file})
455        if(__spec2def_NO_PRIVATE_WARNINGS)
456            add_target_property(lib${_file} STATIC_LIBRARY_FLAGS "/ignore:4104")
457        endif()
458    endif()
459endfunction()
460
461macro(macro_mc FLAG FILE)
462    set(COMMAND_MC ${CMAKE_MC_COMPILER} -u ${FLAG} -b -h ${CMAKE_CURRENT_BINARY_DIR}/ -r ${CMAKE_CURRENT_BINARY_DIR}/ ${FILE})
463endmacro()
464
465# PSEH workaround
466set(PSEH_LIB "pseh")
467
468# Use a full path for the x86 version of ml when using x64 VS.
469# It's not a problem when using the DDK/WDK because, in x64 mode,
470# both the x86 and x64 versions of ml are available.
471if((ARCH STREQUAL "amd64") AND (DEFINED ENV{VCToolsInstallDir}))
472    set(CMAKE_ASM16_COMPILER $ENV{VCToolsInstallDir}/bin/HostX86/x86/ml.exe)
473elseif((ARCH STREQUAL "amd64") AND (DEFINED ENV{VCINSTALLDIR}))
474    set(CMAKE_ASM16_COMPILER $ENV{VCINSTALLDIR}/bin/ml.exe)
475elseif(ARCH STREQUAL "arm")
476    set(CMAKE_ASM16_COMPILER armasm.exe)
477else()
478    set(CMAKE_ASM16_COMPILER ml.exe)
479endif()
480
481function(CreateBootSectorTarget _target_name _asm_file _binary_file _base_address)
482    set(_object_file ${_binary_file}.obj)
483    set(_temp_file ${_binary_file}.tmp)
484
485    get_defines(_defines)
486    get_includes(_includes)
487
488    if(USE_CLANG_CL)
489        set(_no_std_includes_flag "-nostdinc")
490    else()
491        set(_no_std_includes_flag "/X")
492    endif()
493
494    add_custom_command(
495        OUTPUT ${_temp_file}
496        COMMAND ${CMAKE_C_COMPILER} /nologo ${_no_std_includes_flag} /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm ${_includes} ${_defines} /D__ASM__ /D_USE_ML /EP /c ${_asm_file} > ${_temp_file}
497        DEPENDS ${_asm_file})
498
499    if(ARCH STREQUAL "arm")
500        set(_asm16_command ${CMAKE_ASM16_COMPILER} -nologo -o ${_object_file} ${_temp_file})
501    else()
502        set(_asm16_command ${CMAKE_ASM16_COMPILER} /nologo /Cp /Fo${_object_file} /c /Ta ${_temp_file})
503    endif()
504
505    add_custom_command(
506        OUTPUT ${_object_file}
507        COMMAND ${_asm16_command}
508        DEPENDS ${_temp_file})
509
510    add_custom_command(
511        OUTPUT ${_binary_file}
512        COMMAND native-obj2bin ${_object_file} ${_binary_file} ${_base_address}
513        DEPENDS ${_object_file} native-obj2bin)
514
515    set_source_files_properties(${_object_file} ${_temp_file} ${_binary_file} PROPERTIES GENERATED TRUE)
516
517    add_custom_target(${_target_name} ALL DEPENDS ${_binary_file})
518endfunction()
519
520function(allow_warnings __module)
521endfunction()
522
523macro(add_asm_files _target)
524    if(MSVC_IDE AND (CMAKE_VERSION MATCHES "ReactOS"))
525        get_defines(_directory_defines)
526        get_includes(_directory_includes)
527        get_directory_property(_defines COMPILE_DEFINITIONS)
528        foreach(_source_file ${ARGN})
529            get_filename_component(_source_file_base_name ${_source_file} NAME_WE)
530            get_filename_component(_source_file_full_path ${_source_file} ABSOLUTE)
531            set(_preprocessed_asm_file ${CMAKE_CURRENT_BINARY_DIR}/asm/${_source_file_base_name}_${_target}.tmp)
532            set(_object_file ${CMAKE_CURRENT_BINARY_DIR}/asm/${_source_file_base_name}_${_target}.obj)
533            get_source_file_property(_defines_semicolon_list ${_source_file_full_path} COMPILE_DEFINITIONS)
534            unset(_source_file_defines)
535            foreach(_define ${_defines_semicolon_list})
536                if(NOT ${_define} STREQUAL "NOTFOUND")
537                    list(APPEND _source_file_defines -D${_define})
538                endif()
539            endforeach()
540            if(ARCH STREQUAL "arm")
541                set(_pp_asm_compile_command ${CMAKE_ASM_COMPILER} -nologo -o ${_object_file} ${_preprocessed_asm_file})
542            else()
543                set(_pp_asm_compile_command ${CMAKE_ASM_COMPILER} /nologo /Cp /Fo${_object_file} /c /Ta ${_preprocessed_asm_file})
544            endif()
545            add_custom_command(
546                OUTPUT ${_preprocessed_asm_file} ${_object_file}
547                COMMAND cl /nologo /X /I${REACTOS_SOURCE_DIR}/sdk/include/asm /I${REACTOS_BINARY_DIR}/sdk/include/asm ${_directory_includes} ${_source_file_defines} ${_directory_defines} /D__ASM__ /D_USE_ML /EP /c ${_source_file_full_path} > ${_preprocessed_asm_file} && ${_pp_asm_compile_command}
548                DEPENDS ${_source_file_full_path})
549            set_source_files_properties(${_object_file} PROPERTIES EXTERNAL_OBJECT TRUE)
550            list(APPEND ${_target} ${_object_file})
551        endforeach()
552    else()
553        list(APPEND ${_target} ${ARGN})
554    endif()
555endmacro()
556
557function(add_linker_script _target _linker_script_file)
558    get_filename_component(_file_full_path ${_linker_script_file} ABSOLUTE)
559    get_filename_component(_file_name ${_linker_script_file} NAME)
560    set(_generated_file_path_prefix "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${_target}.dir/${_file_name}")
561
562    # Generate the ASM module containing sections specifications and layout.
563    set(_generated_file "${_generated_file_path_prefix}.S")
564    add_custom_command(
565        OUTPUT ${_generated_file}
566        COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${_file_full_path}" "${_generated_file}"
567        DEPENDS ${_file_full_path})
568    set_source_files_properties(${_generated_file} PROPERTIES LANGUAGE "ASM" GENERATED TRUE)
569    add_asm_files(${_target}_linker_file ${_generated_file})
570
571    # Generate the C module containing extra sections specifications and layout,
572    # as well as comment-type linker #pragma directives.
573    set(_generated_file "${_generated_file_path_prefix}.c")
574    add_custom_command(
575        OUTPUT ${_generated_file}
576        COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${_file_full_path}" "${_generated_file}"
577        DEPENDS ${_file_full_path})
578    set_source_files_properties(${_generated_file} PROPERTIES LANGUAGE "C" GENERATED TRUE)
579    list(APPEND ${_target}_linker_file ${_generated_file})
580
581    # Add both files to the sources of the target.
582    target_sources(${_target} PRIVATE "${${_target}_linker_file}")
583
584    # Create the additional linker response file.
585    set(_generated_file "${_generated_file_path_prefix}.rsp")
586    if(USE_CLANG_CL)
587        set(_no_std_includes_flag "-nostdinc")
588    else()
589        set(_no_std_includes_flag "/X")
590    endif()
591    if(MSVC_IDE AND (CMAKE_VERSION MATCHES "ReactOS"))
592        # MSBuild, via the VS IDE, uses response files when calling CL or LINK.
593        # We cannot specify a custom response file on the linker command-line,
594        # since specifying response files from within response files is forbidden.
595        # We therefore have to pre-process, at configuration time, the linker
596        # script so as to retrieve the custom linker options to be appended
597        # to the linker command-line.
598        execute_process(
599            COMMAND ${CMAKE_C_COMPILER} /nologo ${_no_std_includes_flag} /D__LINKER__ /EP /c "${_file_full_path}"
600            # OUTPUT_FILE "${_generated_file}"
601            OUTPUT_VARIABLE linker_options
602            ERROR_QUIET
603            WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
604            RESULT_VARIABLE linker_rsp_result
605            OUTPUT_STRIP_TRAILING_WHITESPACE)
606        if(NOT linker_rsp_result EQUAL 0)
607            message(FATAL_ERROR "Generating pre-processed linker options for target '${_target}' failed with error ${linker_rsp_result}.")
608        endif()
609        # file(STRINGS ${_generated_file} linker_options NEWLINE_CONSUME)
610        string(REGEX REPLACE "[\r\n]+" " " linker_options "${linker_options}")
611        add_target_link_flags(${_target} ${linker_options})
612    else()
613        # Generate at compile-time a linker response file and append it
614        # to the linker command-line.
615        add_custom_command(
616            # OUTPUT ${_generated_file}
617            TARGET ${_target} PRE_LINK # PRE_BUILD
618            COMMAND ${CMAKE_C_COMPILER} /nologo ${_no_std_includes_flag} /D__LINKER__ /EP /c "${_file_full_path}" > "${_generated_file}"
619            DEPENDS ${_file_full_path}
620            VERBATIM)
621        set_source_files_properties(${_generated_file} PROPERTIES GENERATED TRUE)
622        # add_custom_target("${_target}_${_file_name}" ALL DEPENDS ${_generated_file})
623        # add_dependencies(${_target} "${_target}_${_file_name}")
624        add_target_link_flags(${_target} "@${_generated_file}")
625        add_target_property(${_target} LINK_DEPENDS ${_file_full_path})
626    endif()
627endfunction()
628