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