From c4d1491af938a12a0167dae4fd3ea8f1810c752a Mon Sep 17 00:00:00 2001 From: dec05eba Date: Tue, 25 Sep 2018 20:47:40 +0200 Subject: Fix build for windows --- .gitignore | 1 + CMakeLists.txt | 10 +- README.md | 3 +- backend/ninja/Ninja.cpp | 14 +- msvc/git2.lib | Bin 0 -> 180678 bytes msvc/locate_windows_sdk.exe | Bin 0 -> 18432 bytes msvc/locate_windows_sdk/.gitignore | 4 + msvc/locate_windows_sdk/locate_sdk.cpp | 512 +++++++++++++++++++++ msvc/locate_windows_sdk/locate_sdk.hpp | 25 + msvc/locate_windows_sdk/locate_windows_sdk.sln | 31 ++ msvc/locate_windows_sdk/locate_windows_sdk.vcxproj | 159 +++++++ .../locate_windows_sdk.vcxproj.filters | 30 ++ .../locate_windows_sdk.vcxproj.user | 4 + msvc/locate_windows_sdk/main.cpp | Bin 0 -> 1504 bytes msvc/ninja.exe | Bin 0 -> 504320 bytes msvc/sibs.exe | Bin 415744 -> 321024 bytes sibs.sln | 31 -- sibs.vcxproj | 186 -------- sibs.vcxproj.filters | 249 ---------- sibs.vcxproj.user | 4 - src/Exec.cpp | 98 ++-- src/FileUtil.cpp | 49 +- src/main.cpp | 126 +++-- 23 files changed, 980 insertions(+), 556 deletions(-) create mode 100644 msvc/git2.lib create mode 100644 msvc/locate_windows_sdk.exe create mode 100644 msvc/locate_windows_sdk/.gitignore create mode 100644 msvc/locate_windows_sdk/locate_sdk.cpp create mode 100644 msvc/locate_windows_sdk/locate_sdk.hpp create mode 100644 msvc/locate_windows_sdk/locate_windows_sdk.sln create mode 100644 msvc/locate_windows_sdk/locate_windows_sdk.vcxproj create mode 100644 msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.filters create mode 100644 msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.user create mode 100644 msvc/locate_windows_sdk/main.cpp create mode 100644 msvc/ninja.exe delete mode 100644 sibs.sln delete mode 100644 sibs.vcxproj delete mode 100644 sibs.vcxproj.filters delete mode 100644 sibs.vcxproj.user diff --git a/.gitignore b/.gitignore index b086a97..3a593c3 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ cmake-build-debug/ compile_commands.json tests/sibs-build/ tests/compile_commands.json +cmake_msvc/ diff --git a/CMakeLists.txt b/CMakeLists.txt index b18c605..a58a3cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,5 +27,11 @@ find_package(LibArchive REQUIRED) add_executable(sibs ${SOURCE_FILES}) include_directories(${CURL_INCLUDE_DIR} ${LibArchive_INCLUDE_DIR} "depends/libninja/include") -target_link_libraries(sibs ${CURL_LIBRARIES} ${LibArchive_LIBRARIES} -lgit2) -target_compile_options(sibs PRIVATE -Wall -Wextra -Werror=return-type -fdiagnostics-show-option -fexceptions) + +if(WIN32) + target_link_libraries(sibs ${CURL_LIBRARIES} ${LibArchive_LIBRARIES} "${CMAKE_CURRENT_SOURCE_DIR}/msvc/git2.lib") + target_compile_options(sibs PRIVATE /Wall) +else() + target_link_libraries(sibs ${CURL_LIBRARIES} ${LibArchive_LIBRARIES} -lgit2) + target_compile_options(sibs PRIVATE -Wall -Wextra -Werror=return-type -fdiagnostics-show-option -fexceptions) +endif() diff --git a/README.md b/README.md index 41b71f6..2a62768 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,8 @@ Currently zig tests are cached because ninja build system is used, which means i Currently zig files generate header files and include exported functions into sibs-build/generated-headers/zig and the generated headers are usable from c/c++ by using including: `#include ` -The CMakeLists.txt is only for development purpose and only compiles on linux. +The CMakeLists.txt should only be used during development or when installing sibs for the first time. +To compile under windows you can use vcpkg to install dependencies and then generate visual studio project using cmake. List of packages can be found at https://gitlab.com/DEC05EBA/sibs_packages/raw/master/packages.json # Installation diff --git a/backend/ninja/Ninja.cpp b/backend/ninja/Ninja.cpp index 64f8f53..9220593 100644 --- a/backend/ninja/Ninja.cpp +++ b/backend/ninja/Ninja.cpp @@ -206,9 +206,10 @@ namespace backend { switch(cppVersion) { - case CPPVersion::CPP11: return { ninja::NinjaArg("/std=c++11") }; - case CPPVersion::CPP14: return { ninja::NinjaArg("/std=c++14") }; - case CPPVersion::CPP17: return { ninja::NinjaArg("/std=c++17") }; + // Use /Za flag? + case CPPVersion::CPP11: return { ninja::NinjaArg("/std:c++11") }; + case CPPVersion::CPP14: return { ninja::NinjaArg("/std:c++14") }; + case CPPVersion::CPP17: return { ninja::NinjaArg("/std:c++17") }; } break; } @@ -882,6 +883,11 @@ namespace backend else compileCCommand.push_back(ninja::NinjaArg("/w")); +// TODO: Remove this once locate_windows_sdk has been updated to locate multiple arch windows sdk +#if SYSTEM_PLATFORM == PLATFORM_WIN32 +#error "sibs is currently not supported on windows 32-bit because locate_windows_sdk can only locate x64 windows sdk" +#endif + switch (SYSTEM_PLATFORM) { case PLATFORM_WIN32: @@ -1435,7 +1441,7 @@ namespace backend ninja.sourceFiles.reserve(config.zigTestFiles.size()); for(const sibs::FileString &testFile : config.zigTestFiles) { - ninja.addSourceFile(sibs::Language::ZIG, testFile.c_str()); + ninja.addSourceFile(sibs::Language::ZIG, toUtf8(testFile.c_str()).c_str()); } zigTest = true; } diff --git a/msvc/git2.lib b/msvc/git2.lib new file mode 100644 index 0000000..238331e Binary files /dev/null and b/msvc/git2.lib differ diff --git a/msvc/locate_windows_sdk.exe b/msvc/locate_windows_sdk.exe new file mode 100644 index 0000000..6da61ac Binary files /dev/null and b/msvc/locate_windows_sdk.exe differ diff --git a/msvc/locate_windows_sdk/.gitignore b/msvc/locate_windows_sdk/.gitignore new file mode 100644 index 0000000..c0a8b2d --- /dev/null +++ b/msvc/locate_windows_sdk/.gitignore @@ -0,0 +1,4 @@ +.vs/ +x64/ +Release/ +Debug/ diff --git a/msvc/locate_windows_sdk/locate_sdk.cpp b/msvc/locate_windows_sdk/locate_sdk.cpp new file mode 100644 index 0000000..b025bdd --- /dev/null +++ b/msvc/locate_windows_sdk/locate_sdk.cpp @@ -0,0 +1,512 @@ +// +// Author: Jonathan Blow +// Version: 1 +// Date: 31 August, 2018 +// +// This code is released under the MIT license, which you can find at +// +// https://opensource.org/licenses/MIT +// +// +// +// See the comments for how to use this library just below the includes. +// + +// Modified by dec05eba to support x86 + +#include "locate_sdk.hpp" +#include +#include +#include +#include + +#include +#include // For _get_osfhandle + + +// +// HOW TO USE THIS CODE +// +// The purpose of this file is to find the folders that contain libraries +// you may need to link against, on Windows, if you are linking with any +// compiled C or C++ code. This will be necessary for many non-C++ programming +// language environments that want to provide compatibility. +// +// We find the place where the Visual Studio libraries live (for example, +// libvcruntime.lib), where the linker and compiler executables live +// (for example, link.exe), and where the Windows SDK libraries reside +// (kernel32.lib, libucrt.lib). +// +// We all wish you didn't have to worry about so many weird dependencies, +// but we don't really have a choice about this, sadly. +// +// I don't claim that this is the absolute best way to solve this problem, +// and so far we punt on things (if you have multiple versions of Visual Studio +// installed, we return the first one, rather than the newest). But it +// will solve the basic problem for you as simply as I know how to do it, +// and because there isn't too much code here, it's easy to modify and expand. + +// +// Call find_visual_studio_and_windows_sdk, look at the resulting +// paths, then call free_resources on the result. +// +// Everything else in this file is implementation details that you +// don't need to care about. +// + +// +// This file was about 400 lines before we started adding these comments. +// You might think that's way too much code to do something as simple +// as finding a few library and executable paths. I agree. However, +// Microsoft's own solution to this problem, called "vswhere", is a +// mere EIGHT THOUSAND LINE PROGRAM, spread across 70 files, +// that they posted to github *unironically*. +// +// I am not making this up: https://github.com/Microsoft/vswhere +// +// Several people have therefore found the need to solve this problem +// themselves. We referred to some of these other solutions when +// figuring out what to do, most prominently ziglang's version, +// by Ryan Saunderson. +// +// I hate this kind of code. The fact that we have to do this at all +// is stupid, and the actual maneuvers we need to go through +// are just painful. If programming were like this all the time, +// I would quit. +// +// Because this is such an absurd waste of time, I felt it would be +// useful to package the code in an easily-reusable way, in the +// style of the stb libraries. We haven't gone as all-out as some +// of the stb libraries do (which compile in C with no includes, often). +// For this version you need C++ and the headers at the top of the file. +// +// We return the strings as Windows wide character strings. Aesthetically +// I don't like that (I think most sane programs are UTF-8 internally), +// but apparently, not all valid Windows file paths can even be converted +// correctly to UTF-8. So have fun with that. It felt safest and simplest +// to stay with wchar_t since all of this code is fully ensconced in +// Windows crazy-land. + +// Defer macro/thing. + +#define CONCAT_INTERNAL(x,y) x##y +#define CONCAT(x,y) CONCAT_INTERNAL(x,y) + +template +struct ExitScope { + T lambda; + ExitScope(T lambda) :lambda(lambda) {} + ~ExitScope() { lambda(); } + ExitScope(const ExitScope&); +private: + ExitScope & operator =(const ExitScope&); +}; + +class ExitScopeHelp { +public: + template + ExitScope operator+(T t) { return t; } +}; + +#define defer const auto& CONCAT(defer__, __LINE__) = ExitScopeHelp() + [&]() + + +// COM objects for the ridiculous Microsoft craziness. + +struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown +{ + STDMETHOD(GetInstanceId)(_Out_ BSTR* pbstrInstanceId) = 0; + STDMETHOD(GetInstallDate)(_Out_ LPFILETIME pInstallDate) = 0; + STDMETHOD(GetInstallationName)(_Out_ BSTR* pbstrInstallationName) = 0; + STDMETHOD(GetInstallationPath)(_Out_ BSTR* pbstrInstallationPath) = 0; + STDMETHOD(GetInstallationVersion)(_Out_ BSTR* pbstrInstallationVersion) = 0; + STDMETHOD(GetDisplayName)(_In_ LCID lcid, _Out_ BSTR* pbstrDisplayName) = 0; + STDMETHOD(GetDescription)(_In_ LCID lcid, _Out_ BSTR* pbstrDescription) = 0; + STDMETHOD(ResolvePath)(_In_opt_z_ LPCOLESTR pwszRelativePath, _Out_ BSTR* pbstrAbsolutePath) = 0; +}; + +struct DECLSPEC_UUID("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848") DECLSPEC_NOVTABLE IEnumSetupInstances : public IUnknown +{ + STDMETHOD(Next)(_In_ ULONG celt, _Out_writes_to_(celt, *pceltFetched) ISetupInstance** rgelt, _Out_opt_ _Deref_out_range_(0, celt) ULONG* pceltFetched) = 0; + STDMETHOD(Skip)(_In_ ULONG celt) = 0; + STDMETHOD(Reset)(void) = 0; + STDMETHOD(Clone)(_Deref_out_opt_ IEnumSetupInstances** ppenum) = 0; +}; + +struct DECLSPEC_UUID("42843719-DB4C-46C2-8E7C-64F1816EFD5B") DECLSPEC_NOVTABLE ISetupConfiguration : public IUnknown +{ + STDMETHOD(EnumInstances)(_Out_ IEnumSetupInstances** ppEnumInstances) = 0; + STDMETHOD(GetInstanceForCurrentProcess)(_Out_ ISetupInstance** ppInstance) = 0; + STDMETHOD(GetInstanceForPath)(_In_z_ LPCWSTR wzPath, _Out_ ISetupInstance** ppInstance) = 0; +}; + + +// The beginning of the actual code that does things. + +struct Version_Data { + int32_t best_version[4]; // For Windows 8 versions, only two of these numbers are used. + wchar_t *best_name; +}; + +bool os_file_exists(wchar_t *name) { + // @Robustness: What flags do we really want to check here? + + auto attrib = GetFileAttributesW(name); + if (attrib == INVALID_FILE_ATTRIBUTES) return false; + if (attrib & FILE_ATTRIBUTE_DIRECTORY) return false; + + return true; +} + +wchar_t *concat(const wchar_t *a, const wchar_t *b, const wchar_t *c = nullptr, const wchar_t *d = nullptr) { + // Concatenate up to 4 wide strings together. Allocated with malloc. + // If you don't like that, use a programming language that actually + // helps you with using custom allocators. Or just edit the code. + + auto len_a = wcslen(a); + auto len_b = wcslen(b); + + auto len_c = 0; + if (c) len_c = wcslen(c); + + auto len_d = 0; + if (d) len_d = wcslen(d); + + wchar_t *result = (wchar_t *)malloc((len_a + len_b + len_c + len_d + 1) * 2); + memcpy(result, a, len_a * 2); + memcpy(result + len_a, b, len_b * 2); + + if (c) memcpy(result + len_a + len_b, c, len_c * 2); + if (d) memcpy(result + len_a + len_b + len_c, d, len_d * 2); + + result[len_a + len_b + len_c + len_d] = 0; + + return result; +} + +typedef void(*Visit_Proc_W)(wchar_t *short_name, wchar_t *full_name, Version_Data *data); +bool visit_files_w(wchar_t *dir_name, Version_Data *data, Visit_Proc_W proc) { + + // Visit everything in one folder (non-recursively). If it's a directory + // that doesn't start with ".", call the visit proc on it. The visit proc + // will see if the filename conforms to the expected versioning pattern. + + auto wildcard_name = concat(dir_name, L"\\*"); + defer{ free(wildcard_name); }; + + WIN32_FIND_DATAW find_data; + auto handle = FindFirstFileW(wildcard_name, &find_data); + if (handle == INVALID_HANDLE_VALUE) return false; + + while (true) { + if ((find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (find_data.cFileName[0] != '.')) { + auto full_name = concat(dir_name, L"\\", find_data.cFileName); + defer{ free(full_name); }; + + proc(find_data.cFileName, full_name, data); + } + + auto success = FindNextFileW(handle, &find_data); + if (!success) break; + } + + FindClose(handle); + + return true; +} + + +wchar_t *find_windows_kit_root(HKEY key, const wchar_t *version) { + // Given a key to an already opened registry entry, + // get the value stored under the 'version' subkey. + // If that's not the right terminology, hey, I never do registry stuff. + + DWORD required_length; + auto rc = RegQueryValueExW(key, version, NULL, NULL, NULL, &required_length); + if (rc != 0) return NULL; + + DWORD length = required_length + 2; // The +2 is for the maybe optional zero later on. Probably we are over-allocating. + wchar_t *value = (wchar_t *)malloc(length); + if (!value) return NULL; + + rc = RegQueryValueExW(key, version, NULL, NULL, (LPBYTE)value, &length); // We know that version is zero-terminated... + if (rc != 0) return NULL; + + // The documentation says that if the string for some reason was not stored + // with zero-termination, we need to manually terminate it. Sigh!! + + if (value[length]) { + value[length + 1] = 0; + } + + return value; +} + +void win10_best(wchar_t *short_name, wchar_t *full_name, Version_Data *data) { + // Find the Windows 10 subdirectory with the highest version number. + + int i0, i1, i2, i3; + auto success = swscanf_s(short_name, L"%d.%d.%d.%d", &i0, &i1, &i2, &i3); + if (success < 4) return; + + if (i0 < data->best_version[0]) return; + else if (i0 == data->best_version[0]) { + if (i1 < data->best_version[1]) return; + else if (i1 == data->best_version[1]) { + if (i2 < data->best_version[2]) return; + else if (i2 == data->best_version[2]) { + if (i3 < data->best_version[3]) return; + } + } + } + + // we have to copy_string and free here because visit_files free's the full_name string + // after we execute this function, so Win*_Data would contain an invalid pointer. + if (data->best_name) free(data->best_name); + data->best_name = _wcsdup(full_name); + + if (data->best_name) { + data->best_version[0] = i0; + data->best_version[1] = i1; + data->best_version[2] = i2; + data->best_version[3] = i3; + } +} + +void win8_best(wchar_t *short_name, wchar_t *full_name, Version_Data *data) { + // Find the Windows 8 subdirectory with the highest version number. + + int i0, i1; + auto success = swscanf_s(short_name, L"winv%d.%d", &i0, &i1); + if (success < 2) return; + + if (i0 < data->best_version[0]) return; + else if (i0 == data->best_version[0]) { + if (i1 < data->best_version[1]) return; + } + + // we have to copy_string and free here because visit_files free's the full_name string + // after we execute this function, so Win*_Data would contain an invalid pointer. + if (data->best_name) free(data->best_name); + data->best_name = _wcsdup(full_name); + + if (data->best_name) { + data->best_version[0] = i0; + data->best_version[1] = i1; + } +} + +void find_windows_kit_root(Find_Result *result) { + // Information about the Windows 10 and Windows 8 development kits + // is stored in the same place in the registry. We open a key + // to that place, first checking preferntially for a Windows 10 kit, + // then, if that's not found, a Windows 8 kit. + + HKEY main_key; + + auto rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", + 0, KEY_QUERY_VALUE | KEY_WOW64_32KEY | KEY_ENUMERATE_SUB_KEYS, &main_key); + if (rc != S_OK) return; + defer{ RegCloseKey(main_key); }; + + // Look for a Windows 10 entry. + auto windows10_root = find_windows_kit_root(main_key, L"KitsRoot10"); + + if (windows10_root) { + defer{ free(windows10_root); }; + Version_Data data = { 0 }; + auto windows10_lib = concat(windows10_root, L"Lib"); + defer{ free(windows10_lib); }; + + visit_files_w(windows10_lib, &data, win10_best); + if (data.best_name) { + result->windows_sdk_version = 10; + result->windows_sdk_root = data.best_name; + return; + } + } + + // Look for a Windows 8 entry. + auto windows8_root = find_windows_kit_root(main_key, L"KitsRoot81"); + + if (windows8_root) { + defer{ free(windows8_root); }; + + auto windows8_lib = concat(windows8_root, L"Lib"); + defer{ free(windows8_lib); }; + + Version_Data data = { 0 }; + visit_files_w(windows8_lib, &data, win8_best); + if (data.best_name) { + result->windows_sdk_version = 8; + result->windows_sdk_root = data.best_name; + return; + } + } + + // If we get here, we failed to find anything. +} + + +void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *result) { + // The name of this procedure is kind of cryptic. Its purpose is + // to fight through Microsoft craziness. The things that the fine + // Visual Studio team want you to do, JUST TO FIND A SINGLE FOLDER + // THAT EVERYONE NEEDS TO FIND, are ridiculous garbage. + + // For earlier versions of Visual Studio, you'd find this information in the registry, + // similarly to the Windows Kits above. But no, now it's the future, so to ask the + // question "Where is the Visual Studio folder?" you have to do a bunch of COM object + // instantiation, enumeration, and querying. (For extra bonus points, try doing this in + // a new, underdeveloped programming language where you don't have COM routines up + // and running yet. So fun.) + // + // If all this COM object instantiation, enumeration, and querying doesn't give us + // a useful result, we drop back to the registry-checking method. + + auto rc = CoInitialize(NULL); + // "Subsequent valid calls return false." So ignore false. + // if rc != S_OK return false; + + GUID my_uid = { 0x42843719, 0xDB4C, 0x46C2,{ 0x8E, 0x7C, 0x64, 0xF1, 0x81, 0x6E, 0xFD, 0x5B } }; + GUID CLSID_SetupConfiguration = { 0x177F0C4A, 0x1CD3, 0x4DE7,{ 0xA3, 0x2C, 0x71, 0xDB, 0xBB, 0x9F, 0xA3, 0x6D } }; + + ISetupConfiguration *config = NULL; + auto hr = CoCreateInstance(CLSID_SetupConfiguration, NULL, CLSCTX_INPROC_SERVER, my_uid, (void **)&config); + if (hr != 0) return; + defer{ config->Release(); }; + + IEnumSetupInstances *instances = NULL; + hr = config->EnumInstances(&instances); + if (hr != 0) return; + if (!instances) return; + defer{ instances->Release(); }; + + while (1) { + ULONG found = 0; + ISetupInstance *instance = NULL; + auto hr = instances->Next(1, &instance, &found); + if (hr != S_OK) break; + + defer{ instance->Release(); }; + + BSTR bstr_inst_path; + hr = instance->GetInstallationPath(&bstr_inst_path); + if (hr != S_OK) continue; + defer{ SysFreeString(bstr_inst_path); }; + + auto tools_filename = concat(bstr_inst_path, L"\\VC\\Auxiliary\\Build\\Microsoft.VCToolsVersion.default.txt"); + defer{ free(tools_filename); }; + + FILE *f = nullptr; + auto open_result = _wfopen_s(&f, tools_filename, L"rt"); + if (open_result != 0) continue; + if (!f) continue; + defer{ fclose(f); }; + + LARGE_INTEGER tools_file_size; + auto file_handle = (HANDLE)_get_osfhandle(_fileno(f)); + BOOL success = GetFileSizeEx(file_handle, &tools_file_size); + if (!success) continue; + + auto version_bytes = (tools_file_size.QuadPart + 1) * 2; // Warning: This multiplication by 2 presumes there is no variable-length encoding in the wchars (wacky characters in the file could betray this expectation). + wchar_t *version = (wchar_t *)malloc(version_bytes); + defer{ free(version); }; + + auto read_result = fgetws(version, version_bytes, f); + if (!read_result) continue; + + auto version_tail = wcschr(version, '\n'); + if (version_tail) *version_tail = 0; // Stomp the data, because nobody cares about it. + + auto library_path = concat(bstr_inst_path, L"\\VC\\Tools\\MSVC\\", version, L"\\lib\\x64"); + auto library_file = concat(library_path, L"\\vcruntime.lib"); // @Speed: Could have library_path point to this string, with a smaller count, to save on memory flailing! + + if (os_file_exists(library_file)) { + auto link_exe_path = concat(bstr_inst_path, L"\\VC\\Tools\\MSVC\\", version, L"\\bin\\Hostx64\\x64"); + result->vs_exe_path = link_exe_path; + result->vs_library_path = library_path; + return; + } + + /* + Ryan Saunderson said: + "Clang uses the 'SetupInstance->GetInstallationVersion' / ISetupHelper->ParseVersion to find the newest version + and then reads the tools file to define the tools path - which is definitely better than what i did." + + So... @Incomplete: Should probably pick the newest version... + */ + } + + // If we get here, we didn't find Visual Studio 2017. Try earlier versions. + + HKEY vs7_key; + rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7", 0, KEY_QUERY_VALUE | KEY_WOW64_32KEY, &vs7_key); + + if (rc != S_OK) return; + defer{ RegCloseKey(vs7_key); }; + + // Hardcoded search for 4 prior Visual Studio versions. Is there something better to do here? + const wchar_t *versions[] = { L"14.0", L"12.0", L"11.0", L"10.0" }; + const int NUM_VERSIONS = sizeof(versions) / sizeof(versions[0]); + + for (int i = 0; i < NUM_VERSIONS; i++) { + auto v = versions[i]; + + DWORD dw_type; + DWORD cb_data; + + auto rc = RegQueryValueExW(vs7_key, v, NULL, &dw_type, NULL, &cb_data); + if ((rc == ERROR_FILE_NOT_FOUND) || (dw_type != REG_SZ)) { + continue; + } + + auto buffer = (wchar_t *)malloc(cb_data); + if (!buffer) return; + defer{ free(buffer); }; + + rc = RegQueryValueExW(vs7_key, v, NULL, NULL, (LPBYTE)buffer, &cb_data); + if (rc != 0) continue; + + // @Robustness: Do the zero-termination thing suggested in the RegQueryValue docs? + + auto lib_path = concat(buffer, L"VC\\Lib\\amd64"); + + // Check to see whether a vcruntime.lib actually exists here. + auto vcruntime_filename = concat(lib_path, L"\\vcruntime.lib"); + defer{ free(vcruntime_filename); }; + + if (os_file_exists(vcruntime_filename)) { + result->vs_exe_path = concat(buffer, L"VC\\bin"); + result->vs_library_path = lib_path; + return; + } + + free(lib_path); + } + + // If we get here, we failed to find anything. +} + +Find_Result find_visual_studio_and_windows_sdk(SdkArch sdkArch) { + Find_Result result; + + find_windows_kit_root(&result); + + if (result.windows_sdk_root) { + result.windows_sdk_um_library_path = concat(result.windows_sdk_root, L"\\um\\x64"); + result.windows_sdk_ucrt_library_path = concat(result.windows_sdk_root, L"\\ucrt\\x64"); + } + + find_visual_studio_by_fighting_through_microsoft_craziness(&result); + + return result; +} + +void free_resources(Find_Result *result) { + free(result->windows_sdk_root); + free(result->windows_sdk_um_library_path); + free(result->windows_sdk_ucrt_library_path); + free(result->vs_exe_path); + free(result->vs_library_path); +} diff --git a/msvc/locate_windows_sdk/locate_sdk.hpp b/msvc/locate_windows_sdk/locate_sdk.hpp new file mode 100644 index 0000000..6446aa4 --- /dev/null +++ b/msvc/locate_windows_sdk/locate_sdk.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +struct Find_Result { + int windows_sdk_version; // Zero if no Windows SDK found. + + wchar_t *windows_sdk_root = NULL; + wchar_t *windows_sdk_um_library_path = NULL; + wchar_t *windows_sdk_ucrt_library_path = NULL; + + wchar_t *vs_exe_path = NULL; + wchar_t *vs_library_path = NULL; +}; + +enum SdkArch +{ + ARCH_X86, + ARCH_X64 +}; + +Find_Result find_visual_studio_and_windows_sdk(SdkArch sdkArch); + +void free_resources(Find_Result *result); \ No newline at end of file diff --git a/msvc/locate_windows_sdk/locate_windows_sdk.sln b/msvc/locate_windows_sdk/locate_windows_sdk.sln new file mode 100644 index 0000000..f5b2cd3 --- /dev/null +++ b/msvc/locate_windows_sdk/locate_windows_sdk.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2018 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "locate_windows_sdk", "locate_windows_sdk.vcxproj", "{2599CC64-5DBE-4235-A429-815A45ABC04F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Debug|x64.ActiveCfg = Debug|x64 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Debug|x64.Build.0 = Debug|x64 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Debug|x86.ActiveCfg = Debug|Win32 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Debug|x86.Build.0 = Debug|Win32 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Release|x64.ActiveCfg = Release|x64 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Release|x64.Build.0 = Release|x64 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Release|x86.ActiveCfg = Release|Win32 + {2599CC64-5DBE-4235-A429-815A45ABC04F}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D1F48380-19DA-44A0-85CB-2220EEEB78CE} + EndGlobalSection +EndGlobal diff --git a/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj new file mode 100644 index 0000000..e030615 --- /dev/null +++ b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj @@ -0,0 +1,159 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {2599CC64-5DBE-4235-A429-815A45ABC04F} + Win32Proj + locatewindowssdk + 10.0.17134.0 + + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + Application + true + v141 + Unicode + + + Application + false + v141 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + NotUsing + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + NotUsing + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.filters b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.filters new file mode 100644 index 0000000..f9d71ea --- /dev/null +++ b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.user b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.user new file mode 100644 index 0000000..be25078 --- /dev/null +++ b/msvc/locate_windows_sdk/locate_windows_sdk.vcxproj.user @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/msvc/locate_windows_sdk/main.cpp b/msvc/locate_windows_sdk/main.cpp new file mode 100644 index 0000000..7f9b0a4 Binary files /dev/null and b/msvc/locate_windows_sdk/main.cpp differ diff --git a/msvc/ninja.exe b/msvc/ninja.exe new file mode 100644 index 0000000..f86ef07 Binary files /dev/null and b/msvc/ninja.exe differ diff --git a/msvc/sibs.exe b/msvc/sibs.exe index a6ce4e0..21b3e83 100644 Binary files a/msvc/sibs.exe and b/msvc/sibs.exe differ diff --git a/sibs.sln b/sibs.sln deleted file mode 100644 index dee6580..0000000 --- a/sibs.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27703.2018 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sibs", "sibs.vcxproj", "{2C511FA3-FDD5-426D-88B1-29D3A1402CCA}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Debug|x64.ActiveCfg = Debug|x64 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Debug|x64.Build.0 = Debug|x64 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Debug|x86.ActiveCfg = Debug|Win32 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Debug|x86.Build.0 = Debug|Win32 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Release|x64.ActiveCfg = Release|x64 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Release|x64.Build.0 = Release|x64 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Release|x86.ActiveCfg = Release|Win32 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA}.Release|x86.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {5B182611-D575-40A3-97DA-763A0BC62B84} - EndGlobalSection -EndGlobal diff --git a/sibs.vcxproj b/sibs.vcxproj deleted file mode 100644 index 28a2a99..0000000 --- a/sibs.vcxproj +++ /dev/null @@ -1,186 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - Debug - x64 - - - Release - x64 - - - - 15.0 - {2C511FA3-FDD5-426D-88B1-29D3A1402CCA} - Win32Proj - 10.0.17134.0 - - - - Application - true - v141 - Unicode - - - Application - false - v141 - Unicode - - - Application - true - v141 - - - Application - false - v141 - - - - - - - - - - - - - - - - - - - - - true - - - true - - - - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebugDLL - Level3 - ProgramDatabase - Disabled - - - MachineX86 - true - Console - - - - - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDLL - Level3 - ProgramDatabase - - - MachineX86 - true - Console - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sibs.vcxproj.filters b/sibs.vcxproj.filters deleted file mode 100644 index 059dfbf..0000000 --- a/sibs.vcxproj.filters +++ /dev/null @@ -1,249 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/sibs.vcxproj.user b/sibs.vcxproj.user deleted file mode 100644 index be25078..0000000 --- a/sibs.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/Exec.cpp b/src/Exec.cpp index 2eac8bc..6c1a72e 100644 --- a/src/Exec.cpp +++ b/src/Exec.cpp @@ -3,24 +3,28 @@ using namespace std; +const int BUFSIZE = 1024; + +// TODO: Redirect stderr to namespace sibs { #if OS_FAMILY == OS_FAMILY_POSIX Result exec(const _tinydir_char_t *cmd, bool print) { - char buffer[128]; - std::string result; + char buffer[BUFSIZE]; + std::string execStdout; FILE *pipe = popen(cmd, "r"); if(!pipe) return Result::Err("popen() failed"); while(!feof(pipe)) { - if(fgets(buffer, 128, pipe)) + int bytesRead = fgets(buffer, BUFSIZE, pipe); + if(bytesRead > 0) { - result += buffer; + execStdout.append(buffer, bytesRead); if(print) - printf("%s", buffer); + printf("%.*s", bytesRead, buffer); } } @@ -29,7 +33,7 @@ namespace sibs { int returned = WEXITSTATUS(processCloseResult); ExecResult execResult; - execResult.execStdout = result; + execResult.execStdout = move(execStdout); execResult.exitCode = returned; return Result::Ok(execResult); } @@ -55,48 +59,80 @@ namespace sibs } } #else - // TODO(Windows): Redirect stdout (and stderr) to string + // Currently stdout is read in text mode so \n is replaced with \r\n, should we read in binary mode instead? Result exec(const _tinydir_char_t *cmd, bool print) { - char buffer[128]; - std::string result; + FileString cmdNonConst = cmd; + std::string execStdout; - STARTUPINFO startupInfo; - ZeroMemory(&startupInfo, sizeof(startupInfo)); - startupInfo.cb = sizeof(startupInfo); + SECURITY_ATTRIBUTES saAttr; + saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); + saAttr.bInheritHandle = TRUE; + saAttr.lpSecurityDescriptor = nullptr; - PROCESS_INFORMATION processInfo; - ZeroMemory(&processInfo, sizeof(processInfo)); + HANDLE childReadHandle = nullptr; + HANDLE childStdoutHandle = nullptr; - DWORD exitCode; - - if (!CreateProcess(NULL, (LPWSTR)cmd, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo)) + if (!CreatePipe(&childReadHandle, &childStdoutHandle, &saAttr, 0)) { string errMsg = "exec unexpected error: "; errMsg += toUtf8(getLastErrorAsString()); return Result::Err(errMsg); } - WaitForSingleObject(processInfo.hProcess, INFINITE); - GetExitCodeProcess(processInfo.hProcess, &exitCode); - CloseHandle(processInfo.hProcess); - CloseHandle(processInfo.hThread); + if (!SetHandleInformation(childReadHandle, HANDLE_FLAG_INHERIT, 0)) + goto cleanupAndExit; + + PROCESS_INFORMATION piProcInfo; + ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); + + STARTUPINFO siStartInfo; + ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); + siStartInfo.cb = sizeof(STARTUPINFO); + siStartInfo.hStdError = nullptr; + siStartInfo.hStdOutput = childStdoutHandle; + siStartInfo.hStdInput = nullptr; + siStartInfo.dwFlags |= STARTF_USESTDHANDLES; + + DWORD exitCode; + + if (!CreateProcessW(nullptr, (LPWSTR)cmdNonConst.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &siStartInfo, &piProcInfo)) + goto cleanupAndExit; + + WaitForSingleObject(piProcInfo.hProcess, INFINITE); + GetExitCodeProcess(piProcInfo.hProcess, &exitCode); + CloseHandle(piProcInfo.hProcess); + CloseHandle(piProcInfo.hThread); + CloseHandle(childStdoutHandle); + childStdoutHandle = nullptr; + + DWORD bytesRead; + CHAR buffer[BUFSIZE]; + while (true) + { + BOOL bSuccess = ReadFile(childReadHandle, buffer, BUFSIZE, &bytesRead, nullptr); + if (!bSuccess || bytesRead == 0) + break; + + execStdout.append(buffer, bytesRead); + if (print) + printf("%.*s", bytesRead, buffer); + } - if (exitCode == 0) { ExecResult execResult; - execResult.execStdout = result; + execResult.execStdout = move(execStdout); execResult.exitCode = exitCode; + CloseHandle(childReadHandle); return Result::Ok(execResult); } - else - { - string errMsg = "Exited with non-zero exit code ("; - errMsg += to_string(exitCode); - errMsg += "): "; - errMsg += toUtf8(getLastErrorAsString()); - return Result::Err(errMsg); - } + + cleanupAndExit: + string errMsg = "exec unexpected error: "; + errMsg += toUtf8(getLastErrorAsString()); + CloseHandle(childReadHandle); + CloseHandle(childStdoutHandle); + return Result::Err(errMsg); } #endif } diff --git a/src/FileUtil.cpp b/src/FileUtil.cpp index 53430c4..77669e5 100644 --- a/src/FileUtil.cpp +++ b/src/FileUtil.cpp @@ -489,25 +489,38 @@ namespace sibs } #endif - // TODO: Support better path equality check. For example if path contains several slashes in a row: /home/userName/.sibs//lib////libraryName - // then it should equal: /home/userName/.sibs/lib/libraryName - // Maybe check with OS operation if they refer to the same inode? + // TODO: Support better path equality check. Maybe check with OS operation if they refer to the same inode? bool pathEquals(const std::string &path, const std::string &otherPath) { - if(path.size() != otherPath.size()) - return false; - - size_t size = path.size(); - for(size_t i = 0; i < size; ++i) - { - char c = path[i]; - char otherC = otherPath[i]; - if(c == '\\') c = '/'; - if(otherC == '\\') otherC = '/'; - if(c != otherC) - return false; - } - - return true; + size_t pathIndex = 0; + size_t otherPathIndex = 0; + + while (true) + { + while (pathIndex < path.size() && (path[pathIndex] == '/' || path[pathIndex] == '\\')) + { + ++pathIndex; + } + + while (otherPathIndex < otherPath.size() && (otherPath[otherPathIndex] == '/' || otherPath[otherPathIndex] == '\\')) + { + ++otherPathIndex; + } + + if (pathIndex < path.size() && otherPathIndex < otherPath.size()) + { + if (path[pathIndex] != otherPath[otherPathIndex]) + return false; + + ++pathIndex; + ++otherPathIndex; + } + else + { + break; + } + } + + return pathIndex == path.size() && otherPathIndex == otherPath.size(); } } diff --git a/src/main.cpp b/src/main.cpp index 38e68f0..cb1c611 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -112,7 +112,7 @@ static string SIBS_GITIGNORE_FILES = "tests/sibs-build/\n" "tests/compile_commands.json\n"; -void usage() +static void usage() { printf("Usage: sibs COMMAND\n\n"); printf("Simple Build System for Native Languages\n\n"); @@ -124,7 +124,7 @@ void usage() exit(1); } -void usageBuild() +static void usageBuild() { printf("Usage: sibs build [project_path] [--debug|--release] [--sanitize]\n\n"); printf("Build a sibs project\n\n"); @@ -141,7 +141,7 @@ void usageBuild() exit(1); } -void usageNew() +static void usageNew() { printf("Usage: sibs new <--exec|--static|--dynamic> [--lang c|c++|zig]\n\n"); printf("Create a new sibs project\n\n"); @@ -156,7 +156,7 @@ void usageNew() exit(1); } -void usageTest() +static void usageTest() { printf("Usage: sibs test [project_path] [--no-sanitize] [--file filepath...|--all-files]\n\n"); printf("Build and run tests for a sibs project\n\n"); @@ -171,7 +171,7 @@ void usageTest() exit(1); } -void usageInit() +static void usageInit() { printf("Usage: sibs init [project_path] <--exec|--static|--dynamic> [--lang c|c++|zig]\n\n"); printf("Create sibs project structure in an existing directory\n\n"); @@ -187,7 +187,7 @@ void usageInit() exit(1); } -void validateDirectoryPath(const _tinydir_char_t *projectPath) +static void validateDirectoryPath(const _tinydir_char_t *projectPath) { FileType projectPathFileType = getFileType(projectPath); if(projectPathFileType == FileType::FILE_NOT_FOUND) @@ -204,7 +204,7 @@ void validateDirectoryPath(const _tinydir_char_t *projectPath) } } -void validateFilePath(const _tinydir_char_t *projectConfPath) +static void validateFilePath(const _tinydir_char_t *projectConfPath) { FileType projectConfFileType = getFileType(projectConfPath); if(projectConfFileType == FileType::FILE_NOT_FOUND) @@ -221,20 +221,84 @@ void validateFilePath(const _tinydir_char_t *projectConfPath) } } -bool isPathSubPathOf(const FileString &path, const FileString &subPathOf) +static bool isPathSubPathOf(const FileString &path, const FileString &subPathOf) { return _tinydir_strncmp(path.c_str(), subPathOf.c_str(), subPathOf.size()) == 0; } -static bool doesProgramExist(const _tinydir_char_t *programName) +#if OS_FAMILY == OS_FAMILY_WINDOWS +static char* join(const char *str1, const char *str2, const char separator) { - FileString cmd = FileString(programName) + TINYDIR_STRING(" --version"); - Result result = exec(cmd.c_str()); - bool programNotFound = !result && result.getErrorCode() == 127; - return !programNotFound; + int str1len = strlen(str1); + int str2len = strlen(str2); + char *result = new char[str1len + 1 + str2len + 1]; + memcpy(result, str1, str1len); + result[str1len] = separator; + memcpy(result + str1len + 1, str2, str2len); + result[str1len + 1 + str2len] = '\0'; + return result; } -int buildProject(const FileString &projectPath, const FileString &projectConfFilePath, SibsConfig &sibsConfig) +struct MicrosoftBuildTool +{ + // 0 if version not found + int version; + // empty if not found + char binPath[_TINYDIR_PATH_MAX]; + // empty if not found + char umLibPath[_TINYDIR_PATH_MAX]; + // empty if not found + char ucrtLibPath[_TINYDIR_PATH_MAX]; + + bool found() + { + return version != 0; + } +}; + +static MicrosoftBuildTool locateLatestMicrosoftBuildTool() +{ + MicrosoftBuildTool result = { 0 }; + Result execResult = exec(TINYDIR_STRING("locate_windows_sdk")); + if (execResult && execResult.unwrap().exitCode == 0) + { + auto &str = execResult.unwrap().execStdout; + sscanf(execResult.unwrap().execStdout.c_str(), "%d %[^\r\n] %[^\r\n] %[^\r\n]", &result.version, result.binPath, result.umLibPath, result.ucrtLibPath); + } + return result; +} + +static void appendMicrosoftBuildToolToPathEnv() +{ + MicrosoftBuildTool msBuildTool = locateLatestMicrosoftBuildTool(); + if (msBuildTool.found()) + { + fprintf(stderr, "Located microsoft build tools at %s\n", msBuildTool.binPath); + fprintf(stderr, "Located microsoft build libraries at %s;%s\n", msBuildTool.umLibPath, msBuildTool.ucrtLibPath); + + if (const char *pathEnv = getenv("PATH")) + { + // We do not free this because it needs to live as long as it's used as env (in _putenv) + if (_putenv_s("PATH", join(pathEnv, msBuildTool.binPath, ';')) != 0) + fprintf(stderr, "Warning: Failed to add microsoft build tools to PATH env\n"); + } + + // We do not free this because it needs to live as long as it's used as env (in _putenv) + if (_putenv_s("LIB", join(msBuildTool.umLibPath, msBuildTool.ucrtLibPath, ';')) != 0) + fprintf(stderr, "Warning: Failed to add microsoft build libraries to LIB env\n"); + } +} +#endif + +static void appendBuildToolToPathEnv() +{ +#if OS_FAMILY == OS_FAMILY_WINDOWS + // TODO: We shouldn't do this if user wants to compile with clang/mingw? + appendMicrosoftBuildToolToPathEnv(); +#endif +} + +static int buildProject(const FileString &projectPath, const FileString &projectConfFilePath, SibsConfig &sibsConfig) { FileString buildPath; readSibsConfig(projectPath, projectConfFilePath, sibsConfig, buildPath); @@ -317,7 +381,7 @@ int buildProject(const FileString &projectPath, const FileString &projectConfFil return 0; } -int buildProject(int argc, const _tinydir_char_t **argv) +static int buildProject(int argc, const _tinydir_char_t **argv) { if(argc > 3) usageBuild(); @@ -404,7 +468,7 @@ int buildProject(int argc, const _tinydir_char_t **argv) return buildProject(projectPath, projectConfFilePath, sibsConfig); } -int testProject(int argc, const _tinydir_char_t **argv) +static int testProject(int argc, const _tinydir_char_t **argv) { if(argc > 2) usageTest(); @@ -546,7 +610,7 @@ int testProject(int argc, const _tinydir_char_t **argv) } // Returns nullptr if @charToFind is not found -const _tinydir_char_t* findLastOf(const _tinydir_char_t *str, const int strSize, const char charToFind) +static const _tinydir_char_t* findLastOf(const _tinydir_char_t *str, const int strSize, const char charToFind) { for(int i = strSize; i >= 0; --i) { @@ -556,7 +620,7 @@ const _tinydir_char_t* findLastOf(const _tinydir_char_t *str, const int strSize, return nullptr; } -Result newProjectCreateConf(const string &projectName, const string &projectType, const FileString &projectPath) +static Result newProjectCreateConf(const string &projectName, const string &projectType, const FileString &projectPath) { string projectConfStr = "[package]\n"; projectConfStr += "name = \"" + projectName + "\"\n"; @@ -574,12 +638,12 @@ Result newProjectCreateConf(const string &projectName, const string &proje return fileWrite(projectConfPath.c_str(), projectConfStr.c_str()); } -Result createDirectoryRecursive(const FileString &dir) +static Result createDirectoryRecursive(const FileString &dir) { return createDirectoryRecursive(dir.c_str()); } -void createProjectFile(const FileString &projectFilePath, const string &fileContent) +static void createProjectFile(const FileString &projectFilePath, const string &fileContent) { Result fileOverwriteResult = fileOverwrite(projectFilePath.c_str(), fileContent.c_str()); if(fileOverwriteResult.isErr()) @@ -591,7 +655,7 @@ void createProjectFile(const FileString &projectFilePath, const string &fileCont // This can be replaced with createDirectory and fileOverwrite, but it's not important // so there is no reason to do it (right now) -Result gitInitProject(const FileString &projectPath) +static Result gitInitProject(const FileString &projectPath) { FileString cmd = TINYDIR_STRING("git init \""); cmd += projectPath; @@ -599,7 +663,7 @@ Result gitInitProject(const FileString &projectPath) return exec(cmd.c_str()); } -bool gitIgnoreContainsSibs(const FileString &gitIgnoreFilePath) +static bool gitIgnoreContainsSibs(const FileString &gitIgnoreFilePath) { Result fileContentResult = getFileContent(gitIgnoreFilePath.c_str()); if(!fileContentResult) return false; @@ -611,7 +675,7 @@ bool gitIgnoreContainsSibs(const FileString &gitIgnoreFilePath) return containsSibs; } -void gitIgnoreAppendSibs(const FileString &gitIgnoreFilePath) +static void gitIgnoreAppendSibs(const FileString &gitIgnoreFilePath) { Result fileContentResult = getFileContent(gitIgnoreFilePath.c_str()); string fileContentNew; @@ -627,10 +691,10 @@ void gitIgnoreAppendSibs(const FileString &gitIgnoreFilePath) fileContentNew += SIBS_GITIGNORE_FILES; Result result = fileOverwrite(gitIgnoreFilePath.c_str(), { fileContentNew.data(), fileContentNew.size() }); if(!result) - ferr << "Failed to add sibs to .gitignore, reason: " << result.getErrMsg() << endl; + ferr << "Failed to add sibs to .gitignore, reason: " << toFileString(result.getErrMsg()) << endl; } -int initProject(int argc, const _tinydir_char_t **argv) +static int initProject(int argc, const _tinydir_char_t **argv) { FileString projectPath; const _tinydir_char_t *projectType = nullptr; @@ -785,7 +849,7 @@ int initProject(int argc, const _tinydir_char_t **argv) auto createProjectConfResult = newProjectCreateConf(projectName, projectTypeConf, projectPath); if(!createProjectConfResult) { - ferr << "A project already exists in the directory " << projectPath << ". Error: failed to create project.conf, reason: " << createProjectConfResult.getErrMsg() << endl; + ferr << "A project already exists in the directory " << projectPath << ". Error: failed to create project.conf, reason: " << toFileString(createProjectConfResult.getErrMsg()) << endl; exit(20); } createDirectoryRecursive(projectPath + TINYDIR_STRING("/src")); @@ -830,7 +894,7 @@ int initProject(int argc, const _tinydir_char_t **argv) return 0; } -void newProjectCreateMainDir(const FileString &projectPath) +static void newProjectCreateMainDir(const FileString &projectPath) { Result createProjectDirResult = createDirectoryRecursive(projectPath.c_str()); if(createProjectDirResult.isErr()) @@ -840,7 +904,7 @@ void newProjectCreateMainDir(const FileString &projectPath) } } -void checkFailCreateSubDir(Result createSubDirResult) +static void checkFailCreateSubDir(Result createSubDirResult) { if(!createSubDirResult) { @@ -849,7 +913,7 @@ void checkFailCreateSubDir(Result createSubDirResult) } } -int newProject(int argc, const _tinydir_char_t **argv) +static int newProject(int argc, const _tinydir_char_t **argv) { string projectName; const _tinydir_char_t *projectType = nullptr; @@ -918,7 +982,7 @@ int newProject(int argc, const _tinydir_char_t **argv) { if(!projectName.empty()) { - ferr << "Error: Project name was defined more than once. First defined as " << projectName << " then as " << arg << endl; + ferr << "Error: Project name was defined more than once. First defined as " << toFileString(projectName) << " then as " << arg << endl; usageNew(); } projectName = toUtf8(arg); @@ -1041,6 +1105,7 @@ int wmain(int argc, const _tinydir_char_t **argv) const _tinydir_char_t **subCommandArgPtr = argv + i + 1; if(_tinydir_strcmp(arg, TINYDIR_STRING("build")) == 0) { + appendBuildToolToPathEnv(); return buildProject(subCommandArgCount, subCommandArgPtr); } else if(_tinydir_strcmp(arg, TINYDIR_STRING("new")) == 0) @@ -1049,6 +1114,7 @@ int wmain(int argc, const _tinydir_char_t **argv) } else if(_tinydir_strcmp(arg, TINYDIR_STRING("test")) == 0) { + appendBuildToolToPathEnv(); return testProject(subCommandArgCount, subCommandArgPtr); } else if(_tinydir_strcmp(arg, TINYDIR_STRING("init")) == 0) -- cgit v1.2.3