From e5185d23c3f690efa5d9e2be72abc09b01e48cd8 Mon Sep 17 00:00:00 2001 From: Wolfgang Thaller Date: Sun, 18 Aug 2019 13:21:00 +0200 Subject: [PATCH] Switch tab-indented files to 4-space indent --- .editorconfig | 13 + AutomatedTests/CMakeLists.txt | 40 +- AutomatedTests/Empty.c | 4 +- AutomatedTests/File.c | 2 +- AutomatedTests/Init.cc | 20 +- AutomatedTests/Log.c | 12 +- AutomatedTests/ReallyEmpty.c | 4 +- AutomatedTests/Segment1.c | 128 +-- AutomatedTests/Segment2.c | 6 +- AutomatedTests/StdIO.c | 6 +- AutomatedTests/Test.c | 2 +- AutomatedTests/Test.h | 124 +-- AutomatedTests/Timeout.c | 12 +- AutomatedTests/ZeroInitialized.c | 70 +- Console/CMakeLists.txt | 20 +- Console/ConsoleTest.cc | 26 +- Console/retro/Console.cc | 2 +- Console/retro/Console.h | 88 +-- Console/retro/ConsoleWindow.cc | 146 ++-- Console/retro/ConsoleWindow.h | 18 +- Console/retro/InitConsole.cc | 92 +-- ConvertObj/ConvertObj.cc | 680 ++++++++-------- Elf2Mac/CMakeLists.txt | 12 +- Elf2Mac/Elf2Mac.cc | 322 ++++---- Elf2Mac/Elf2Mac.h | 24 +- Elf2Mac/LdScript.cc | 206 ++--- Elf2Mac/Object.cc | 520 ++++++------ Elf2Mac/Object.h | 52 +- Elf2Mac/Reloc.cc | 72 +- Elf2Mac/Reloc.h | 48 +- Elf2Mac/Section.cc | 318 ++++---- Elf2Mac/Section.h | 74 +- Elf2Mac/SegmentMap.cc | 176 ++--- Elf2Mac/SegmentMap.h | 58 +- Elf2Mac/Symbol.cc | 42 +- Elf2Mac/Symbol.h | 42 +- Elf2Mac/Symtab.cc | 78 +- Elf2Mac/Symtab.h | 44 +- LaunchAPPL/Client/CMakeLists.txt | 32 +- LaunchAPPL/Client/Carbon.cc | 20 +- LaunchAPPL/Client/Carbon.h | 6 +- LaunchAPPL/Client/Classic.cc | 80 +- LaunchAPPL/Client/Classic.h | 6 +- LaunchAPPL/Client/Executor.cc | 42 +- LaunchAPPL/Client/Executor.h | 8 +- LaunchAPPL/Client/LaunchAPPL.cc | 382 ++++----- LaunchAPPL/Client/LaunchMethod.cc | 4 +- LaunchAPPL/Client/LaunchMethod.h | 80 +- LaunchAPPL/Client/Launcher.cc | 52 +- LaunchAPPL/Client/Launcher.h | 94 +-- LaunchAPPL/Client/MakeExecutable.cc | 68 +- LaunchAPPL/Client/MiniVMac.h | 8 +- LaunchAPPL/Client/SSH.cc | 172 ++-- LaunchAPPL/Client/SSH.h | 8 +- LaunchAPPL/Client/Serial.cc | 6 +- LaunchAPPL/Client/Serial.h | 8 +- LaunchAPPL/Client/SharedFile.cc | 6 +- LaunchAPPL/Client/SharedFile.h | 8 +- LaunchAPPL/Client/StreamBasedLauncher.h | 8 +- LaunchAPPL/Client/TCP.cc | 6 +- LaunchAPPL/Client/TCP.h | 8 +- LaunchAPPL/Client/Utilities.cc | 298 +++---- LaunchAPPL/Server/LaunchAPPLServer.cc | 18 +- LaunchAPPL/Server/MacSerialStream.cc | 2 +- LaunchAPPL/Server/MacTCPStream.cc | 16 +- LaunchAPPL/Server/OpenTptStream.cc | 2 +- PEFTools/MakeImport.cc | 566 ++++++------- PEFTools/MakePEF.cc | 906 ++++++++++----------- PEFTools/PEF.h | 132 ++-- PEFTools/rs6000.h | 214 ++--- ResourceFiles/BinaryIO.cc | 36 +- ResourceFiles/CMakeLists.txt | 14 +- ResourceFiles/ResInfo.cc | 220 +++--- ResourceFiles/ResType.cc | 62 +- ResourceFiles/ResType.h | 28 +- ResourceFiles/ResourceFile.cc | 924 +++++++++++----------- ResourceFiles/ResourceFile.h | 58 +- ResourceFiles/ResourceFork.cc | 266 +++---- ResourceFiles/ResourceFork.h | 46 +- Rez/CMakeLists.txt | 50 +- Rez/Diagnostic.cc | 26 +- Rez/Diagnostic.h | 24 +- Rez/Expression.cc | 188 ++--- Rez/Expression.h | 130 +-- Rez/ResSpec.h | 20 +- Rez/ResourceCompiler.cc | 210 ++--- Rez/ResourceCompiler.h | 104 +-- Rez/ResourceDefinitions.cc | 424 +++++----- Rez/ResourceDefinitions.h | 146 ++-- Rez/Rez.cc | 248 +++--- Rez/RezLexer.cc | 206 ++--- Rez/RezLexer.h | 30 +- Rez/RezLexerNextToken.cc | 488 ++++++------ Rez/RezLexerWaveToken.h | 4 +- Rez/RezWorld.cc | 50 +- Rez/RezWorld.h | 30 +- Rez/Test/UnitTests.cc | 178 ++--- Samples/Dialog/CMakeLists.txt | 34 +- Samples/Dialog/dialog.c | 18 +- Samples/HelloWorld/CMakeLists.txt | 14 +- Samples/HelloWorld/hello.c | 32 +- Samples/Launcher/CMakeLists.txt | 2 +- Samples/Launcher/Launcher.c | 226 +++--- Samples/MPWTool/main.c | 26 +- Samples/Raytracer/CMakeLists.txt | 58 +- Samples/Raytracer/fixed.cc | 40 +- Samples/Raytracer/fixed.h | 134 ++-- Samples/Raytracer/fixedbenchmark.cc | 146 ++-- Samples/Raytracer/raytracer.c | 406 +++++----- Samples/Raytracer/raytracer2.cc | 414 +++++----- Samples/SystemExtension/CMakeLists.txt | 38 +- Samples/SystemExtension/ShowInitIcon.c | 144 ++-- Samples/SystemExtension/SystemExtension.c | 14 +- Samples/WDEF/CMakeLists.txt | 28 +- Samples/WDEF/wdefshell.c | 2 +- TestApps/EmptyTest.c | 2 +- TestApps/ExceptionTest.cc | 88 +-- TestApps/InitTest.cc | 62 +- cmake/add_application.cmake | 168 ++-- interfaces-and-libraries.sh | 430 +++++----- libretro/CMakeLists.txt | 100 +-- libretro/MultiSegApp.c | 108 +-- libretro/PoorMansDebugging.h | 104 +-- libretro/Retro68Runtime.h | 78 +- libretro/consolehooks.c | 38 +- libretro/glue.c | 480 +++++------ libretro/malloc.c | 150 ++-- libretro/ppcstart.c | 48 +- libretro/relocate.c | 576 +++++++------- libretro/start.c | 52 +- libretro/syscalls.c | 302 +++---- prepare-headers.sh | 102 +-- prepare-rincludes.sh | 2 +- 133 files changed, 7879 insertions(+), 7866 deletions(-) diff --git a/.editorconfig b/.editorconfig index 17b5b69487..a8faf89def 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,6 +6,9 @@ indent_style = space tab_width = 4 charset = utf-8 +[InterfacesAndLibraries/**/*] +indent_style = tab + [gcc/**/*] indent_style = tab tab_width = 8 @@ -16,5 +19,15 @@ indent_style = tab tab_width = 8 indent_width = 2 +[libelf/**/*] +indent_style = tab +tab_width = 8 +indent_width = 2 + +[hfsutils/**/*] +indent_style = tab +tab_width = 8 +indent_width = 2 + [**/Makefile] indent_style=tab diff --git a/AutomatedTests/CMakeLists.txt b/AutomatedTests/CMakeLists.txt index c65d47296b..4b43ecec63 100644 --- a/AutomatedTests/CMakeLists.txt +++ b/AutomatedTests/CMakeLists.txt @@ -1,20 +1,20 @@ find_program(LAUNCH_APPL LaunchAPPL PATH "${CMAKE_INSTALL_PREFIX}/../bin/") execute_process(COMMAND ${LAUNCH_APPL} --list-emulators - OUTPUT_VARIABLE EMULATOR_LIST) + OUTPUT_VARIABLE EMULATOR_LIST) string(REPLACE "\n" ";" EMULATOR_LIST "${EMULATOR_LIST}") if(CMAKE_SYSTEM_NAME MATCHES "RetroCarbon") - if("carbon" IN_LIST EMULATOR_LIST) - set(RETRO68_LAUNCH_METHOD carbon CACHE STRING "How to launch Mac applications (for automated testing)") - else() - set(RETRO68_LAUNCH_METHOD NONE CACHE STRING "How to launch Mac applications (for automated testing)") - endif() + if("carbon" IN_LIST EMULATOR_LIST) + set(RETRO68_LAUNCH_METHOD carbon CACHE STRING "How to launch Mac applications (for automated testing)") + else() + set(RETRO68_LAUNCH_METHOD NONE CACHE STRING "How to launch Mac applications (for automated testing)") + endif() else() - if("classic" IN_LIST EMULATOR_LIST) - set(RETRO68_LAUNCH_METHOD classic CACHE STRING "How to launch Mac applications (for automated testing)") - else() - set(RETRO68_LAUNCH_METHOD NONE CACHE STRING "How to launch Mac applications (for automated testing)") - endif() + if("classic" IN_LIST EMULATOR_LIST) + set(RETRO68_LAUNCH_METHOD classic CACHE STRING "How to launch Mac applications (for automated testing)") + else() + set(RETRO68_LAUNCH_METHOD NONE CACHE STRING "How to launch Mac applications (for automated testing)") + endif() endif() if(CMAKE_SYSTEM_NAME MATCHES "RetroCarbon") @@ -33,17 +33,17 @@ set(LAUNCH_METHOD_FLAG) if(RETRO68_LAUNCH_METHOD MATCHES "NONE") else() set(LAUNCH_METHOD_FLAG "-e${RETRO68_LAUNCH_METHOD}") -endif() # RETRO68_LAUNCH_METHOD +endif() # RETRO68_LAUNCH_METHOD enable_testing() function(test FILE) - get_filename_component(NAME ${FILE} NAME_WE) + get_filename_component(NAME ${FILE} NAME_WE) add_application(${NAME} ${FILE} Test.h Test.c) target_include_directories(${NAME} PRIVATE .) - add_test(NAME ${TESTCASE_PREFIX}${NAME} COMMAND ${LAUNCH_APPL} + add_test(NAME ${TESTCASE_PREFIX}${NAME} COMMAND ${LAUNCH_APPL} ${LAUNCH_METHOD_FLAG} ${RETRO68_TEST_CONFIG} ${NAME}.bin) if(ARGN) set_tests_properties(${TESTCASE_PREFIX}${NAME} ${ARGN}) @@ -51,8 +51,8 @@ function(test FILE) endfunction() if(CMAKE_SYSTEM_NAME MATCHES "Retro68") - test(ReallyEmpty.c) - set_target_properties(ReallyEmpty PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-single") + test(ReallyEmpty.c) + set_target_properties(ReallyEmpty PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-single") endif() test(Empty.c) @@ -70,10 +70,10 @@ test(Init.cc PROPERTIES PASS_REGULAR_EXPRESSION "constructor\nmain\ndestructor") test(StdIO.c PROPERTIES PASS_REGULAR_EXPRESSION "OK") if(CMAKE_SYSTEM_NAME MATCHES Retro68) - add_application(Segments Segment1.c Segment2.c Segments.segmap Test.h Test.c) - set_target_properties(Segments PROPERTIES - LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-segments -Wl,${CMAKE_CURRENT_SOURCE_DIR}/Segments.segmap") - add_test(NAME ${TESTCASE_PREFIX}Segments COMMAND ${LAUNCH_APPL} + add_application(Segments Segment1.c Segment2.c Segments.segmap Test.h Test.c) + set_target_properties(Segments PROPERTIES + LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-segments -Wl,${CMAKE_CURRENT_SOURCE_DIR}/Segments.segmap") + add_test(NAME ${TESTCASE_PREFIX}Segments COMMAND ${LAUNCH_APPL} ${LAUNCH_METHOD_FLAG} ${RETRO68_TEST_CONFIG} Segments.bin) endif() diff --git a/AutomatedTests/Empty.c b/AutomatedTests/Empty.c index 7e05b9a6a8..fef951aee0 100644 --- a/AutomatedTests/Empty.c +++ b/AutomatedTests/Empty.c @@ -1,5 +1,5 @@ int main() { - // Test: do things work well enough for us to get to main()? - return 0; + // Test: do things work well enough for us to get to main()? + return 0; } diff --git a/AutomatedTests/File.c b/AutomatedTests/File.c index e4be336294..0608477c1d 100644 --- a/AutomatedTests/File.c +++ b/AutomatedTests/File.c @@ -2,5 +2,5 @@ int main() { - TEST_LOG_OK(); + TEST_LOG_OK(); } diff --git a/AutomatedTests/Init.cc b/AutomatedTests/Init.cc index 1ec84912f7..db3fe78564 100644 --- a/AutomatedTests/Init.cc +++ b/AutomatedTests/Init.cc @@ -3,20 +3,20 @@ class Constructed { public: - Constructed() - { - TestLog("constructor"); - } - ~Constructed() - { - TestLog("destructor"); - } + Constructed() + { + TestLog("constructor"); + } + ~Constructed() + { + TestLog("destructor"); + } }; Constructed thing; int main() { - TestLog("main"); - return 0; + TestLog("main"); + return 0; } diff --git a/AutomatedTests/Log.c b/AutomatedTests/Log.c index 3c3195f8ba..5a0396641b 100644 --- a/AutomatedTests/Log.c +++ b/AutomatedTests/Log.c @@ -4,10 +4,10 @@ char readWriteData[6] = "Three"; int main() { - // constant initialized data - TEST_LOG_SIZED("One",3); - TEST_LOG_SIZED("Two",3); - // read-write initialized data - TEST_LOG_SIZED(readWriteData,5); - return 0; + // constant initialized data + TEST_LOG_SIZED("One",3); + TEST_LOG_SIZED("Two",3); + // read-write initialized data + TEST_LOG_SIZED(readWriteData,5); + return 0; } diff --git a/AutomatedTests/ReallyEmpty.c b/AutomatedTests/ReallyEmpty.c index 1f26045306..4f1d76dec6 100644 --- a/AutomatedTests/ReallyEmpty.c +++ b/AutomatedTests/ReallyEmpty.c @@ -1,6 +1,6 @@ void _start() { - // Test: do things work well enough for us to get to a startup function? - // Note: this won't work for multisegment 68K apps, as the startup function will be in the wrong segment. + // Test: do things work well enough for us to get to a startup function? + // Note: this won't work for multisegment 68K apps, as the startup function will be in the wrong segment. } diff --git a/AutomatedTests/Segment1.c b/AutomatedTests/Segment1.c index dcaca117f8..7c8bbed974 100644 --- a/AutomatedTests/Segment1.c +++ b/AutomatedTests/Segment1.c @@ -10,87 +10,87 @@ void Bar(); Boolean Test(Boolean unloadFoo, Boolean unloadBar, Boolean compact) { - variable = 6; - Foo(); - if(variable != 54) - { - TestLog("Expected 54 after Foo()."); - return false; - } + variable = 6; + Foo(); + if(variable != 54) + { + TestLog("Expected 54 after Foo()."); + return false; + } - if(unloadFoo) - UnloadSeg(&Foo); - if(unloadBar) - UnloadSeg(&Bar); + if(unloadFoo) + UnloadSeg(&Foo); + if(unloadBar) + UnloadSeg(&Bar); - Size grow; - if(compact) - MaxMem(&grow); + Size grow; + if(compact) + MaxMem(&grow); - Bar(); - if(variable != 42) - { - TestLog("Expected 42 after Bar()."); - return false; - } - return true; + Bar(); + if(variable != 42) + { + TestLog("Expected 42 after Bar()."); + return false; + } + return true; } int main() { - Size grow, maxblock, maxblock2, freemem, freemem2; + Size grow, maxblock, maxblock2, freemem, freemem2; - MaxApplZone(); // just to keep things simple and predictable - MoreMasters(); + MaxApplZone(); // just to keep things simple and predictable + MoreMasters(); - maxblock = MaxMem(&grow); - freemem = FreeMem(); + maxblock = MaxMem(&grow); + freemem = FreeMem(); - TestLog("1. No unloading"); - if(!Test(false, false, false)) - return 1; + TestLog("1. No unloading"); + if(!Test(false, false, false)) + return 1; - maxblock2 = MaxMem(&grow); + maxblock2 = MaxMem(&grow); - TestLog("2. UnloadSeg(&Foo)"); - if(!Test(true, false, false)) - return 1; - TestLog("3. UnloadSeg(&Bar)"); - if(!Test(false, true, false)) - return 1; - TestLog("4. UnloadSeg(&Foo); UnloadSeg(&Bar)"); - if(!Test(true, true, false)) - return 1; + TestLog("2. UnloadSeg(&Foo)"); + if(!Test(true, false, false)) + return 1; + TestLog("3. UnloadSeg(&Bar)"); + if(!Test(false, true, false)) + return 1; + TestLog("4. UnloadSeg(&Foo); UnloadSeg(&Bar)"); + if(!Test(true, true, false)) + return 1; - TestLog("5. UnloadSeg(&Foo); MaxMem()"); - if(!Test(true, false, true)) - return 1; - TestLog("6. UnloadSeg(&Bar); MaxMem()"); - if(!Test(false, true, true)) - return 1; - TestLog("7. UnloadSeg(&Foo); UnloadSeg(&Bar); MaxMem()"); - if(!Test(true, true, true)) - return 1; + TestLog("5. UnloadSeg(&Foo); MaxMem()"); + if(!Test(true, false, true)) + return 1; + TestLog("6. UnloadSeg(&Bar); MaxMem()"); + if(!Test(false, true, true)) + return 1; + TestLog("7. UnloadSeg(&Foo); UnloadSeg(&Bar); MaxMem()"); + if(!Test(true, true, true)) + return 1; - UnloadSeg(&Foo); + UnloadSeg(&Foo); - maxblock2 = MaxMem(&grow); - freemem2 = FreeMem(); + maxblock2 = MaxMem(&grow); + freemem2 = FreeMem(); - if(maxblock2 < maxblock || freemem2 < freemem) - { - TestLog("Leak"); - char s[256]; - sprintf(s, "maxblock: %d (delta %d), freemem: %d (delta %d)", - maxblock2, maxblock2-maxblock, freemem2, freemem2-freemem); - TestLog(s); - return 1; - } - else if(maxblock2 > maxblock || freemem2 > freemem) - TestLog("Magic Memory"); + if(maxblock2 < maxblock || freemem2 < freemem) + { + TestLog("Leak"); + char s[256]; + sprintf(s, "maxblock: %d (delta %d), freemem: %d (delta %d)", + maxblock2, maxblock2-maxblock, freemem2, freemem2-freemem); + TestLog(s); + return 1; + } + else if(maxblock2 > maxblock || freemem2 > freemem) + TestLog("Magic Memory"); - TestLog("OK"); + TestLog("OK"); - return 0; + return 0; } diff --git a/AutomatedTests/Segment2.c b/AutomatedTests/Segment2.c index a17b77b408..1aa70db779 100644 --- a/AutomatedTests/Segment2.c +++ b/AutomatedTests/Segment2.c @@ -2,11 +2,11 @@ extern int variable; #include void Foo() { - variable *= 9; + variable *= 9; } void Bar() { - variable /= 9; - variable *= 7; + variable /= 9; + variable *= 7; } diff --git a/AutomatedTests/StdIO.c b/AutomatedTests/StdIO.c index 27f8c65f46..2c3442c5f3 100644 --- a/AutomatedTests/StdIO.c +++ b/AutomatedTests/StdIO.c @@ -2,7 +2,7 @@ int main() { - FILE *f = fopen("out", "w"); - fprintf(f, "OK\n"); - fclose(f); + FILE *f = fopen("out", "w"); + fprintf(f, "OK\n"); + fclose(f); } diff --git a/AutomatedTests/Test.c b/AutomatedTests/Test.c index 5b25106471..6859d2f826 100644 --- a/AutomatedTests/Test.c +++ b/AutomatedTests/Test.c @@ -2,5 +2,5 @@ void TestLog(const char *str) { - TEST_LOG_SIZED(str, strlen(str)); + TEST_LOG_SIZED(str, strlen(str)); } diff --git a/AutomatedTests/Test.h b/AutomatedTests/Test.h index f2a081509b..ad84002808 100644 --- a/AutomatedTests/Test.h +++ b/AutomatedTests/Test.h @@ -22,52 +22,52 @@ void TestLog(const char *str); /* The same thing as a macro. String length has to be given explicitly, * to avoid a call to strlen(). */ #define TEST_LOG_SIZED(str, size) \ - do { \ - HParamBlockRec _hpb; \ - \ - unsigned char _fileName[4]; \ - short _ref;\ - _fileName[0] = 3; \ - _fileName[1] = 'o'; \ - _fileName[2] = 'u'; \ - _fileName[3] = 't'; \ - \ - _hpb.ioParam.ioCompletion = NULL; \ - _hpb.ioParam.ioNamePtr = (StringPtr)_fileName; \ - _hpb.ioParam.ioVRefNum = 0; \ - _hpb.fileParam.ioDirID = 0; \ - _hpb.ioParam.ioPermssn = fsRdWrPerm; \ - _hpb.ioParam.ioMisc = NULL; \ - PBHOpenSync(&_hpb); \ - _ref = _hpb.ioParam.ioRefNum; \ - \ - _hpb.ioParam.ioCompletion = NULL; \ - _hpb.ioParam.ioBuffer = (Ptr)str; \ - _hpb.ioParam.ioReqCount = size; \ - _hpb.ioParam.ioPosMode = fsFromLEOF; \ - _hpb.ioParam.ioPosOffset = 0; \ - _hpb.ioParam.ioRefNum = _ref; \ - _hpb.ioParam.ioMisc = NULL; \ - PBWriteSync((ParmBlkPtr)&_hpb); \ - char _newline = '\n'; \ - _hpb.ioParam.ioCompletion = NULL; \ - _hpb.ioParam.ioBuffer = &_newline; \ - _hpb.ioParam.ioReqCount = 1; \ - _hpb.ioParam.ioPosMode = fsFromLEOF; \ - _hpb.ioParam.ioPosOffset = 0; \ - _hpb.ioParam.ioRefNum = _ref; \ - _hpb.ioParam.ioMisc = NULL; \ - PBWriteSync((ParmBlkPtr)&_hpb); \ - _hpb.ioParam.ioCompletion = NULL; \ - _hpb.ioParam.ioRefNum = _ref; \ - _hpb.ioParam.ioMisc = NULL; \ - PBCloseSync((ParmBlkPtr)&_hpb); \ - _hpb.ioParam.ioCompletion = NULL; \ - _hpb.ioParam.ioNamePtr = NULL; \ - _hpb.ioParam.ioVRefNum = 0; \ - _hpb.ioParam.ioMisc = NULL; \ - PBFlushVolSync((ParmBlkPtr)&_hpb); \ - } while(0); + do { \ + HParamBlockRec _hpb; \ + \ + unsigned char _fileName[4]; \ + short _ref;\ + _fileName[0] = 3; \ + _fileName[1] = 'o'; \ + _fileName[2] = 'u'; \ + _fileName[3] = 't'; \ + \ + _hpb.ioParam.ioCompletion = NULL; \ + _hpb.ioParam.ioNamePtr = (StringPtr)_fileName; \ + _hpb.ioParam.ioVRefNum = 0; \ + _hpb.fileParam.ioDirID = 0; \ + _hpb.ioParam.ioPermssn = fsRdWrPerm; \ + _hpb.ioParam.ioMisc = NULL; \ + PBHOpenSync(&_hpb); \ + _ref = _hpb.ioParam.ioRefNum; \ + \ + _hpb.ioParam.ioCompletion = NULL; \ + _hpb.ioParam.ioBuffer = (Ptr)str; \ + _hpb.ioParam.ioReqCount = size; \ + _hpb.ioParam.ioPosMode = fsFromLEOF; \ + _hpb.ioParam.ioPosOffset = 0; \ + _hpb.ioParam.ioRefNum = _ref; \ + _hpb.ioParam.ioMisc = NULL; \ + PBWriteSync((ParmBlkPtr)&_hpb); \ + char _newline = '\n'; \ + _hpb.ioParam.ioCompletion = NULL; \ + _hpb.ioParam.ioBuffer = &_newline; \ + _hpb.ioParam.ioReqCount = 1; \ + _hpb.ioParam.ioPosMode = fsFromLEOF; \ + _hpb.ioParam.ioPosOffset = 0; \ + _hpb.ioParam.ioRefNum = _ref; \ + _hpb.ioParam.ioMisc = NULL; \ + PBWriteSync((ParmBlkPtr)&_hpb); \ + _hpb.ioParam.ioCompletion = NULL; \ + _hpb.ioParam.ioRefNum = _ref; \ + _hpb.ioParam.ioMisc = NULL; \ + PBCloseSync((ParmBlkPtr)&_hpb); \ + _hpb.ioParam.ioCompletion = NULL; \ + _hpb.ioParam.ioNamePtr = NULL; \ + _hpb.ioParam.ioVRefNum = 0; \ + _hpb.ioParam.ioMisc = NULL; \ + PBFlushVolSync((ParmBlkPtr)&_hpb); \ + } while(0); /* * Output either "OK" or "NO". @@ -75,23 +75,23 @@ void TestLog(const char *str); * we might not want to test them yet. */ -#define TEST_LOG_OK() \ - do { \ - char ok[3]; \ - ok[0] = 'O'; \ - ok[1] = 'K'; \ - ok[2] = '\0'; \ - TEST_LOG_SIZED(ok, 2); \ - } while(0) +#define TEST_LOG_OK() \ + do { \ + char ok[3]; \ + ok[0] = 'O'; \ + ok[1] = 'K'; \ + ok[2] = '\0'; \ + TEST_LOG_SIZED(ok, 2); \ + } while(0) -#define TEST_LOG_NO() \ - do { \ - char no[3]; \ - no[0] = 'O'; \ - no[1] = 'K'; \ - no[2] = '\0'; \ - TEST_LOG_SIZED(no, 2); \ - } while(0) +#define TEST_LOG_NO() \ + do { \ + char no[3]; \ + no[0] = 'O'; \ + no[1] = 'K'; \ + no[2] = '\0'; \ + TEST_LOG_SIZED(no, 2); \ + } while(0) #endif // TEST_H diff --git a/AutomatedTests/Timeout.c b/AutomatedTests/Timeout.c index ec6624054c..3a5dc145b7 100644 --- a/AutomatedTests/Timeout.c +++ b/AutomatedTests/Timeout.c @@ -2,10 +2,10 @@ int main() { - TEST_LOG_SIZED("One",3); - TEST_LOG_SIZED("Two",3); - for(;;) - ; - TEST_LOG_SIZED("Three",5); - return 0; + TEST_LOG_SIZED("One",3); + TEST_LOG_SIZED("Two",3); + for(;;) + ; + TEST_LOG_SIZED("Three",5); + return 0; } diff --git a/AutomatedTests/ZeroInitialized.c b/AutomatedTests/ZeroInitialized.c index e0f149ef4f..82fd0c570d 100644 --- a/AutomatedTests/ZeroInitialized.c +++ b/AutomatedTests/ZeroInitialized.c @@ -10,45 +10,45 @@ EventRecord e; int main() { - int i; - if(commonSymbol) - { - TEST_LOG_NO(); - return 1; - } - if(zeroInited) - { - TEST_LOG_NO(); - return 1; - } - for(i = 0; i < 32768; i++) - { - if(zeroInitedArray[i]) - { - TEST_LOG_NO(); - return 1; - } - zeroInitedArray[i] = 42; - } - + int i; + if(commonSymbol) + { + TEST_LOG_NO(); + return 1; + } + if(zeroInited) + { + TEST_LOG_NO(); + return 1; + } + for(i = 0; i < 32768; i++) + { + if(zeroInitedArray[i]) + { + TEST_LOG_NO(); + return 1; + } + zeroInitedArray[i] = 42; + } + // Initialize some of the Macintosh Toolbox // and maybe trigger a context switch, so we can be sure // our global variables were put in the right placce. #if !TARGET_API_MAC_CARBON - InitGraf(&qd.thePort); - InitFonts(); - InitWindows(); + InitGraf(&qd.thePort); + InitFonts(); + InitWindows(); #endif - GetNextEvent(everyEvent, &e); + GetNextEvent(everyEvent, &e); - for(i = 0; i < 32768; i++) - { - if(zeroInitedArray[i] != 42) - { - TEST_LOG_NO(); - return 1; - } - } - TEST_LOG_OK(); - return 0; + for(i = 0; i < 32768; i++) + { + if(zeroInitedArray[i] != 42) + { + TEST_LOG_NO(); + return 1; + } + } + TEST_LOG_OK(); + return 0; } diff --git a/Console/CMakeLists.txt b/Console/CMakeLists.txt index fe7204b72b..8121b652f7 100644 --- a/Console/CMakeLists.txt +++ b/Console/CMakeLists.txt @@ -16,15 +16,15 @@ # along with Retro68. If not, see . add_library(RetroConsole - retro/Console.cc - retro/Console.h - retro/ConsoleWindow.cc - retro/ConsoleWindow.h - retro/MacUtils.h - retro/InitConsole.cc - ) + retro/Console.cc + retro/Console.h + retro/ConsoleWindow.cc + retro/ConsoleWindow.h + retro/MacUtils.h + retro/InitConsole.cc + ) set_target_properties(retrocrt - PROPERTIES + PROPERTIES COMPILE_OPTIONS -ffunction-sections) # different library name for Carbon @@ -37,6 +37,6 @@ target_include_directories(RetroConsole PUBLIC .) install(TARGETS RetroConsole DESTINATION lib) add_application(ConsoleTest - ConsoleTest.cc - ) + ConsoleTest.cc + ) target_link_libraries(ConsoleTest RetroConsole) diff --git a/Console/ConsoleTest.cc b/Console/ConsoleTest.cc index df282fe9aa..587490fddb 100644 --- a/Console/ConsoleTest.cc +++ b/Console/ConsoleTest.cc @@ -3,21 +3,21 @@ namespace retro { - void InitConsole(); + void InitConsole(); } int main() { - retro::InitConsole(); - std::string out = "Hello, world.\nEnter \"exit\" to quit.\n"; - retro::Console::currentInstance->write(out.data(), out.size()); - - std::string in; - do - { - in = retro::Console::currentInstance->ReadLine(); - out = "You Entered: " + in; - retro::Console::currentInstance->write(out.data(), out.size()); - } while(in != "exit\n"); - return 0; + retro::InitConsole(); + std::string out = "Hello, world.\nEnter \"exit\" to quit.\n"; + retro::Console::currentInstance->write(out.data(), out.size()); + + std::string in; + do + { + in = retro::Console::currentInstance->ReadLine(); + out = "You Entered: " + in; + retro::Console::currentInstance->write(out.data(), out.size()); + } while(in != "exit\n"); + return 0; } diff --git a/Console/retro/Console.cc b/Console/retro/Console.cc index 3fd0a73f0b..bc10bf582b 100644 --- a/Console/retro/Console.cc +++ b/Console/retro/Console.cc @@ -293,7 +293,7 @@ std::string Console::ReadLine() char c; do - { + { c = WaitNextChar(); if(!c) { diff --git a/Console/retro/Console.h b/Console/retro/Console.h index 472777ce6c..d94417c21b 100644 --- a/Console/retro/Console.h +++ b/Console/retro/Console.h @@ -25,66 +25,66 @@ namespace retro { - class Console - { - public: - Console(); - Console(GrafPtr port, Rect r); - ~Console(); + class Console + { + public: + Console(); + Console(GrafPtr port, Rect r); + ~Console(); - void Reshape(Rect newBounds); + void Reshape(Rect newBounds); - void Draw(Rect r); - void Draw() { Draw(bounds); } - void putch(char c); + void Draw(Rect r); + void Draw() { Draw(bounds); } + void putch(char c); - void write(const char *s, int n); - std::string ReadLine(); + void write(const char *s, int n); + std::string ReadLine(); - static Console *currentInstance; + static Console *currentInstance; - short GetRows() const { return rows; } - short GetCols() const { return cols; } - - void Idle(); + short GetRows() const { return rows; } + short GetCols() const { return cols; } + + void Idle(); bool IsEOF() const { return eof; } - private: - GrafPtr consolePort = nullptr; - Rect bounds; + private: + GrafPtr consolePort = nullptr; + Rect bounds; - std::vector chars, onscreen; + std::vector chars, onscreen; - short cellSizeX; - short cellSizeY; + short cellSizeX; + short cellSizeY; - short rows = 0, cols = 0; + short rows = 0, cols = 0; - short cursorX, cursorY; + short cursorX, cursorY; - Rect dirtyRect = {}; - - long blinkTicks = 0; - bool cursorDrawn = false; - bool cursorVisible = true; + Rect dirtyRect = {}; + + long blinkTicks = 0; + bool cursorDrawn = false; + bool cursorVisible = true; bool eof = false; - void PutCharNoUpdate(char c); - void Update(); + void PutCharNoUpdate(char c); + void Update(); - Rect CellRect(short x, short y); - void DrawCell(short x, short y, bool erase = true); - void DrawCells(short x1, short x2, short y, bool erase = true); - void ScrollUp(short n = 1); - - void InvalidateCursor(); + Rect CellRect(short x, short y); + void DrawCell(short x, short y, bool erase = true); + void DrawCells(short x1, short x2, short y, bool erase = true); + void ScrollUp(short n = 1); + + void InvalidateCursor(); - virtual char WaitNextChar(); - - protected: - void Init(GrafPtr port, Rect r); - - }; + virtual char WaitNextChar(); + + protected: + void Init(GrafPtr port, Rect r); + + }; } diff --git a/Console/retro/ConsoleWindow.cc b/Console/retro/ConsoleWindow.cc index 107a7996ad..1f4092d313 100644 --- a/Console/retro/ConsoleWindow.cc +++ b/Console/retro/ConsoleWindow.cc @@ -25,103 +25,103 @@ using namespace retro; namespace { - std::unordered_map *windows = NULL; + std::unordered_map *windows = NULL; } ConsoleWindow::ConsoleWindow(Rect r, ConstStr255Param title) { - GrafPtr port; + GrafPtr port; - win = NewWindow(NULL, &r, "\pRetro68 Console", true, 0, (WindowPtr)-1, false, 0); + win = NewWindow(NULL, &r, "\pRetro68 Console", true, 0, (WindowPtr)-1, false, 0); #if !TARGET_API_MAC_CARBON - port = win; - Rect portRect = port->portRect; + port = win; + Rect portRect = port->portRect; #else - port = GetWindowPort(win); - Rect portRect; - GetPortBounds(port, &portRect); + port = GetWindowPort(win); + Rect portRect; + GetPortBounds(port, &portRect); #endif - SetPort(port); - EraseRect(&portRect); + SetPort(port); + EraseRect(&portRect); - if(!windows) - windows = new std::unordered_map(); - (*windows)[win] = this; + if(!windows) + windows = new std::unordered_map(); + (*windows)[win] = this; - Init(port, portRect); + Init(port, portRect); } ConsoleWindow::~ConsoleWindow() { - windows->erase(win); - DisposeWindow(win); + windows->erase(win); + DisposeWindow(win); } char ConsoleWindow::WaitNextChar() { - EventRecord event; - WindowPtr eventWin; - ConsoleWindow *realConsole; + EventRecord event; + WindowPtr eventWin; + ConsoleWindow *realConsole; #if TARGET_API_MAC_CARBON - Rect *boundsPtr = NULL; + Rect *boundsPtr = NULL; #else - Rect *boundsPtr = &qd.screenBits.bounds; + Rect *boundsPtr = &qd.screenBits.bounds; #endif - - do - { - #if TARGET_API_MAC_CARBON - #define SystemTask() - #endif - SystemTask(); - Idle(); - while(!GetNextEvent(everyEvent, &event)) - { - SystemTask(); - Idle(); - } - - switch(event.what) - { - case updateEvt: - eventWin = (WindowPtr)event.message; - realConsole = (*windows)[(WindowPtr)event.message]; - if(realConsole) - { - Rect updateRect; - BeginUpdate(eventWin); + + do + { + #if TARGET_API_MAC_CARBON + #define SystemTask() + #endif + SystemTask(); + Idle(); + while(!GetNextEvent(everyEvent, &event)) + { + SystemTask(); + Idle(); + } + + switch(event.what) + { + case updateEvt: + eventWin = (WindowPtr)event.message; + realConsole = (*windows)[(WindowPtr)event.message]; + if(realConsole) + { + Rect updateRect; + BeginUpdate(eventWin); #if TARGET_API_MAC_CARBON - RgnHandle rgn = NewRgn(); - GetPortVisibleRegion(GetWindowPort(eventWin), rgn); - GetRegionBounds(rgn, &updateRect); - DisposeRgn(rgn); + RgnHandle rgn = NewRgn(); + GetPortVisibleRegion(GetWindowPort(eventWin), rgn); + GetRegionBounds(rgn, &updateRect); + DisposeRgn(rgn); #else - updateRect = (*qd.thePort->visRgn)->rgnBBox; // Life was simple back then. + updateRect = (*qd.thePort->visRgn)->rgnBBox; // Life was simple back then. #endif - realConsole->Draw(updateRect); - EndUpdate(eventWin); - } - break; - case mouseDown: - - switch(FindWindow(event.where, &eventWin)) - { - case inDrag: - DragWindow(eventWin, event.where, boundsPtr); - break; - case inGrow: - { - long growResult = GrowWindow(eventWin, event.where, boundsPtr); - SizeWindow(eventWin, growResult & 0xFFFF, growResult >> 16, false); - Reshape(Rect {0, 0, (short) (growResult >> 16), (short) (growResult & 0xFFFF) }); - } - break; - } - break; - } - } while(event.what != keyDown && event.what != autoKey); - - return event.message & charCodeMask; + realConsole->Draw(updateRect); + EndUpdate(eventWin); + } + break; + case mouseDown: + + switch(FindWindow(event.where, &eventWin)) + { + case inDrag: + DragWindow(eventWin, event.where, boundsPtr); + break; + case inGrow: + { + long growResult = GrowWindow(eventWin, event.where, boundsPtr); + SizeWindow(eventWin, growResult & 0xFFFF, growResult >> 16, false); + Reshape(Rect {0, 0, (short) (growResult >> 16), (short) (growResult & 0xFFFF) }); + } + break; + } + break; + } + } while(event.what != keyDown && event.what != autoKey); + + return event.message & charCodeMask; } diff --git a/Console/retro/ConsoleWindow.h b/Console/retro/ConsoleWindow.h index 1f27359648..6d491f7b04 100644 --- a/Console/retro/ConsoleWindow.h +++ b/Console/retro/ConsoleWindow.h @@ -25,14 +25,14 @@ namespace retro { - class ConsoleWindow : public Console - { - public: - ConsoleWindow(Rect r, ConstStr255Param title); - ~ConsoleWindow(); - private: - WindowPtr win; + class ConsoleWindow : public Console + { + public: + ConsoleWindow(Rect r, ConstStr255Param title); + ~ConsoleWindow(); + private: + WindowPtr win; - virtual char WaitNextChar(); - }; + virtual char WaitNextChar(); + }; } diff --git a/Console/retro/InitConsole.cc b/Console/retro/InitConsole.cc index b7c3f29b4e..31c096d782 100644 --- a/Console/retro/InitConsole.cc +++ b/Console/retro/InitConsole.cc @@ -1,20 +1,20 @@ /* - Copyright 2014 Wolfgang Thaller. + Copyright 2014 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include @@ -34,26 +34,26 @@ namespace retro { - void InitConsole(); + void InitConsole(); } using namespace retro; void retro::InitConsole() { - if(Console::currentInstance) - return; + if(Console::currentInstance) + return; Console::currentInstance = (Console*) -1; #if !TARGET_API_MAC_CARBON - InitGraf(&qd.thePort); - InitFonts(); - InitWindows(); - InitMenus(); + InitGraf(&qd.thePort); + InitFonts(); + InitWindows(); + InitMenus(); - Rect r = qd.screenBits.bounds; + Rect r = qd.screenBits.bounds; #else - Rect r = (*GetMainDevice())->gdRect; + Rect r = (*GetMainDevice())->gdRect; #endif { // give MultiFinder a chance to bring the App to front @@ -71,41 +71,41 @@ void retro::InitConsole() EventAvail(everyEvent, &event); } - r.top += 40; - InsetRect(&r, 5,5); - - Console::currentInstance = new ConsoleWindow(r, "\pRetro68 Console"); - InitCursor(); + r.top += 40; + InsetRect(&r, 5,5); + + Console::currentInstance = new ConsoleWindow(r, "\pRetro68 Console"); + InitCursor(); } extern "C" ssize_t _consolewrite(int fd, const void *buf, size_t count) { - if(!Console::currentInstance) - InitConsole(); - if(Console::currentInstance == (Console*)-1) - return 0; + if(!Console::currentInstance) + InitConsole(); + if(Console::currentInstance == (Console*)-1) + return 0; - Console::currentInstance->write((const char*)buf, count); - return count; + Console::currentInstance->write((const char*)buf, count); + return count; } extern "C" ssize_t _consoleread(int fd, void *buf, size_t count) { - if(!Console::currentInstance) - InitConsole(); - if(Console::currentInstance == (Console*)-1) - return 0; + if(!Console::currentInstance) + InitConsole(); + if(Console::currentInstance == (Console*)-1) + return 0; - static std::string consoleBuf; - if(consoleBuf.size() == 0) - { - consoleBuf = Console::currentInstance->ReadLine(); + static std::string consoleBuf; + if(consoleBuf.size() == 0) + { + consoleBuf = Console::currentInstance->ReadLine(); if(!Console::currentInstance->IsEOF()) consoleBuf += "\n"; - } - if(count > consoleBuf.size()) - count = consoleBuf.size(); - memcpy(buf, consoleBuf.data(), count); - consoleBuf = consoleBuf.substr(count); - return count; + } + if(count > consoleBuf.size()) + count = consoleBuf.size(); + memcpy(buf, consoleBuf.data(), count); + consoleBuf = consoleBuf.substr(count); + return count; } diff --git a/ConvertObj/ConvertObj.cc b/ConvertObj/ConvertObj.cc index d3e93f29af..6383c48fd7 100644 --- a/ConvertObj/ConvertObj.cc +++ b/ConvertObj/ConvertObj.cc @@ -25,22 +25,22 @@ bool dataSections = true; bool dataInText = false; using stringid = int; -unordered_map sectionMap; -unordered_map stringDictionary; +unordered_map sectionMap; +unordered_map stringDictionary; unordered_set localLabels; enum RecordType { - kPad = 0, - kFirst = 1, - kLast = 2, + kPad = 0, + kFirst = 1, + kLast = 2, kComment = 3, - kDictionary = 4, - kModule = 5, - kEntryPoint = 6, - kSize = 7, - kContent = 8, - kReference = 9, - kComputedRef = 10, + kDictionary = 4, + kModule = 5, + kEntryPoint = 6, + kSize = 7, + kContent = 8, + kReference = 9, + kComputedRef = 10, kFilename = 11 }; @@ -49,19 +49,19 @@ enum ModuleFlags { kExtern = 0x08 // default local }; -enum ReferenceFlags { // flags field of kReference - k16BitPatch = 0x10, // default 32Bit - kFromData = 0x01, // default fromCode - kA5Relative = 0x80, // default absolute +enum ReferenceFlags { // flags field of kReference + k16BitPatch = 0x10, // default 32Bit + kFromData = 0x01, // default fromCode + kA5Relative = 0x80, // default absolute - kUnknownReferenceFlags = 0x6E // rather a lot, isn't it? - // The following flags are known to exist from DumpOBJ, - // but their value is unkown as I haven't actually seen them yet: - // k32BitOffsets (default k16BitOffsets) + kUnknownReferenceFlags = 0x6E // rather a lot, isn't it? + // The following flags are known to exist from DumpOBJ, + // but their value is unkown as I haven't actually seen them yet: + // k32BitOffsets (default k16BitOffsets) }; enum ComputedReferenceFlags { - kDifference = 0x80 + kDifference = 0x80 }; enum ContentFlags { @@ -73,97 +73,97 @@ enum ContentFlags { string encodeIdentifier(stringid id) { const string& s = stringDictionary[id]; - std::ostringstream ss; + std::ostringstream ss; if(localLabels.find(id) != localLabels.end()) ss << "L" << id << "."; if(s.empty() || isdigit(s[0])) - ss << "__z"; + ss << "__z"; - for(char c : s) - { - if(c == '_' || isalnum(c)) - ss << c; - else - { - ss << "__z" << (int) c << "_"; - } - } + for(char c : s) + { + if(c == '_' || isalnum(c)) + ss << c; + else + { + ss << "__z" << (int) c << "_"; + } + } - return ss.str(); + return ss.str(); } struct Reloc { - int size; - stringid name1 = -1; - stringid name2 = -1; + int size; + stringid name1 = -1; + stringid name2 = -1; - int write(std::ostream& out, uint8_t *p); + int write(std::ostream& out, uint8_t *p); }; int Reloc::write(std::ostream& out, uint8_t *p) { - if(size == 2) - { - out << "\t.short "; - int val = (int)p[0] * 256 + p[1]; + if(size == 2) + { + out << "\t.short "; + int val = (int)p[0] * 256 + p[1]; - out << encodeIdentifier(name1); - if(name2 != -1) - out << " - " << encodeIdentifier(name2); - if(val > 0) - out << " + " << val; - else if(val < 0) - out << " - " << -val; - if(name2 == -1) - out << "-."; - out << std::endl; - return 2; - } - else if(size == 4) - { - out << "\t.long "; - int val = ((int)p[0] << 24) | ((int)p[1] << 16) | ((int)p[2] << 8) | p[3]; + out << encodeIdentifier(name1); + if(name2 != -1) + out << " - " << encodeIdentifier(name2); + if(val > 0) + out << " + " << val; + else if(val < 0) + out << " - " << -val; + if(name2 == -1) + out << "-."; + out << std::endl; + return 2; + } + else if(size == 4) + { + out << "\t.long "; + int val = ((int)p[0] << 24) | ((int)p[1] << 16) | ((int)p[2] << 8) | p[3]; - out << encodeIdentifier(name1); - if(name2 != -1) - out << " - " << encodeIdentifier(name2); - if(val > 0) - out << " + " << val; - else if(val < 0) - out << " - " << -val; - out << std::endl; - return 4; - } - else - { - assert(false); - return 1; - } + out << encodeIdentifier(name1); + if(name2 != -1) + out << " - " << encodeIdentifier(name2); + if(val > 0) + out << " + " << val; + else if(val < 0) + out << " - " << -val; + out << std::endl; + return 4; + } + else + { + assert(false); + return 1; + } } struct Module { - stringid name; - stringid segment; + stringid name; + stringid segment; bool isData; - vector bytes; - unordered_map> labels; - unordered_map relocs; + vector bytes; + unordered_map> labels; + unordered_map relocs; - std::vector> nearrefs; + std::vector> nearrefs; - void write(std::ostream& out); + void write(std::ostream& out); }; void Module::write(std::ostream& out) { - - string encodedName = encodeIdentifier(sectionMap[name]); + + string encodedName = encodeIdentifier(sectionMap[name]); - if(isData && !dataInText) + if(isData && !dataInText) { if(dataSections) out << "\t.section .data." << encodedName << ",\"aw\"\n"; @@ -175,41 +175,41 @@ void Module::write(std::ostream& out) else { if(functionSections) - out << "\t.section .text." << encodedName << ",\"ax\",@progbits\n"; + out << "\t.section .text." << encodedName << ",\"ax\",@progbits\n"; else - out << "\t.section .text,\"ax\",@progbits\n"; + out << "\t.section .text,\"ax\",@progbits\n"; out << "\t.align 2,0\n"; } - for(uint32_t offset = 0; offset < bytes.size();) - { - auto labelP = labels.find(offset); - if(labelP != labels.end()) - { - for(stringid rawLabel : labelP->second) - { - string label = encodeIdentifier(rawLabel); - if(localLabels.find(rawLabel) == localLabels.end()) + for(uint32_t offset = 0; offset < bytes.size();) + { + auto labelP = labels.find(offset); + if(labelP != labels.end()) + { + for(stringid rawLabel : labelP->second) + { + string label = encodeIdentifier(rawLabel); + if(localLabels.find(rawLabel) == localLabels.end()) out << "\t.globl " << label << "\n"; - out << label << ":\n"; - } - } + out << label << ":\n"; + } + } - auto relocP = relocs.find(offset); - if(relocP != relocs.end()) - { - offset += relocP->second.write(out, &bytes[offset]); - } - else - { - out << "\t.byte " << (int)bytes[offset] << "\n"; - offset++; - } - } + auto relocP = relocs.find(offset); + if(relocP != relocs.end()) + { + offset += relocP->second.write(out, &bytes[offset]); + } + else + { + out << "\t.byte " << (int)bytes[offset] << "\n"; + offset++; + } + } if(addMacsbugNames && !isData) { if(functionSections) - out << "\t.section .text." << encodedName << ".macsbug,\"ax\",@progbits\n"; + out << "\t.section .text." << encodedName << ".macsbug,\"ax\",@progbits\n"; if(encodedName.size() < 32) out << "\t.byte " << (encodedName.size() | 0x80) << "\n"; else @@ -218,38 +218,38 @@ void Module::write(std::ostream& out) out << "\t.ascii \"" << encodedName << "\"\n"; out << "\t.align 2,0\n\t.short 0\n"; } - out << "# ######\n\n"; + out << "# ######\n\n"; } void sortModules(std::vector>& modules) { - std::set unemitted; - for(auto& m : modules) - unemitted.insert(m->name); - - std::unordered_map> nameMap; - for(auto& m : modules) - for(auto& l : m->labels) - for(auto& str : l.second) - nameMap[str] = m; - - - for(auto& m : modules) - for(auto& r : m->relocs) - { - if(r.second.size != 2) - continue; - if(r.second.name2 == -1) - { - if(auto p = nameMap.find(r.second.name1); p != nameMap.end()) + std::set unemitted; + for(auto& m : modules) + unemitted.insert(m->name); + + std::unordered_map> nameMap; + for(auto& m : modules) + for(auto& l : m->labels) + for(auto& str : l.second) + nameMap[str] = m; + + + for(auto& m : modules) + for(auto& r : m->relocs) + { + if(r.second.size != 2) + continue; + if(r.second.name2 == -1) + { + if(auto p = nameMap.find(r.second.name1); p != nameMap.end()) { std::shared_ptr m1 = p->second; m1->nearrefs.push_back(m); m->nearrefs.push_back(m1); } - } - else - { + } + else + { auto p1 = nameMap.find(r.second.name1); auto p2 = nameMap.find(r.second.name2); @@ -260,60 +260,60 @@ void sortModules(std::vector>& modules) m1->nearrefs.push_back(m2); m2->nearrefs.push_back(m1); } - } - } - + } + } + - std::vector> sorted; - sorted.reserve(modules.size()); - - auto p = sorted.begin(); - - while(!unemitted.empty()) - { - while(p != sorted.end()) - { - for(auto& m2weak : (*p)->nearrefs) - { - if(std::shared_ptr m2 = m2weak.lock()) - { - auto unemittedP = unemitted.find(m2->name); - if(unemittedP != unemitted.end()) - { - sorted.push_back(m2); - unemitted.erase(unemittedP); - } - } - } - ++p; - } + std::vector> sorted; + sorted.reserve(modules.size()); + + auto p = sorted.begin(); + + while(!unemitted.empty()) + { + while(p != sorted.end()) + { + for(auto& m2weak : (*p)->nearrefs) + { + if(std::shared_ptr m2 = m2weak.lock()) + { + auto unemittedP = unemitted.find(m2->name); + if(unemittedP != unemitted.end()) + { + sorted.push_back(m2); + unemitted.erase(unemittedP); + } + } + } + ++p; + } if(!unemitted.empty()) { sorted.push_back(nameMap[*unemitted.begin()]); unemitted.erase(unemitted.begin()); } - } - - sorted.swap(modules); + } + + sorted.swap(modules); } int main(int argc, char* argv[]) { - if(argc != 2) - { - std::cerr << "Usage: ConvertOBJ mpw.o > retro68.s\n"; - return 1; - } - std::ifstream in(argv[1]); - if(!in) - { - std::cerr << "Could not read imput file \"" << argv[1] << "\"\n"; - std::cerr << "Usage: ConvertOBJ mpw.o > retro68.s\n"; - return 1; - } - - std::shared_ptr module; - std::vector> modules; + if(argc != 2) + { + std::cerr << "Usage: ConvertOBJ mpw.o > retro68.s\n"; + return 1; + } + std::ifstream in(argv[1]); + if(!in) + { + std::cerr << "Could not read imput file \"" << argv[1] << "\"\n"; + std::cerr << "Usage: ConvertOBJ mpw.o > retro68.s\n"; + return 1; + } + + std::shared_ptr module; + std::vector> modules; { @@ -343,30 +343,30 @@ int main(int argc, char* argv[]) std::cout << "\t.text\n\t.align 2\n"; - for(bool endOfObject = false; !endOfObject;) { - if(verbose) - std::cerr << std::hex << in.tellg() << ": "; - int recordType = byte(in); - if(!in) - { - std::cerr << "Unexpected End of File\n"; - return 1; - } + for(bool endOfObject = false; !endOfObject;) { + if(verbose) + std::cerr << std::hex << in.tellg() << ": "; + int recordType = byte(in); + if(!in) + { + std::cerr << "Unexpected End of File\n"; + return 1; + } - if(verbose) - std::cerr << "Record: " << recordType << std::endl; + if(verbose) + std::cerr << "Record: " << recordType << std::endl; - switch(recordType) - { - case kPad: - if(verbose) - std::cerr << "Pad\n"; - break; + switch(recordType) + { + case kPad: + if(verbose) + std::cerr << "Pad\n"; + break; case kComment: { - /*int flags =*/ byte(in); - int size = word(in); + /*int flags =*/ byte(in); + int size = word(in); size -= 4; if(verbose) std::cerr << "Comment: "; @@ -380,189 +380,189 @@ int main(int argc, char* argv[]) std::cerr << std::endl; } break; - case kDictionary: - { - /*int flags =*/ byte(in); - if(verbose) - std::cerr << "Dictionary\n"; - int sz = word(in); - int stringId = word(in); - int end = (int)(in.tellg()) - 6 + sz; - while(in.tellg() < end) - { - int n = byte(in); - string s; - for(int i = 0; i < n; i++) - s += (char) byte(in); - if(verbose) - std::cerr << s << std::endl; - stringDictionary[stringId++] = s; - } - } - break; - case kModule: - { - int flags = byte(in); - stringid name = word(in); - sectionMap[name] = name; - stringid segment = word(in); + case kDictionary: + { + /*int flags =*/ byte(in); + if(verbose) + std::cerr << "Dictionary\n"; + int sz = word(in); + int stringId = word(in); + int end = (int)(in.tellg()) - 6 + sz; + while(in.tellg() < end) + { + int n = byte(in); + string s; + for(int i = 0; i < n; i++) + s += (char) byte(in); + if(verbose) + std::cerr << s << std::endl; + stringDictionary[stringId++] = s; + } + } + break; + case kModule: + { + int flags = byte(in); + stringid name = word(in); + sectionMap[name] = name; + stringid segment = word(in); - if(verbose) - std::cerr << "Module " << stringDictionary[name] << "(" << stringDictionary[segment] << "), flags = " << flags << "\n"; + if(verbose) + std::cerr << "Module " << stringDictionary[name] << "(" << stringDictionary[segment] << "), flags = " << flags << "\n"; if((flags & kExtern) == 0) localLabels.insert(name); - module.reset(new Module()); - module->name = name; + module.reset(new Module()); + module->name = name; module->segment = segment; module->isData = (flags & kData) != 0; - module->labels[0].push_back(name); - modules.push_back(module); - } - break; - case kContent: - { - int flags = byte(in); - int sz = word(in) - 4; - uint32_t offset = 0; - if(flags & kContentOffset) - { - offset = longword(in); - sz -= 4; - } + module->labels[0].push_back(name); + modules.push_back(module); + } + break; + case kContent: + { + int flags = byte(in); + int sz = word(in) - 4; + uint32_t offset = 0; + if(flags & kContentOffset) + { + offset = longword(in); + sz -= 4; + } int repeat = 1; if(flags & kContentRepeat) { repeat = word(in); sz -= 2; } - if(verbose) - std::cerr << "Content (offset = " << offset << ", size = " << sz << ", repeat = " << repeat << ")\n"; + if(verbose) + std::cerr << "Content (offset = " << offset << ", size = " << sz << ", repeat = " << repeat << ")\n"; - assert(module.get()); - if(module->bytes.size() < offset + sz * repeat) - module->bytes.resize(offset + sz * repeat); - in.read((char*) &module->bytes[offset], sz); + assert(module.get()); + if(module->bytes.size() < offset + sz * repeat) + module->bytes.resize(offset + sz * repeat); + in.read((char*) &module->bytes[offset], sz); while(--repeat > 0) { std::copy(module->bytes.begin() + offset, module->bytes.begin() + offset + sz, module->bytes.begin() + offset + sz); offset += sz; } - } - break; - case kSize: - { - /*int flags =*/ byte(in); - long size = longword(in); - if(verbose) - std::cerr << "Size " << size << "\n"; - assert(module.get()); - module->bytes.resize(size); - } - break; - case kReference: - { - int flags = byte(in); - int sz = word(in); - int end = (int)(in.tellg()) - 4 + sz; - stringid name = word(in); + } + break; + case kSize: + { + /*int flags =*/ byte(in); + long size = longword(in); + if(verbose) + std::cerr << "Size " << size << "\n"; + assert(module.get()); + module->bytes.resize(size); + } + break; + case kReference: + { + int flags = byte(in); + int sz = word(in); + int end = (int)(in.tellg()) - 4 + sz; + stringid name = word(in); - if(verbose) - std::cerr << "Reference to " << stringDictionary[name] << " at\n"; - Reloc reloc; - reloc.name1 = name; + if(verbose) + std::cerr << "Reference to " << stringDictionary[name] << " at\n"; + Reloc reloc; + reloc.name1 = name; - if(flags & kUnknownReferenceFlags) - { - std::cerr << "Unknown relocation flags: 0x" << std::hex << flags << std::endl; - std::cerr << "Cannot convert this file.\n"; - std::exit(1); - } - if(flags & kA5Relative) - { - std::cerr << "Unsupported relocation flags: 0x" << std::hex << flags << std::endl; - std::cerr << "MPW .o files with near-model global variables or calls to imported functions will not work.\n"; - std::cerr << "Cannot convert this file.\n"; - std::exit(1); - } - flags &= ~kFromData; // FIXME: sticking data bits in the text section, not nice, but might sometimes work + if(flags & kUnknownReferenceFlags) + { + std::cerr << "Unknown relocation flags: 0x" << std::hex << flags << std::endl; + std::cerr << "Cannot convert this file.\n"; + std::exit(1); + } + if(flags & kA5Relative) + { + std::cerr << "Unsupported relocation flags: 0x" << std::hex << flags << std::endl; + std::cerr << "MPW .o files with near-model global variables or calls to imported functions will not work.\n"; + std::cerr << "Cannot convert this file.\n"; + std::exit(1); + } + flags &= ~kFromData; // FIXME: sticking data bits in the text section, not nice, but might sometimes work - reloc.size = (flags & k16BitPatch ? 2 : 4); + reloc.size = (flags & k16BitPatch ? 2 : 4); - assert(module); + assert(module); - while(in.tellg() < end) - { - int offset = word(in); - if(verbose) - std::cerr << " " << offset << std::endl; - module->relocs[offset] = reloc; - } - } - break; - case kEntryPoint: - { - int flags = byte(in); - stringid name = word(in); - long offset = longword(in); - if(verbose) - std::cerr << "EntryPoint " << stringDictionary[name] << " at offset " << offset << "\n"; + while(in.tellg() < end) + { + int offset = word(in); + if(verbose) + std::cerr << " " << offset << std::endl; + module->relocs[offset] = reloc; + } + } + break; + case kEntryPoint: + { + int flags = byte(in); + stringid name = word(in); + long offset = longword(in); + if(verbose) + std::cerr << "EntryPoint " << stringDictionary[name] << " at offset " << offset << "\n"; if((flags & kExtern) == 0) localLabels.insert(name); - assert(module); - module->labels[offset].push_back(name); - } - break; - case kComputedRef: - { - int flags = byte(in); - int sz = word(in); - int end = (int)(in.tellg()) - 4 + sz; - stringid name1 = word(in); - stringid name2 = word(in); + assert(module); + module->labels[offset].push_back(name); + } + break; + case kComputedRef: + { + int flags = byte(in); + int sz = word(in); + int end = (int)(in.tellg()) - 4 + sz; + stringid name1 = word(in); + stringid name2 = word(in); - Reloc reloc; - reloc.name1 = name1; - reloc.name2 = name2; - reloc.size = 2; + Reloc reloc; + reloc.name1 = name1; + reloc.name2 = name2; + reloc.size = 2; - assert(flags == 0x90); - assert(module); + assert(flags == 0x90); + assert(module); if(auto p = sectionMap.find(name1); p != sectionMap.end()) sectionMap[module->name] = p->second; - if(verbose) - std::cerr << "ComputedReference to " + if(verbose) + std::cerr << "ComputedReference to " << stringDictionary[name1] << " - " << stringDictionary[name2] << " at\n"; - while(in.tellg() < end) - { - int offset = word(in); - if(verbose) - std::cerr << " " << offset << std::endl; - module->relocs[offset] = reloc; - } - } - break; + while(in.tellg() < end) + { + int offset = word(in); + if(verbose) + std::cerr << " " << offset << std::endl; + module->relocs[offset] = reloc; + } + } + break; case kFilename: /* int flags = */ byte(in); /* short nameref = */ word(in); /* long date = */ longword(in); break; - case kLast: - byte(in); - endOfObject = true; - break; - default: - std::cerr << "Unknown record (type " << recordType << ") at " << std::hex << in.tellg() << std::endl; - return 1; - } - } - if(shouldSortModules) - sortModules(modules); - for(auto& m : modules) - m->write(std::cout); - return 0; + case kLast: + byte(in); + endOfObject = true; + break; + default: + std::cerr << "Unknown record (type " << recordType << ") at " << std::hex << in.tellg() << std::endl; + return 1; + } + } + if(shouldSortModules) + sortModules(modules); + for(auto& m : modules) + m->write(std::cout); + return 0; } diff --git a/Elf2Mac/CMakeLists.txt b/Elf2Mac/CMakeLists.txt index 372623e11e..592996d0da 100644 --- a/Elf2Mac/CMakeLists.txt +++ b/Elf2Mac/CMakeLists.txt @@ -18,12 +18,12 @@ find_package(Boost COMPONENTS REQUIRED) add_executable(Elf2Mac - Elf2Mac.h Elf2Mac.cc SegmentMap.cc LdScript.cc - Reloc.h Reloc.cc - Symbol.h Symbol.cc - Symtab.h Symtab.cc - Section.h Section.cc - Object.h Object.cc) + Elf2Mac.h Elf2Mac.cc SegmentMap.cc LdScript.cc + Reloc.h Reloc.cc + Symbol.h Symbol.cc + Symtab.h Symtab.cc + Section.h Section.cc + Object.h Object.cc) target_link_libraries(Elf2Mac ResourceFiles ELF) target_include_directories(Elf2Mac PRIVATE ${CMAKE_INSTALL_PREFIX}/include) diff --git a/Elf2Mac/Elf2Mac.cc b/Elf2Mac/Elf2Mac.cc index 566e928315..48436b5b03 100644 --- a/Elf2Mac/Elf2Mac.cc +++ b/Elf2Mac/Elf2Mac.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Elf2Mac.h" @@ -45,179 +45,179 @@ string argvZero; void RealLD(vector args) { - vector argv; - string realLD = argvZero + ".real"; - argv.push_back(realLD.c_str()); - for(string& s : args) - argv.push_back(s.c_str()); - argv.push_back(NULL); + vector argv; + string realLD = argvZero + ".real"; + argv.push_back(realLD.c_str()); + for(string& s : args) + argv.push_back(s.c_str()); + argv.push_back(NULL); - pid_t pid = fork(); - if(pid < 0) - { - perror("unable to fork"); - exit(-1); - } - else if(pid == 0) - { - execvp(argv[0], const_cast (argv.data())); - perror("exec failed"); - exit(-1); - } - else - { - int wstatus; - int result = 0; - do - { - result = waitpid(pid, &wstatus, 0); - } while(result == -1 && errno == EINTR); - if(!WIFEXITED(wstatus)) - { - errx(EXIT_FAILURE, "ld process did not exit properly"); - } - else - { - int exitcode = WEXITSTATUS(wstatus); - if(exitcode) - exit(exitcode); - } - } + pid_t pid = fork(); + if(pid < 0) + { + perror("unable to fork"); + exit(-1); + } + else if(pid == 0) + { + execvp(argv[0], const_cast (argv.data())); + perror("exec failed"); + exit(-1); + } + else + { + int wstatus; + int result = 0; + do + { + result = waitpid(pid, &wstatus, 0); + } while(result == -1 && errno == EINTR); + if(!WIFEXITED(wstatus)) + { + errx(EXIT_FAILURE, "ld process did not exit properly"); + } + else + { + int exitcode = WEXITSTATUS(wstatus); + if(exitcode) + exit(exitcode); + } + } } int main(int argc, char *argv[]) { - vector args; - std::copy(argv + 1, argv+argc, std::back_inserter(args)); - argvZero = argv[0]; + vector args; + std::copy(argv + 1, argv+argc, std::back_inserter(args)); + argvZero = argv[0]; - if(boost::algorithm::ends_with(argv[0], "ld")) - { - string outputFile = "a.out"; + if(boost::algorithm::ends_with(argv[0], "ld")) + { + string outputFile = "a.out"; string entryPoint = "_start"; - bool elf2mac = false; - bool flatoutput = false; - bool segments = true; - bool stripMacsbug = false; + bool elf2mac = false; + bool flatoutput = false; + bool segments = true; + bool stripMacsbug = false; bool saveLdScript = false; - SegmentMap segmentMap; + SegmentMap segmentMap; - vector args2; - for(auto p = args.begin(), e = args.end(); p != e; ++p) - { - if(*p == "-o") - { - ++p; - if(p == e) - errx(EXIT_FAILURE, "-o missing argument"); - outputFile = *p; - } - else if(boost::algorithm::starts_with(*p, "-o")) - { - outputFile = (*p).substr(2); - } - else if(*p == "-elf2mac" || *p == "--elf2mac") - { - elf2mac = true; - } + vector args2; + for(auto p = args.begin(), e = args.end(); p != e; ++p) + { + if(*p == "-o") + { + ++p; + if(p == e) + errx(EXIT_FAILURE, "-o missing argument"); + outputFile = *p; + } + else if(boost::algorithm::starts_with(*p, "-o")) + { + outputFile = (*p).substr(2); + } + else if(*p == "-elf2mac" || *p == "--elf2mac") + { + elf2mac = true; + } else if(*p == "-e") - { - ++p; - if(p == e) - errx(EXIT_FAILURE, "-e missing argument"); - entryPoint = *p; - } + { + ++p; + if(p == e) + errx(EXIT_FAILURE, "-e missing argument"); + entryPoint = *p; + } else if(boost::algorithm::starts_with(*p, "-e")) { entryPoint = (*p).substr(2); } - else if(*p == "--mac-flat") - { - elf2mac = true; - flatoutput = true; - segments = false; - } - else if(*p == "--mac-single") - { - elf2mac = true; - flatoutput = false; - segments = false; - } - else if(*p == "--mac-segments") - { - elf2mac = true; - if(flatoutput) - errx(EXIT_FAILURE, "--mac-segments can't be used with --mac-flat"); - ++p; - if(p == e) - errx(EXIT_FAILURE, "--mac-segments missing argument"); - segmentMap = SegmentMap(*p); - } - else if(*p == "--mac-strip-macsbug") - { - stripMacsbug = true; - } + else if(*p == "--mac-flat") + { + elf2mac = true; + flatoutput = true; + segments = false; + } + else if(*p == "--mac-single") + { + elf2mac = true; + flatoutput = false; + segments = false; + } + else if(*p == "--mac-segments") + { + elf2mac = true; + if(flatoutput) + errx(EXIT_FAILURE, "--mac-segments can't be used with --mac-flat"); + ++p; + if(p == e) + errx(EXIT_FAILURE, "--mac-segments missing argument"); + segmentMap = SegmentMap(*p); + } + else if(*p == "--mac-strip-macsbug") + { + stripMacsbug = true; + } else if(*p == "--mac-keep-ldscript") { saveLdScript = true; } - else - { - args2.push_back(*p); - } - } + else + { + args2.push_back(*p); + } + } - if(elf2mac) - { - char tmpfile[] = "/tmp/ldscriptXXXXXX"; - int fd = mkstemp(tmpfile); - if(fd < 0) - errx(EXIT_FAILURE, "can't create temp file"); + if(elf2mac) + { + char tmpfile[] = "/tmp/ldscriptXXXXXX"; + int fd = mkstemp(tmpfile); + if(fd < 0) + errx(EXIT_FAILURE, "can't create temp file"); - { - ofstream out(tmpfile); - if(segments) - { - segmentMap.CreateLdScript(out, entryPoint, stripMacsbug); - } - else - { - CreateFlatLdScript(out, entryPoint, stripMacsbug); - } - } + { + ofstream out(tmpfile); + if(segments) + { + segmentMap.CreateLdScript(out, entryPoint, stripMacsbug); + } + else + { + CreateFlatLdScript(out, entryPoint, stripMacsbug); + } + } - args2.push_back("-o"); - args2.push_back(outputFile + ".gdb"); - args2.push_back("-T"); - args2.push_back(tmpfile); - RealLD(args2); - if(saveLdScript) + args2.push_back("-o"); + args2.push_back(outputFile + ".gdb"); + args2.push_back("-T"); + args2.push_back(tmpfile); + RealLD(args2); + if(saveLdScript) std::cerr << "Ld Script at: " << tmpfile << std::endl; else unlink(tmpfile); - Object theObject(outputFile + ".gdb"); - if(flatoutput) - theObject.FlatCode(outputFile); - else if(segments) - theObject.MultiSegmentApp(outputFile, segmentMap); - else - theObject.SingleSegmentApp(outputFile); - } - else - { - RealLD(args); - } - return 0; - } - else - { - if(argc != 2) - errx(EXIT_FAILURE, "usage : %s file-name ", argv[0]); - Object theObject(argv[1]); - SegmentMap segmentMap; - theObject.MultiSegmentApp("out.bin", segmentMap); - } - return 0; + Object theObject(outputFile + ".gdb"); + if(flatoutput) + theObject.FlatCode(outputFile); + else if(segments) + theObject.MultiSegmentApp(outputFile, segmentMap); + else + theObject.SingleSegmentApp(outputFile); + } + else + { + RealLD(args); + } + return 0; + } + else + { + if(argc != 2) + errx(EXIT_FAILURE, "usage : %s file-name ", argv[0]); + Object theObject(argv[1]); + SegmentMap segmentMap; + theObject.MultiSegmentApp("out.bin", segmentMap); + } + return 0; } diff --git a/Elf2Mac/Elf2Mac.h b/Elf2Mac/Elf2Mac.h index 3602ae139a..772e2d504f 100644 --- a/Elf2Mac/Elf2Mac.h +++ b/Elf2Mac/Elf2Mac.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef ELF2MAC_H diff --git a/Elf2Mac/LdScript.cc b/Elf2Mac/LdScript.cc index 2e551a3900..a28e584d90 100644 --- a/Elf2Mac/LdScript.cc +++ b/Elf2Mac/LdScript.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Elf2Mac.h" @@ -34,7 +34,7 @@ SECTIONS )ld"; const char * textSection = R"ld(/* ld script for Elf2Mac */ - .text : { + .text : { _stext = . ; PROVIDE(_rsrc_start = .); *(.rsrcheader) @@ -142,7 +142,7 @@ const char * scriptEnd = R"ld( * Keep them for now, they are discarded by Elf2Mac. */ /DISCARD/ : { *(.note.GNU-stack) } - /* Stabs debugging sections. */ + /* Stabs debugging sections. */ .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } .stab.excl 0 : { *(.stab.excl) } @@ -184,120 +184,120 @@ const char * scriptEnd = R"ld( void CreateFlatLdScript(std::ostream& out, string entryPoint, bool stripMacsbug) { - out << "_MULTISEG_APP = 0;\n"; - out << boost::replace_all_copy(scriptStart, "@entryPoint@", entryPoint); - if(stripMacsbug) - { - out << "\t.strippedmacsbugnames 0 (NOLOAD) : { *(.text.*.macsbug) }\n"; - out << "\t. = 0;\n"; - } - out << boost::replace_all_copy(textSection, "@entryPoint@", entryPoint) << scriptEnd; + out << "_MULTISEG_APP = 0;\n"; + out << boost::replace_all_copy(scriptStart, "@entryPoint@", entryPoint); + if(stripMacsbug) + { + out << "\t.strippedmacsbugnames 0 (NOLOAD) : { *(.text.*.macsbug) }\n"; + out << "\t. = 0;\n"; + } + out << boost::replace_all_copy(textSection, "@entryPoint@", entryPoint) << scriptEnd; } void SegmentInfo::WriteFilters(std::ostream &out, string section) { - for(string filter : filters) - { - out << " " << filter << "(" << section << ")\n"; - out << " " << filter << "(" << section << ".*)\n"; - } + for(string filter : filters) + { + out << " " << filter << "(" << section << ")\n"; + out << " " << filter << "(" << section << ".*)\n"; + } } void SegmentInfo::WriteFiltersKeep(std::ostream &out, string section) { - for(string filter : filters) - { - out << "\t\tKEEP(" << filter << "(" << section << "))\n"; - out << "\t\tKEEP(" << filter << "(" << section << ".*))\n"; - } + for(string filter : filters) + { + out << "\t\tKEEP(" << filter << "(" << section << "))\n"; + out << "\t\tKEEP(" << filter << "(" << section << ".*))\n"; + } } void SegmentInfo::CreateLdScript(std::ostream &out, string entryPoint) { - out << "\t.code" << id << " : {\n"; - out << "\t\tFILL(0x4E71);\n"; - if(id == 1) - { - out << boost::replace_all_copy(R"ld( - _stext = .; - FILL(0x4E71); - PROVIDE(_rsrc_start = .); - . = ALIGN (2); - _entry_trampoline = .; - SHORT(DEFINED(__break_on_entry) ? 0xA9FF : 0x4e71); - LONG(0x61000002); /* bsr *+2 */ - SHORT(0x0697); /* addi.l #_, (a7) */ - LONG(@entryPoint@ - _entry_trampoline - 6); - PROVIDE(_start = .); /* fallback entry point to a safe spot - needed for libretro bootstrap */ - SHORT(0x4e75); /* rts */ + out << "\t.code" << id << " : {\n"; + out << "\t\tFILL(0x4E71);\n"; + if(id == 1) + { + out << boost::replace_all_copy(R"ld( + _stext = .; + FILL(0x4E71); + PROVIDE(_rsrc_start = .); + . = ALIGN (2); + _entry_trampoline = .; + SHORT(DEFINED(__break_on_entry) ? 0xA9FF : 0x4e71); + LONG(0x61000002); /* bsr *+2 */ + SHORT(0x0697); /* addi.l #_, (a7) */ + LONG(@entryPoint@ - _entry_trampoline - 6); + PROVIDE(_start = .); /* fallback entry point to a safe spot - needed for libretro bootstrap */ + SHORT(0x4e75); /* rts */ - FILL(0); - *(.relocvars) - FILL(0x4E71); + FILL(0); + *(.relocvars) + FILL(0x4E71); )ld", "@entryPoint@", entryPoint); - } - WriteFilters(out, ".text"); + } + WriteFilters(out, ".text"); - if(id == 2) - { - out << "\t\t*(.gnu.linkonce.t*)\n"; - } - if(id == 1) - { - out << R"ld( - . = ALIGN (4) ; - __init_section = .; - KEEP (*(.init)) - __init_section_end = .; - __fini_section = .; - KEEP (*(.fini)) - __fini_section_end = .; + if(id == 2) + { + out << "\t\t*(.gnu.linkonce.t*)\n"; + } + if(id == 1) + { + out << R"ld( + . = ALIGN (4) ; + __init_section = .; + KEEP (*(.init)) + __init_section_end = .; + __fini_section = .; + KEEP (*(.fini)) + __fini_section_end = .; )ld"; - } + } - out << "\t\t. = ALIGN (4);\n"; // this is important, for some reason. - if(id == 1) - out << "\t\t__EH_FRAME_BEGIN__" << " = .;\n"; - else - out << "\t\t__EH_FRAME_BEGIN__" << id << " = .;\n"; - WriteFiltersKeep(out, ".eh_frame"); - out << "\t\tLONG(0);\n"; - WriteFiltersKeep(out, ".gcc_except_table"); + out << "\t\t. = ALIGN (4);\n"; // this is important, for some reason. + if(id == 1) + out << "\t\t__EH_FRAME_BEGIN__" << " = .;\n"; + else + out << "\t\t__EH_FRAME_BEGIN__" << id << " = .;\n"; + WriteFiltersKeep(out, ".eh_frame"); + out << "\t\tLONG(0);\n"; + WriteFiltersKeep(out, ".gcc_except_table"); - if(id == 1) - { - out << R"ld( - . = ALIGN(0x4) ; - _etext = . ; + if(id == 1) + { + out << R"ld( + . = ALIGN(0x4) ; + _etext = . ; )ld"; - } - else - { - out << boost::replace_all_copy(R"ld( - . = ALIGN(0x4); - FILL(0); - . += 32; - LONG(__EH_FRAME_BEGIN__@N@ - .); + } + else + { + out << boost::replace_all_copy(R"ld( + . = ALIGN(0x4); + FILL(0); + . += 32; + LONG(__EH_FRAME_BEGIN__@N@ - .); )ld", "@N@", boost::lexical_cast(id)); - } + } - out << "\t}\n"; + out << "\t}\n"; } void SegmentMap::CreateLdScript(std::ostream &out, string entryPoint, bool stripMacsbug) { - out << "_MULTISEG_APP = 1;\n"; - out << boost::replace_all_copy(scriptStart, "@entryPoint@", entryPoint); - if(stripMacsbug) - { - out << "\t.strippedmacsbugnames 0 (NOLOAD) : { *(.text.*.macsbug) }\n"; - out << "\t. = 0;\n"; - } - for(SegmentInfo& seg: segments) - { - seg.CreateLdScript(out, entryPoint); - } + out << "_MULTISEG_APP = 1;\n"; + out << boost::replace_all_copy(scriptStart, "@entryPoint@", entryPoint); + if(stripMacsbug) + { + out << "\t.strippedmacsbugnames 0 (NOLOAD) : { *(.text.*.macsbug) }\n"; + out << "\t. = 0;\n"; + } + for(SegmentInfo& seg: segments) + { + seg.CreateLdScript(out, entryPoint); + } - out << scriptEnd; + out << scriptEnd; } diff --git a/Elf2Mac/Object.cc b/Elf2Mac/Object.cc index 2ff4a590aa..3f48b65e42 100644 --- a/Elf2Mac/Object.cc +++ b/Elf2Mac/Object.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Object.h" @@ -52,173 +52,173 @@ Object::~Object() Object::Object(string input) { - if(elf_version ( EV_CURRENT ) == EV_NONE) - errx(EXIT_FAILURE , "ELF library initialization failed: %s", elf_errmsg( -1)); + if(elf_version ( EV_CURRENT ) == EV_NONE) + errx(EXIT_FAILURE , "ELF library initialization failed: %s", elf_errmsg( -1)); - int fd = open(input.c_str(), O_RDONLY, 0); - elf = elf_begin(fd, ELF_C_READ, NULL); + int fd = open(input.c_str(), O_RDONLY, 0); + elf = elf_begin(fd, ELF_C_READ, NULL); - elf_getshdrstrndx(elf, §ionHeaderStringTableIdx); + elf_getshdrstrndx(elf, §ionHeaderStringTableIdx); - GElf_Ehdr ehdr; - gelf_getehdr(elf, &ehdr); + GElf_Ehdr ehdr; + gelf_getehdr(elf, &ehdr); - int idx; + int idx; - idx = 1; - for(Elf_Scn *scn = NULL; (scn = elf_nextscn(elf, scn)) != NULL; idx++) - { - GElf_Shdr shdr; - gelf_getshdr(scn, &shdr); - std::string name = elf_strptr(elf, sectionHeaderStringTableIdx, shdr.sh_name); - if(shdr.sh_type == SHT_STRTAB) - { - if(name == ".strtab") - mainStringTableIdx = idx; - } - } + idx = 1; + for(Elf_Scn *scn = NULL; (scn = elf_nextscn(elf, scn)) != NULL; idx++) + { + GElf_Shdr shdr; + gelf_getshdr(scn, &shdr); + std::string name = elf_strptr(elf, sectionHeaderStringTableIdx, shdr.sh_name); + if(shdr.sh_type == SHT_STRTAB) + { + if(name == ".strtab") + mainStringTableIdx = idx; + } + } - idx = 1; - for(Elf_Scn *scn = NULL; (scn = elf_nextscn(elf, scn)) != NULL; idx++) - { - GElf_Shdr shdr; - gelf_getshdr(scn, &shdr); - std::string name = elf_strptr(elf, sectionHeaderStringTableIdx, shdr.sh_name); - //std::cout << "section #" << idx << ": " << name << std::endl; - //std::cout << " =" << shdr.sh_addr << " + " << shdr.sh_size << std::endl; + idx = 1; + for(Elf_Scn *scn = NULL; (scn = elf_nextscn(elf, scn)) != NULL; idx++) + { + GElf_Shdr shdr; + gelf_getshdr(scn, &shdr); + std::string name = elf_strptr(elf, sectionHeaderStringTableIdx, shdr.sh_name); + //std::cout << "section #" << idx << ": " << name << std::endl; + //std::cout << " =" << shdr.sh_addr << " + " << shdr.sh_size << std::endl; - if(shdr.sh_type == SHT_SYMTAB - && !symtab) - { - symtab.reset(new Symtab(*this, scn)); - } - if(shdr.sh_type == SHT_RELA) - { - if(boost::algorithm::starts_with(name,".rela.")) - { - string progbitsName = name.substr(5); - assert(sections.find(progbitsName) != sections.end()); - sections[progbitsName]->SetRela(scn); - } - } - if(shdr.sh_type == SHT_PROGBITS && (shdr.sh_flags & SHF_ALLOC)) - { - SectionKind kind = SectionKind::code; + if(shdr.sh_type == SHT_SYMTAB + && !symtab) + { + symtab.reset(new Symtab(*this, scn)); + } + if(shdr.sh_type == SHT_RELA) + { + if(boost::algorithm::starts_with(name,".rela.")) + { + string progbitsName = name.substr(5); + assert(sections.find(progbitsName) != sections.end()); + sections[progbitsName]->SetRela(scn); + } + } + if(shdr.sh_type == SHT_PROGBITS && (shdr.sh_flags & SHF_ALLOC)) + { + SectionKind kind = SectionKind::code; - if(name == ".data") - kind = SectionKind::data; - if(name == ".strippedmacsbugnames") - kind = SectionKind::undefined; + if(name == ".data") + kind = SectionKind::data; + if(name == ".strippedmacsbugnames") + kind = SectionKind::undefined; - auto section = make_shared
(*this, name, idx, kind, scn); + auto section = make_shared
(*this, name, idx, kind, scn); - sections[name] = sectionsByElfIndex[idx] = section; - if(kind == SectionKind::data) - dataSection = section; - else if(kind == SectionKind::code) - codeSections.push_back(section); - } - if(shdr.sh_type == SHT_NOBITS) - { - bssSection = sections[name] = sectionsByElfIndex[idx] = - make_shared
(*this, name, idx, SectionKind::bss, scn); - } - } + sections[name] = sectionsByElfIndex[idx] = section; + if(kind == SectionKind::data) + dataSection = section; + else if(kind == SectionKind::code) + codeSections.push_back(section); + } + if(shdr.sh_type == SHT_NOBITS) + { + bssSection = sections[name] = sectionsByElfIndex[idx] = + make_shared
(*this, name, idx, SectionKind::bss, scn); + } + } - std::sort(codeSections.begin(), codeSections.end(), - [](shared_ptr
a, shared_ptr
b) { return a->name < b->name; }); + std::sort(codeSections.begin(), codeSections.end(), + [](shared_ptr
a, shared_ptr
b) { return a->name < b->name; }); } void Object::FlatCode(std::ostream& out) { - for(auto sec : codeSections) - { - sec->FixRelocs(true); - out << sec->GetData(); - } - - dataSection->FixRelocs(true); - out << dataSection->GetData(); + for(auto sec : codeSections) + { + sec->FixRelocs(true); + out << sec->GetData(); + } + + dataSection->FixRelocs(true); + out << dataSection->GetData(); - std::vector relocs; - for(auto sec : codeSections) - { - auto tmp = sec->GetRelocations(false); - relocs.insert(relocs.end(), tmp.begin(), tmp.end()); - } - { - auto tmp = dataSection->GetRelocations(false); - relocs.insert(relocs.end(), tmp.begin(), tmp.end()); - } - out << SerializeRelocs(relocs); + std::vector relocs; + for(auto sec : codeSections) + { + auto tmp = sec->GetRelocations(false); + relocs.insert(relocs.end(), tmp.begin(), tmp.end()); + } + { + auto tmp = dataSection->GetRelocations(false); + relocs.insert(relocs.end(), tmp.begin(), tmp.end()); + } + out << SerializeRelocs(relocs); } void Object::FlatCode(string fn) { - ofstream out(fn); - FlatCode(out); + ofstream out(fn); + FlatCode(out); } std::string fromhex(std::string hex) { - std::string bin; - int nibble; - bool haveNibble = false; - for(std::string::iterator p = hex.begin(); p != hex.end(); ++p) - { - if(std::isspace(*p)) - continue; - assert(isdigit(*p) || (tolower(*p) >= 'a' && tolower(*p) <= 'f')); - int digit; - if(isdigit(*p)) - digit = *p - '0'; - else - digit = tolower(*p) - 'a' + 0xA; + std::string bin; + int nibble; + bool haveNibble = false; + for(std::string::iterator p = hex.begin(); p != hex.end(); ++p) + { + if(std::isspace(*p)) + continue; + assert(isdigit(*p) || (tolower(*p) >= 'a' && tolower(*p) <= 'f')); + int digit; + if(isdigit(*p)) + digit = *p - '0'; + else + digit = tolower(*p) - 'a' + 0xA; - if(haveNibble) - { - bin += (char) ((nibble << 4) | digit); - haveNibble = false; - } - else - { - nibble = digit; - haveNibble = true; - } - } - return bin; + if(haveNibble) + { + bin += (char) ((nibble << 4) | digit); + haveNibble = false; + } + else + { + nibble = digit; + haveNibble = true; + } + } + return bin; } void Object::SingleSegmentApp(string output) { - ResourceFile file(output); - Resources& rsrc = file.resources; + ResourceFile file(output); + Resources& rsrc = file.resources; - rsrc.addResource(Resource(ResType("CODE"), 0, - fromhex( - "00000028 00000000 00000008 00000020" - "0000 3F3C 0001 A9F0" - ) - )); + rsrc.addResource(Resource(ResType("CODE"), 0, + fromhex( + "00000028 00000000 00000008 00000020" + "0000 3F3C 0001 A9F0" + ) + )); - { - std::ostringstream code1; - word(code1, 0); - word(code1, 1); - FlatCode(code1); + { + std::ostringstream code1; + word(code1, 0); + word(code1, 1); + FlatCode(code1); - rsrc.addResource(Resource(ResType("CODE"), 1, - code1.str())); - } + rsrc.addResource(Resource(ResType("CODE"), 1, + code1.str())); + } - file.creator = ResType("????"); - file.type = ResType("APPL"); + file.creator = ResType("????"); + file.type = ResType("APPL"); - file.write(); + file.write(); } @@ -227,70 +227,70 @@ void Object::MultiSegmentApp(string output, SegmentMap& segmentMap) { bool noisy = false; - ResourceFile file(output); - Resources& rsrc = file.resources; + ResourceFile file(output); + Resources& rsrc = file.resources; - for(auto namedSec : sections) - { - namedSec.second->ScanRelocs(); - } + for(auto namedSec : sections) + { + namedSec.second->ScanRelocs(); + } - int jtEntryCount = 0; - unordered_map> jtEntries; - for(Symbol& sym : symtab->symbols) - { - if(sym.valid) - { - if(sym.referencedExternally && sym.sectionKind == SectionKind::code) - { - sym.needsJT = true; - sym.jtIndex = -1; - sym.section->jtEntries.push_back(&sym); - ++jtEntryCount; - } - } - } + int jtEntryCount = 0; + unordered_map> jtEntries; + for(Symbol& sym : symtab->symbols) + { + if(sym.valid) + { + if(sym.referencedExternally && sym.sectionKind == SectionKind::code) + { + sym.needsJT = true; + sym.jtIndex = -1; + sym.section->jtEntries.push_back(&sym); + ++jtEntryCount; + } + } + } - uint32_t data_and_bss_size = dataSection->shdr.sh_size + bssSection->shdr.sh_size; + uint32_t data_and_bss_size = dataSection->shdr.sh_size + bssSection->shdr.sh_size; - { - std::ostringstream code0; - longword(code0, 0x20 + 8 * (jtEntryCount+2)); - longword(code0, data_and_bss_size); - longword(code0, 8 * (jtEntryCount+2)); - longword(code0, 0x20); + { + std::ostringstream code0; + longword(code0, 0x20 + 8 * (jtEntryCount+2)); + longword(code0, data_and_bss_size); + longword(code0, 8 * (jtEntryCount+2)); + longword(code0, 0x20); - code0 << fromhex("0000 3F3C 0001 A9F0"); // jt entry for entrypoint - code0 << fromhex("0000 FFFF 0000 0000"); // 32-bit entries start from here + code0 << fromhex("0000 3F3C 0001 A9F0"); // jt entry for entrypoint + code0 << fromhex("0000 FFFF 0000 0000"); // 32-bit entries start from here - int jtIndex = 2; - int id = 1; - for(auto sec : codeSections) - { - sec->codeID = id; + int jtIndex = 2; + int id = 1; + for(auto sec : codeSections) + { + sec->codeID = id; - sec->firstJTEntryIndex = jtIndex; + sec->firstJTEntryIndex = jtIndex; - GElf_Shdr &shdr = sec->shdr; + GElf_Shdr &shdr = sec->shdr; - for(Symbol* jtEntry : sec->jtEntries) - { - word(code0, id); - word(code0, 0xA9F0); - uint32_t offset = jtEntry->st_value - shdr.sh_addr; - if(id == 1) - offset += 4; - else - offset += 40; - longword(code0, offset); + for(Symbol* jtEntry : sec->jtEntries) + { + word(code0, id); + word(code0, 0xA9F0); + uint32_t offset = jtEntry->st_value - shdr.sh_addr; + if(id == 1) + offset += 4; + else + offset += 40; + longword(code0, offset); - jtEntry->jtIndex = jtIndex++; + jtEntry->jtIndex = jtIndex++; - //std::cout << "JT Entry " << jtEntry->jtIndex << ": " << jtEntry->name << std::endl; - } + //std::cout << "JT Entry " << jtEntry->jtIndex << ": " << jtEntry->name << std::endl; + } - id++; - } + id++; + } if(noisy) { @@ -302,69 +302,69 @@ void Object::MultiSegmentApp(string output, SegmentMap& segmentMap) std::cout << ".bss: " << bssSection->shdr.sh_size << " bytes at A5-" << std::hex << bssSection->shdr.sh_size << std::dec << "\n"; } - rsrc.addResource(Resource(ResType("CODE"), 0, code0.str())); - } + rsrc.addResource(Resource(ResType("CODE"), 0, code0.str())); + } - for(auto sec : codeSections) - { - int id = sec->codeID; - if(id == 1) - sec->outputBase = 4; // standard 'CODE' header - else - sec->outputBase = 40; // far-model 'CODE' header + for(auto sec : codeSections) + { + int id = sec->codeID; + if(id == 1) + sec->outputBase = 4; // standard 'CODE' header + else + sec->outputBase = 40; // far-model 'CODE' header - string exceptionInfoMarker = "__EH_FRAME_BEGIN__"; - if(id != 1) - exceptionInfoMarker += boost::lexical_cast(id); - int exceptionInfoSym = symtab->FindSym(exceptionInfoMarker); - if(exceptionInfoSym != -1) - { - Symbol& s = symtab->GetSym(exceptionInfoSym); - sec->exceptionInfoStart = s.st_value; + string exceptionInfoMarker = "__EH_FRAME_BEGIN__"; + if(id != 1) + exceptionInfoMarker += boost::lexical_cast(id); + int exceptionInfoSym = symtab->FindSym(exceptionInfoMarker); + if(exceptionInfoSym != -1) + { + Symbol& s = symtab->GetSym(exceptionInfoSym); + sec->exceptionInfoStart = s.st_value; - int codeSize = sec->shdr.sh_size; - int exceptionSize = sec->shdr.sh_addr + codeSize - sec->exceptionInfoStart; - double percent = 100.0 * exceptionSize / codeSize; + int codeSize = sec->shdr.sh_size; + int exceptionSize = sec->shdr.sh_addr + codeSize - sec->exceptionInfoStart; + double percent = 100.0 * exceptionSize / codeSize; - if(noisy) + if(noisy) std::cout << "CODE " << id << " has " << exceptionSize << " bytes of exception info (" << percent << "%)\n"; - } - else if(noisy) - std::cout << "exception info marker not found: " << exceptionInfoMarker << std::endl; - } - dataSection->outputBase = -data_and_bss_size; - bssSection->outputBase = -bssSection->shdr.sh_size; + } + else if(noisy) + std::cout << "exception info marker not found: " << exceptionInfoMarker << std::endl; + } + dataSection->outputBase = -data_and_bss_size; + bssSection->outputBase = -bssSection->shdr.sh_size; - for(auto namedSec : sections) - { - namedSec.second->FixRelocs(false); - } + for(auto namedSec : sections) + { + namedSec.second->FixRelocs(false); + } - for(auto sec : codeSections) - { - int id = sec->codeID; - std::ostringstream code; - if(id == 1) - { - word(code, 0); - word(code, 1); - } - else - { - word(code, 0xFFFF); - word(code, 0); - longword(code, 0); - longword(code, 0); - longword(code, 8 * sec->firstJTEntryIndex ); - longword(code, sec->jtEntries.size()); - longword(code, 0); // reloc info for A5 - longword(code, 0); // assumed address for A5 - longword(code, 0); // reloc info for code - longword(code, 0); // assumed address for start of code resource - longword(code, 0); - } - code << sec->GetData(); + for(auto sec : codeSections) + { + int id = sec->codeID; + std::ostringstream code; + if(id == 1) + { + word(code, 0); + word(code, 1); + } + else + { + word(code, 0xFFFF); + word(code, 0); + longword(code, 0); + longword(code, 0); + longword(code, 8 * sec->firstJTEntryIndex ); + longword(code, sec->jtEntries.size()); + longword(code, 0); // reloc info for A5 + longword(code, 0); // assumed address for A5 + longword(code, 0); // reloc info for code + longword(code, 0); // assumed address for start of code resource + longword(code, 0); + } + code << sec->GetData(); if(noisy) { @@ -377,24 +377,24 @@ void Object::MultiSegmentApp(string output, SegmentMap& segmentMap) } } - string segmentName = segmentMap.GetSegmentName(id); + string segmentName = segmentMap.GetSegmentName(id); - rsrc.addResource(Resource(ResType("CODE"), id, - code.str(), - segmentName)); + rsrc.addResource(Resource(ResType("CODE"), id, + code.str(), + segmentName)); - rsrc.addResource(Resource(ResType("RELA"),id, SerializeRelocs(sec->GetRelocations(true)))); - } + rsrc.addResource(Resource(ResType("RELA"),id, SerializeRelocs(sec->GetRelocations(true)))); + } - rsrc.addResource(Resource(ResType("DATA"),0, dataSection->GetData())); - rsrc.addResource(Resource(ResType("RELA"),0, SerializeRelocs(dataSection->GetRelocations(true)))); + rsrc.addResource(Resource(ResType("DATA"),0, dataSection->GetData())); + rsrc.addResource(Resource(ResType("RELA"),0, SerializeRelocs(dataSection->GetRelocations(true)))); if(noisy) - std::cout << "DATA 0: " << dataSection->shdr.sh_size << " bytes\n"; + std::cout << "DATA 0: " << dataSection->shdr.sh_size << " bytes\n"; - file.creator = ResType("????"); - file.type = ResType("APPL"); + file.creator = ResType("????"); + file.type = ResType("APPL"); - file.write(); + file.write(); } diff --git a/Elf2Mac/Object.h b/Elf2Mac/Object.h index 43d7df0096..4802c90d1f 100644 --- a/Elf2Mac/Object.h +++ b/Elf2Mac/Object.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef OBJECT_H @@ -36,25 +36,25 @@ class SegmentMap; class Object { public: - Elf *elf; - std::unique_ptr symtab; - std::unordered_map> sections; - std::unordered_map> sectionsByElfIndex; + Elf *elf; + std::unique_ptr symtab; + std::unordered_map> sections; + std::unordered_map> sectionsByElfIndex; - std::vector> codeSections; - std::shared_ptr
dataSection, bssSection; - size_t sectionHeaderStringTableIdx; - size_t mainStringTableIdx; + std::vector> codeSections; + std::shared_ptr
dataSection, bssSection; + size_t sectionHeaderStringTableIdx; + size_t mainStringTableIdx; - Object(std::string input); - ~Object(); + Object(std::string input); + ~Object(); - void FlatCode(std::ostream& out); - void FlatCode(std::string fn); + void FlatCode(std::ostream& out); + void FlatCode(std::string fn); - void SingleSegmentApp(std::string output); - void MultiSegmentApp(std::string output, SegmentMap &segmentMap); + void SingleSegmentApp(std::string output); + void MultiSegmentApp(std::string output, SegmentMap &segmentMap); }; diff --git a/Elf2Mac/Reloc.cc b/Elf2Mac/Reloc.cc index 4848b01ac7..2e30606ac8 100644 --- a/Elf2Mac/Reloc.cc +++ b/Elf2Mac/Reloc.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Reloc.h" @@ -32,38 +32,38 @@ Reloc::Reloc(const GElf_Rela &rela) std::string SerializeRelocsUncompressed(std::vector relocs) { - std::ostringstream out; - for(const auto& r : relocs) - { - longword(out, r.offset | ((int)r.base << 24)); - } - longword(out, -1); - return out.str(); + std::ostringstream out; + for(const auto& r : relocs) + { + longword(out, r.offset | ((int)r.base << 24)); + } + longword(out, -1); + return out.str(); } std::string SerializeRelocs(std::vector relocs) { - std::ostringstream out; - uint32_t offset = -1; + std::ostringstream out; + uint32_t offset = -1; - for(const auto& r : relocs) - { - uint32_t delta = r.offset - offset; - offset = r.offset; + for(const auto& r : relocs) + { + uint32_t delta = r.offset - offset; + offset = r.offset; - uint32_t base = (uint32_t) r.base; + uint32_t base = (uint32_t) r.base; - uint32_t encoded = (delta << 2) | base; + uint32_t encoded = (delta << 2) | base; - while(encoded >= 128) - { - byte(out, (encoded & 0x7F) | 0x80); - encoded >>= 7; - } - byte(out, encoded); - } + while(encoded >= 128) + { + byte(out, (encoded & 0x7F) | 0x80); + encoded >>= 7; + } + byte(out, encoded); + } - byte(out, 0); + byte(out, 0); - return out.str(); + return out.str(); } diff --git a/Elf2Mac/Reloc.h b/Elf2Mac/Reloc.h index d3fd4ad9cc..9448661655 100644 --- a/Elf2Mac/Reloc.h +++ b/Elf2Mac/Reloc.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef RELOC_H @@ -28,30 +28,30 @@ enum class RelocBase { - code = 0, - data, - bss, - jumptable, - code1 + code = 0, + data, + bss, + jumptable, + code1 }; class Reloc : public GElf_Rela { public: - RelocBase relocBase; + RelocBase relocBase; - Reloc(); - Reloc(const GElf_Rela& rela); + Reloc(); + Reloc(const GElf_Rela& rela); }; class RuntimeReloc { public: - RelocBase base; - uint32_t offset; + RelocBase base; + uint32_t offset; - RuntimeReloc() : base(RelocBase::code), offset(0) {} - RuntimeReloc(RelocBase b, uint32_t o) : base(b), offset(o) {} + RuntimeReloc() : base(RelocBase::code), offset(0) {} + RuntimeReloc(RelocBase b, uint32_t o) : base(b), offset(o) {} }; std::string SerializeRelocsUncompressed(std::vector relocs); diff --git a/Elf2Mac/Section.cc b/Elf2Mac/Section.cc index 10bb06c807..c05cf2a915 100644 --- a/Elf2Mac/Section.cc +++ b/Elf2Mac/Section.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Section.h" @@ -43,198 +43,198 @@ Section::Section(Object& theObject, string name, int idx, SectionKind kind, Elf_ exceptionInfoStart(0), codeID(-1), firstJTEntryIndex(0) { - data = elf_getdata(elfsec, NULL); - gelf_getshdr(elfsec, &shdr); - outputBase = shdr.sh_addr; + data = elf_getdata(elfsec, NULL); + gelf_getshdr(elfsec, &shdr); + outputBase = shdr.sh_addr; } void Section::SetRela(Elf_Scn *scn) { - relasec = scn; - GElf_Shdr rshdr; - gelf_getshdr(relasec, &rshdr); + relasec = scn; + GElf_Shdr rshdr; + gelf_getshdr(relasec, &rshdr); - int nRela = rshdr.sh_size / rshdr.sh_entsize; - Elf_Data *data = elf_getdata(relasec, NULL); - for(int i = 0; i < nRela; i++) - { - GElf_Rela rela; - gelf_getrela(data, i, &rela); + int nRela = rshdr.sh_size / rshdr.sh_entsize; + Elf_Data *data = elf_getdata(relasec, NULL); + for(int i = 0; i < nRela; i++) + { + GElf_Rela rela; + gelf_getrela(data, i, &rela); - if(rela.r_offset < shdr.sh_addr || rela.r_offset > shdr.sh_addr + shdr.sh_size - 4) - { - // FIXME: There are sometimes relocations beyond the end of the sections - // in LD output for some reason. That's bad. Let's ignore it. - continue; - } - relocs.push_back(rela); - } + if(rela.r_offset < shdr.sh_addr || rela.r_offset > shdr.sh_addr + shdr.sh_size - 4) + { + // FIXME: There are sometimes relocations beyond the end of the sections + // in LD output for some reason. That's bad. Let's ignore it. + continue; + } + relocs.push_back(rela); + } - std::sort(relocs.begin(), relocs.end(), - [](GElf_Rela& a, GElf_Rela& b) { return a.r_offset < b.r_offset; }); + std::sort(relocs.begin(), relocs.end(), + [](GElf_Rela& a, GElf_Rela& b) { return a.r_offset < b.r_offset; }); } uint32_t Section::GetSize() { - return data->d_size; + return data->d_size; } string Section::GetData() { - return string((char*)data->d_buf, (char*)data->d_buf + data->d_size); + return string((char*)data->d_buf, (char*)data->d_buf + data->d_size); } std::vector Section::GetRelocations(bool useOffsets) { - std::vector outRelocs; + std::vector outRelocs; - for(auto& rela : relocs) - { - //printf("rel: %d %d %x %x\n", (int)GELF_R_TYPE(rela.r_info), (int)GELF_R_SYM(rela.r_info), (unsigned)rela.r_addend, (unsigned)rela.r_offset); + for(auto& rela : relocs) + { + //printf("rel: %d %d %x %x\n", (int)GELF_R_TYPE(rela.r_info), (int)GELF_R_SYM(rela.r_info), (unsigned)rela.r_addend, (unsigned)rela.r_offset); - int symidx = GELF_R_SYM(rela.r_info); - if(symidx == 0) - continue; + int symidx = GELF_R_SYM(rela.r_info); + if(symidx == 0) + continue; - Symbol& sym = theObject.symtab->GetSym(symidx); + Symbol& sym = theObject.symtab->GetSym(symidx); - if(sym.st_shndx == SHN_UNDEF || sym.st_shndx >= SHN_LORESERVE) - continue; - if(sym.sectionKind == SectionKind::undefined) - continue; + if(sym.st_shndx == SHN_UNDEF || sym.st_shndx >= SHN_LORESERVE) + continue; + if(sym.sectionKind == SectionKind::undefined) + continue; - if(GELF_R_TYPE(rela.r_info) == R_68K_32) - { - assert(sym.sectionKind != SectionKind::undefined); + if(GELF_R_TYPE(rela.r_info) == R_68K_32) + { + assert(sym.sectionKind != SectionKind::undefined); - uint32_t offset = rela.r_offset; - if(useOffsets) - offset -= shdr.sh_addr; + uint32_t offset = rela.r_offset; + if(useOffsets) + offset -= shdr.sh_addr; - //longword(out, offset | ((int)rela.relocBase << 24)); - outRelocs.emplace_back(rela.relocBase, offset); - } - } + //longword(out, offset | ((int)rela.relocBase << 24)); + outRelocs.emplace_back(rela.relocBase, offset); + } + } - return outRelocs; + return outRelocs; } void Section::ScanRelocs() { - for(Reloc& rela : relocs) - { - int symidx = GELF_R_SYM(rela.r_info); - if(symidx == 0) - continue; + for(Reloc& rela : relocs) + { + int symidx = GELF_R_SYM(rela.r_info); + if(symidx == 0) + continue; - Symbol *sym = &theObject.symtab->GetSym(symidx); + Symbol *sym = &theObject.symtab->GetSym(symidx); - if(sym->st_shndx == SHN_UNDEF) - continue; + if(sym->st_shndx == SHN_UNDEF) + continue; - if(rela.r_addend != 0) - { - int symidx2 = theObject.symtab->FindSym(sym->st_shndx, sym->st_value + rela.r_addend); - if(symidx2 != -1) - { - sym = &theObject.symtab->GetSym(symidx2); - rela.r_addend = 0; - rela.r_info = GELF_R_INFO(symidx2, GELF_R_TYPE(rela.r_info)); + if(rela.r_addend != 0) + { + int symidx2 = theObject.symtab->FindSym(sym->st_shndx, sym->st_value + rela.r_addend); + if(symidx2 != -1) + { + sym = &theObject.symtab->GetSym(symidx2); + rela.r_addend = 0; + rela.r_info = GELF_R_INFO(symidx2, GELF_R_TYPE(rela.r_info)); - } - } + } + } - if(sym->st_shndx != idx) - sym->referencedExternally = true; - } + if(sym->st_shndx != idx) + sym->referencedExternally = true; + } } void Section::FixRelocs(bool allowDirectCodeRefs) { - for(Reloc& rela : relocs) - { - if(GELF_R_TYPE(rela.r_info) != R_68K_32) - continue; + for(Reloc& rela : relocs) + { + if(GELF_R_TYPE(rela.r_info) != R_68K_32) + continue; - int symidx = GELF_R_SYM(rela.r_info); - if(symidx == 0) - continue; - Symbol& sym = theObject.symtab->GetSym(symidx); + int symidx = GELF_R_SYM(rela.r_info); + if(symidx == 0) + continue; + Symbol& sym = theObject.symtab->GetSym(symidx); - if(sym.sectionKind == SectionKind::undefined) - continue; + if(sym.sectionKind == SectionKind::undefined) + continue; - RelocBase relocBase; - switch(sym.sectionKind) - { - case SectionKind::code: - relocBase = RelocBase::code; - if(sym.needsJT && (exceptionInfoStart == 0 || rela.r_offset < exceptionInfoStart || sym.name == "__gxx_personality_v0")) - { - if(rela.r_addend == 0) - { - relocBase = RelocBase::jumptable; - } - else - { - if(sym.section.get() != this) - { - std::cerr << "Invalid ref from " - << name << ":" << std::hex << rela.r_offset-shdr.sh_addr << std::dec - << " to " << sym.section->name - << "(" << sym.name << ")" - << "+" << rela.r_offset << std::endl; - } - assert(sym.section.get() == this); - } - } - else if(!allowDirectCodeRefs) - { - if(sym.section.get() != this) - { - std::cerr << "Invalid ref from " - << name << ":" << std::hex << rela.r_offset-shdr.sh_addr << std::dec - << " to " << sym.section->name - << "(" << sym.name << ")" - << "+" << rela.r_offset << std::endl; - std::cerr << "needsJT: " << (sym.needsJT ? "true" : "false") << std::endl; - std::cerr << "from addr: " << rela.r_offset << ", exceptionInfoStart: " << exceptionInfoStart << std::endl; + RelocBase relocBase; + switch(sym.sectionKind) + { + case SectionKind::code: + relocBase = RelocBase::code; + if(sym.needsJT && (exceptionInfoStart == 0 || rela.r_offset < exceptionInfoStart || sym.name == "__gxx_personality_v0")) + { + if(rela.r_addend == 0) + { + relocBase = RelocBase::jumptable; + } + else + { + if(sym.section.get() != this) + { + std::cerr << "Invalid ref from " + << name << ":" << std::hex << rela.r_offset-shdr.sh_addr << std::dec + << " to " << sym.section->name + << "(" << sym.name << ")" + << "+" << rela.r_offset << std::endl; + } + assert(sym.section.get() == this); + } + } + else if(!allowDirectCodeRefs) + { + if(sym.section.get() != this) + { + std::cerr << "Invalid ref from " + << name << ":" << std::hex << rela.r_offset-shdr.sh_addr << std::dec + << " to " << sym.section->name + << "(" << sym.name << ")" + << "+" << rela.r_offset << std::endl; + std::cerr << "needsJT: " << (sym.needsJT ? "true" : "false") << std::endl; + std::cerr << "from addr: " << rela.r_offset << ", exceptionInfoStart: " << exceptionInfoStart << std::endl; - } - assert(sym.section.get() == this); - } - break; - case SectionKind::data: - relocBase = RelocBase::data; - break; - case SectionKind::bss: - relocBase = RelocBase::bss; - break; - case SectionKind::undefined: - assert(false); - break; - } - rela.relocBase = relocBase; + } + assert(sym.section.get() == this); + } + break; + case SectionKind::data: + relocBase = RelocBase::data; + break; + case SectionKind::bss: + relocBase = RelocBase::bss; + break; + case SectionKind::undefined: + assert(false); + break; + } + rela.relocBase = relocBase; - uint8_t *relocand = ((uint8_t*) data->d_buf + rela.r_offset - shdr.sh_addr); + uint8_t *relocand = ((uint8_t*) data->d_buf + rela.r_offset - shdr.sh_addr); - if(relocBase == RelocBase::jumptable) - { - uint32_t dst = 0x20 + sym.jtIndex * 8 + 2; - relocand[0] = dst >> 24; - relocand[1] = dst >> 16; - relocand[2] = dst >> 8; - relocand[3] = dst; - } - else - { - uint32_t orig = (relocand[0] << 24) | (relocand[1] << 16) | (relocand[2] << 8) | relocand[3]; - uint32_t dst = orig + sym.section->outputBase - sym.section->shdr.sh_addr; - relocand[0] = dst >> 24; - relocand[1] = dst >> 16; - relocand[2] = dst >> 8; - relocand[3] = dst; - } - } + if(relocBase == RelocBase::jumptable) + { + uint32_t dst = 0x20 + sym.jtIndex * 8 + 2; + relocand[0] = dst >> 24; + relocand[1] = dst >> 16; + relocand[2] = dst >> 8; + relocand[3] = dst; + } + else + { + uint32_t orig = (relocand[0] << 24) | (relocand[1] << 16) | (relocand[2] << 8) | relocand[3]; + uint32_t dst = orig + sym.section->outputBase - sym.section->shdr.sh_addr; + relocand[0] = dst >> 24; + relocand[1] = dst >> 16; + relocand[2] = dst >> 8; + relocand[3] = dst; + } + } } diff --git a/Elf2Mac/Section.h b/Elf2Mac/Section.h index c1a12f1b77..fae008b8dd 100644 --- a/Elf2Mac/Section.h +++ b/Elf2Mac/Section.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef SECTION_H @@ -33,41 +33,41 @@ class RuntimeReloc; enum class SectionKind { - undefined = -1, - code = 0, - data, - bss + undefined = -1, + code = 0, + data, + bss }; class Section { public: - Object& theObject; - std::string name; - int idx; - SectionKind kind; - Elf_Scn *elfsec, *relasec; - Elf_Data *data; - GElf_Shdr shdr; - uint32_t outputBase; - uint32_t exceptionInfoStart; + Object& theObject; + std::string name; + int idx; + SectionKind kind; + Elf_Scn *elfsec, *relasec; + Elf_Data *data; + GElf_Shdr shdr; + uint32_t outputBase; + uint32_t exceptionInfoStart; - int codeID; + int codeID; - std::vector relocs; - std::vector jtEntries; - int firstJTEntryIndex; + std::vector relocs; + std::vector jtEntries; + int firstJTEntryIndex; - Section(Object& object, std::string name, int idx, SectionKind kind, Elf_Scn *elfsec); - ~Section(); - void SetRela(Elf_Scn *scn); + Section(Object& object, std::string name, int idx, SectionKind kind, Elf_Scn *elfsec); + ~Section(); + void SetRela(Elf_Scn *scn); - uint32_t GetSize(); - std::string GetData(); - std::vector GetRelocations(bool useOffsets); + uint32_t GetSize(); + std::string GetData(); + std::vector GetRelocations(bool useOffsets); - void ScanRelocs(); - void FixRelocs(bool allowDirectCodeRefs); + void ScanRelocs(); + void FixRelocs(bool allowDirectCodeRefs); }; diff --git a/Elf2Mac/SegmentMap.cc b/Elf2Mac/SegmentMap.cc index 0c627edaa3..7c102ec2bc 100644 --- a/Elf2Mac/SegmentMap.cc +++ b/Elf2Mac/SegmentMap.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "SegmentMap.h" @@ -29,98 +29,98 @@ SegmentInfo::SegmentInfo() SegmentMap::SegmentMap() { - segments.emplace_back(1, "Runtime", - "*/libretrocrt.a:start.c.obj", - "*/libretrocrt.a:relocate.c.obj", - "*/libretrocrt.a:MultiSegApp.c.obj", - "*/libretrocrt.a:LoadSeg.s.obj", - "*/libretrocrt.a:*", + segments.emplace_back(1, "Runtime", + "*/libretrocrt.a:start.c.obj", + "*/libretrocrt.a:relocate.c.obj", + "*/libretrocrt.a:MultiSegApp.c.obj", + "*/libretrocrt.a:LoadSeg.s.obj", + "*/libretrocrt.a:*", "*/libInterface.a:*", - "*/libgcc.a:*", - "*/libc.a:*" - ); - segments.emplace_back(5, "libstdc++ locale", - "*/libstdc++.a:locale.o", - "*/libstdc++.a:locale_faces.o", - "*/libstdc++.a:locale_init.o"); - segments.emplace_back(7, "libstdc++ locale-inst", - "*/libstdc++.a:locale-inst.o"); - segments.emplace_back(8, "libstdc++ wlocale-inst", - "*/libstdc++.a:wlocale-inst.o"); - segments.emplace_back(6, "libstdc++ cp-demangle", - "*/libstdc++.a:cp-demangle.o"); - segments.emplace_back(3, "libstdc++", - "*/libstdc++.a:*"); - segments.emplace_back(4, "RetroConsole", - "*/libRetroConsole.a:*"); + "*/libgcc.a:*", + "*/libc.a:*" + ); + segments.emplace_back(5, "libstdc++ locale", + "*/libstdc++.a:locale.o", + "*/libstdc++.a:locale_faces.o", + "*/libstdc++.a:locale_init.o"); + segments.emplace_back(7, "libstdc++ locale-inst", + "*/libstdc++.a:locale-inst.o"); + segments.emplace_back(8, "libstdc++ wlocale-inst", + "*/libstdc++.a:wlocale-inst.o"); + segments.emplace_back(6, "libstdc++ cp-demangle", + "*/libstdc++.a:cp-demangle.o"); + segments.emplace_back(3, "libstdc++", + "*/libstdc++.a:*"); + segments.emplace_back(4, "RetroConsole", + "*/libRetroConsole.a:*"); - segments.emplace_back(2, "Main", - "*"); + segments.emplace_back(2, "Main", + "*"); } SegmentMap::SegmentMap(std::string filename) { - segments.emplace_back(1, "Runtime", - "*/libretrocrt.a:start.c.obj", - "*/libretrocrt.a:relocate.c.obj", - "*/libretrocrt.a:MultiSegApp.c.obj", - "*/libretrocrt.a:LoadSeg.s.obj", - "*/libretrocrt.a:*", + segments.emplace_back(1, "Runtime", + "*/libretrocrt.a:start.c.obj", + "*/libretrocrt.a:relocate.c.obj", + "*/libretrocrt.a:MultiSegApp.c.obj", + "*/libretrocrt.a:LoadSeg.s.obj", + "*/libretrocrt.a:*", "*/libInterface.a:*", - "*/libgcc.a:*", - "*/libc.a:*" - ); + "*/libgcc.a:*", + "*/libc.a:*" + ); - std::ifstream in(filename); - int id = -1; - int nextID = 3; - while(in) - { - std::string s; - in >> std::ws; - std::getline(in, s); - //std::cout << "segs: " << s << std::endl; - if(!in) - break; + std::ifstream in(filename); + int id = -1; + int nextID = 3; + while(in) + { + std::string s; + in >> std::ws; + std::getline(in, s); + //std::cout << "segs: " << s << std::endl; + if(!in) + break; - std::string upper; - std::transform(s.begin(), s.end(), std::back_inserter(upper), [](char c) { return std::toupper(c); }); + std::string upper; + std::transform(s.begin(), s.end(), std::back_inserter(upper), [](char c) { return std::toupper(c); }); - if(s[0] == '#') - continue; - else if(upper == "SEGMENT" || (upper.substr(0,7) == "SEGMENT" && std::isspace(upper[7]))) - { - std::string name; + if(s[0] == '#') + continue; + else if(upper == "SEGMENT" || (upper.substr(0,7) == "SEGMENT" && std::isspace(upper[7]))) + { + std::string name; - auto p = s.begin() + 7; - while(p != s.end() && std::isspace(*p)) - ++p; - name = std::string(p, s.end()); - id = nextID++; + auto p = s.begin() + 7; + while(p != s.end() && std::isspace(*p)) + ++p; + name = std::string(p, s.end()); + id = nextID++; - segments.emplace_back(id, name); - } - else - { - if(id < 0) - { - throw std::runtime_error("missing SEGMENT directive.\n"); - } + segments.emplace_back(id, name); + } + else + { + if(id < 0) + { + throw std::runtime_error("missing SEGMENT directive.\n"); + } - segments.back().filters.push_back(s); - } - } + segments.back().filters.push_back(s); + } + } - segments.emplace_back(2, "Main", - "*"); + segments.emplace_back(2, "Main", + "*"); } std::string SegmentMap::GetSegmentName(int id) { - for(auto& seg : segments) - { - if(seg.id == id) - return seg.name; - } - return ""; + for(auto& seg : segments) + { + if(seg.id == id) + return seg.name; + } + return ""; } diff --git a/Elf2Mac/SegmentMap.h b/Elf2Mac/SegmentMap.h index 4e4e21b3ad..8b78a813e9 100644 --- a/Elf2Mac/SegmentMap.h +++ b/Elf2Mac/SegmentMap.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef SEGMENTMAP_H @@ -26,31 +26,31 @@ class SegmentInfo { public: - int id; - std::string name; - std::vector filters; - SegmentInfo(); + int id; + std::string name; + std::vector filters; + SegmentInfo(); - template - SegmentInfo(int id, std::string name, Args... args) - : id(id), name(name), filters { args... } - { - } + template + SegmentInfo(int id, std::string name, Args... args) + : id(id), name(name), filters { args... } + { + } - void WriteFilters(std::ostream& out, std::string section); - void WriteFiltersKeep(std::ostream& out, std::string section); - void CreateLdScript(std::ostream& out, std::string entryPoint); + void WriteFilters(std::ostream& out, std::string section); + void WriteFiltersKeep(std::ostream& out, std::string section); + void CreateLdScript(std::ostream& out, std::string entryPoint); }; class SegmentMap { - std::vector segments; + std::vector segments; public: - SegmentMap(); - SegmentMap(std::string filename); + SegmentMap(); + SegmentMap(std::string filename); - void CreateLdScript(std::ostream& out, std::string entryPoint, bool stripMacsbug); - std::string GetSegmentName(int id); + void CreateLdScript(std::ostream& out, std::string entryPoint, bool stripMacsbug); + std::string GetSegmentName(int id); }; #endif // SEGMENTMAP_H diff --git a/Elf2Mac/Symbol.cc b/Elf2Mac/Symbol.cc index b9a3e58455..ada272472a 100644 --- a/Elf2Mac/Symbol.cc +++ b/Elf2Mac/Symbol.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Symbol.h" @@ -33,13 +33,13 @@ Symbol::Symbol(Object& theObject, const GElf_Sym &sym) sectionKind(SectionKind::undefined), needsJT(false) { - if(st_shndx != SHN_UNDEF && st_shndx < SHN_LORESERVE) - { - section = theObject.sectionsByElfIndex[st_shndx]; - sectionKind = section->kind; - } - if(st_name) - { - name = elf_strptr(theObject.elf, theObject.mainStringTableIdx, st_name); - } + if(st_shndx != SHN_UNDEF && st_shndx < SHN_LORESERVE) + { + section = theObject.sectionsByElfIndex[st_shndx]; + sectionKind = section->kind; + } + if(st_name) + { + name = elf_strptr(theObject.elf, theObject.mainStringTableIdx, st_name); + } } diff --git a/Elf2Mac/Symbol.h b/Elf2Mac/Symbol.h index 84f55dd1c7..174df73eb0 100644 --- a/Elf2Mac/Symbol.h +++ b/Elf2Mac/Symbol.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef SYMBOL_H @@ -32,16 +32,16 @@ class Object; class Symbol : public GElf_Sym { public: - bool valid; - bool referencedExternally; - SectionKind sectionKind; - bool needsJT; - int jtIndex; - std::shared_ptr
section; - std::string name; + bool valid; + bool referencedExternally; + SectionKind sectionKind; + bool needsJT; + int jtIndex; + std::shared_ptr
section; + std::string name; - Symbol(); - Symbol(Object &theObject, const GElf_Sym& sym); + Symbol(); + Symbol(Object &theObject, const GElf_Sym& sym); }; diff --git a/Elf2Mac/Symtab.cc b/Elf2Mac/Symtab.cc index dbc260ecdc..949bc76780 100644 --- a/Elf2Mac/Symtab.cc +++ b/Elf2Mac/Symtab.cc @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include "Symtab.h" @@ -30,26 +30,26 @@ using std::string; Symtab::Symtab(Object& theObject, Elf_Scn *elfsec) : elfsec(elfsec) { - data = elf_getdata(elfsec, NULL); + data = elf_getdata(elfsec, NULL); - GElf_Shdr shdr; - gelf_getshdr(elfsec, &shdr); + GElf_Shdr shdr; + gelf_getshdr(elfsec, &shdr); - int count = shdr.sh_size / shdr.sh_entsize; - symbols.reserve(count); + int count = shdr.sh_size / shdr.sh_entsize; + symbols.reserve(count); - for(int i = 0; i < count; i++) - { - GElf_Sym sym; - auto res = gelf_getsym(data, i, &sym); - assert(res != 0); - symbols.emplace_back(theObject, sym); + for(int i = 0; i < count; i++) + { + GElf_Sym sym; + auto res = gelf_getsym(data, i, &sym); + assert(res != 0); + symbols.emplace_back(theObject, sym); - if(sym.st_shndx != SHN_UNDEF && sym.st_shndx < SHN_LORESERVE) - symbolsByAddress[make_pair((int)sym.st_shndx,sym.st_value)] = i; - if(sym.st_name) - symbolsByName[symbols.back().name] = i; - } + if(sym.st_shndx != SHN_UNDEF && sym.st_shndx < SHN_LORESERVE) + symbolsByAddress[make_pair((int)sym.st_shndx,sym.st_value)] = i; + if(sym.st_name) + symbolsByName[symbols.back().name] = i; + } } Symtab::~Symtab() @@ -59,23 +59,23 @@ Symtab::~Symtab() Symbol &Symtab::GetSym(int idx) { - return symbols[idx]; + return symbols[idx]; } int Symtab::FindSym(int secidx, uint32_t addr) { - auto p = symbolsByAddress.find(make_pair(secidx, addr)); - if(p != symbolsByAddress.end()) - return p->second; - else - return -1; + auto p = symbolsByAddress.find(make_pair(secidx, addr)); + if(p != symbolsByAddress.end()) + return p->second; + else + return -1; } int Symtab::FindSym(string name) { - auto p = symbolsByName.find(name); - if(p != symbolsByName.end()) - return p->second; - else - return -1; + auto p = symbolsByName.find(name); + if(p != symbolsByName.end()) + return p->second; + else + return -1; } diff --git a/Elf2Mac/Symtab.h b/Elf2Mac/Symtab.h index 4ec46351ba..d7f9e5f508 100644 --- a/Elf2Mac/Symtab.h +++ b/Elf2Mac/Symtab.h @@ -1,20 +1,20 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #ifndef SYMTAB_H @@ -33,18 +33,18 @@ class Symbol; class Symtab { public: - Elf_Scn *elfsec; - Elf_Data *data; - std::vector symbols; - std::map, int> symbolsByAddress; - std::unordered_map symbolsByName; + Elf_Scn *elfsec; + Elf_Data *data; + std::vector symbols; + std::map, int> symbolsByAddress; + std::unordered_map symbolsByName; - Symtab(Object &theObject, Elf_Scn *elfsec); - ~Symtab(); + Symtab(Object &theObject, Elf_Scn *elfsec); + ~Symtab(); - Symbol& GetSym(int idx); - int FindSym(int secidx, uint32_t addr); - int FindSym(std::string name); + Symbol& GetSym(int idx); + int FindSym(int secidx, uint32_t addr); + int FindSym(std::string name); }; diff --git a/LaunchAPPL/Client/CMakeLists.txt b/LaunchAPPL/Client/CMakeLists.txt index cc7b179f93..7b1cfbb6c4 100644 --- a/LaunchAPPL/Client/CMakeLists.txt +++ b/LaunchAPPL/Client/CMakeLists.txt @@ -1,8 +1,8 @@ find_package(Boost COMPONENTS filesystem program_options) set(LAUNCHMETHODS - Executor.h Executor.cc - MiniVMac.h MiniVMac.cc + Executor.h Executor.cc + MiniVMac.h MiniVMac.cc SSH.h SSH.cc StreamBasedLauncher.h StreamBasedLauncher.cc Serial.h Serial.cc @@ -11,32 +11,32 @@ set(LAUNCHMETHODS ) if(APPLE) - LIST(APPEND LAUNCHMETHODS - Classic.h Classic.cc - ) - LIST(APPEND LAUNCHMETHODS - Carbon.h Carbon.cc) + LIST(APPEND LAUNCHMETHODS + Classic.h Classic.cc + ) + LIST(APPEND LAUNCHMETHODS + Carbon.h Carbon.cc) endif() add_definitions(-DRETRO68_PREFIX="${CMAKE_INSTALL_PREFIX}") add_executable(LaunchAPPL - LaunchAPPL.cc - MakeExecutable.cc + LaunchAPPL.cc + MakeExecutable.cc - LaunchMethod.h LaunchMethod.cc - Launcher.h Launcher.cc + LaunchMethod.h LaunchMethod.cc + Launcher.h Launcher.cc - Utilities.h Utilities.cc + Utilities.h Utilities.cc - ${LAUNCHMETHODS}) - + ${LAUNCHMETHODS}) + target_include_directories(LaunchAPPL PRIVATE ${CMAKE_INSTALL_PREFIX}/include ${Boost_INCLUDE_DIR}) target_link_libraries(LaunchAPPL ResourceFiles LaunchAPPLCommon ${Boost_LIBRARIES}) if(APPLE) - find_library(APPLICATIONSERVICES_FW ApplicationServices) - target_link_libraries(LaunchAPPL ${APPLICATIONSERVICES_FW}) + find_library(APPLICATIONSERVICES_FW ApplicationServices) + target_link_libraries(LaunchAPPL ${APPLICATIONSERVICES_FW}) endif() install(TARGETS LaunchAPPL RUNTIME DESTINATION bin) diff --git a/LaunchAPPL/Client/Carbon.cc b/LaunchAPPL/Client/Carbon.cc index b7e20d4f0f..3b4257528b 100644 --- a/LaunchAPPL/Client/Carbon.cc +++ b/LaunchAPPL/Client/Carbon.cc @@ -3,17 +3,17 @@ #include "Utilities.h" const std::string launchCFM = - "/System/Library/Frameworks/Carbon.framework/Versions/A/Support/LaunchCFMApp"; + "/System/Library/Frameworks/Carbon.framework/Versions/A/Support/LaunchCFMApp"; namespace po = boost::program_options; class CarbonLauncher : public Launcher { public: - CarbonLauncher(po::variables_map& options); - virtual ~CarbonLauncher(); + CarbonLauncher(po::variables_map& options); + virtual ~CarbonLauncher(); - virtual bool Go(int timeout = 0); + virtual bool Go(int timeout = 0); }; @@ -30,18 +30,18 @@ CarbonLauncher::~CarbonLauncher() bool CarbonLauncher::Go(int timeout) { - return ChildProcess(launchCFM, { appPath.string() }, timeout) == 0; + return ChildProcess(launchCFM, { appPath.string() }, timeout) == 0; } bool Carbon::CheckPlatform() { - /* If LaunchCFMApp doesn't exist, we're likely on a Mac OS X version - where it doesn't exist anymore (10.7 Lion or later), - or on an entirely different platform. */ - return CheckExecutable(launchCFM); + /* If LaunchCFMApp doesn't exist, we're likely on a Mac OS X version + where it doesn't exist anymore (10.7 Lion or later), + or on an entirely different platform. */ + return CheckExecutable(launchCFM); } std::unique_ptr Carbon::MakeLauncher(variables_map &options) { - return std::unique_ptr(new CarbonLauncher(options)); + return std::unique_ptr(new CarbonLauncher(options)); } diff --git a/LaunchAPPL/Client/Carbon.h b/LaunchAPPL/Client/Carbon.h index ff68272f47..01776d3196 100644 --- a/LaunchAPPL/Client/Carbon.h +++ b/LaunchAPPL/Client/Carbon.h @@ -6,10 +6,10 @@ class Carbon : public LaunchMethod { public: - virtual std::string GetName() { return "carbon"; } + virtual std::string GetName() { return "carbon"; } - virtual bool CheckPlatform(); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual bool CheckPlatform(); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // CARBON_METHOD_H diff --git a/LaunchAPPL/Client/Classic.cc b/LaunchAPPL/Client/Classic.cc index 8d71ba0041..18a3deb94f 100644 --- a/LaunchAPPL/Client/Classic.cc +++ b/LaunchAPPL/Client/Classic.cc @@ -12,10 +12,10 @@ namespace po = boost::program_options; class ClassicLauncher : public Launcher { public: - ClassicLauncher(po::variables_map& options); - virtual ~ClassicLauncher(); + ClassicLauncher(po::variables_map& options); + virtual ~ClassicLauncher(); - virtual bool Go(int timeout = 0); + virtual bool Go(int timeout = 0); }; @@ -31,52 +31,52 @@ ClassicLauncher::~ClassicLauncher() } bool ClassicLauncher::Go(int timeout) -{ - FSRef ref; - FSPathMakeRef((const UInt8*) appPath.string().c_str(), &ref, NULL); - LSApplicationParameters params; - memset(¶ms, 0, sizeof(params)); - params.flags = kLSLaunchStartClassic - | kLSLaunchInClassic - | kLSLaunchDontAddToRecents - | kLSLaunchNewInstance; - params.application = &ref; - - ProcessSerialNumber psn; - LSOpenApplication(¶ms, &psn); - - // Classic startup takes place before LSOpenApplication returns, - // so no extra timeout is needed - - for(int i = 0; i < timeout || timeout == 0; i++) - { - sleep(1); - - ProcessInfoRec pi; - pi.processInfoLength = sizeof(pi); - pi.processName = NULL; - pi.processAppSpec = 0; - if(GetProcessInformation(&psn, &pi) == procNotFound) - return true; - } +{ + FSRef ref; + FSPathMakeRef((const UInt8*) appPath.string().c_str(), &ref, NULL); + LSApplicationParameters params; + memset(¶ms, 0, sizeof(params)); + params.flags = kLSLaunchStartClassic + | kLSLaunchInClassic + | kLSLaunchDontAddToRecents + | kLSLaunchNewInstance; + params.application = &ref; + + ProcessSerialNumber psn; + LSOpenApplication(¶ms, &psn); + + // Classic startup takes place before LSOpenApplication returns, + // so no extra timeout is needed + + for(int i = 0; i < timeout || timeout == 0; i++) + { + sleep(1); + + ProcessInfoRec pi; + pi.processInfoLength = sizeof(pi); + pi.processName = NULL; + pi.processAppSpec = 0; + if(GetProcessInformation(&psn, &pi) == procNotFound) + return true; + } - KillProcess(&psn); + KillProcess(&psn); - return false; + return false; } bool Classic::CheckPlatform() { - long sysver = 0; - Gestalt(gestaltSystemVersion, &sysver); - if(sysver >= 0x1050) - return false; - else - return true; + long sysver = 0; + Gestalt(gestaltSystemVersion, &sysver); + if(sysver >= 0x1050) + return false; + else + return true; } std::unique_ptr Classic::MakeLauncher(variables_map &options) { - return std::unique_ptr(new ClassicLauncher(options)); + return std::unique_ptr(new ClassicLauncher(options)); } #endif diff --git a/LaunchAPPL/Client/Classic.h b/LaunchAPPL/Client/Classic.h index 22d869c545..8f9be3640c 100644 --- a/LaunchAPPL/Client/Classic.h +++ b/LaunchAPPL/Client/Classic.h @@ -6,10 +6,10 @@ class Classic : public LaunchMethod { public: - virtual std::string GetName() { return "classic"; } + virtual std::string GetName() { return "classic"; } - virtual bool CheckPlatform(); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual bool CheckPlatform(); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // CLASSIC_H diff --git a/LaunchAPPL/Client/Executor.cc b/LaunchAPPL/Client/Executor.cc index 64fb65aacc..f14f0b4a50 100644 --- a/LaunchAPPL/Client/Executor.cc +++ b/LaunchAPPL/Client/Executor.cc @@ -7,10 +7,10 @@ namespace po = boost::program_options; class ExecutorLauncher : public Launcher { public: - ExecutorLauncher(po::variables_map& options); - virtual ~ExecutorLauncher(); + ExecutorLauncher(po::variables_map& options); + virtual ~ExecutorLauncher(); - virtual bool Go(int timeout = 0); + virtual bool Go(int timeout = 0); }; @@ -27,37 +27,37 @@ ExecutorLauncher::~ExecutorLauncher() bool ExecutorLauncher::Go(int timeout) { - std::vector args; - if(options.count("executor-option")) - args = options["executor-option"].as>(); - args.push_back(appPath.string()); + std::vector args; + if(options.count("executor-option")) + args = options["executor-option"].as>(); + args.push_back(appPath.string()); - if(options.count("executor-system-folder")) - setenv("SystemFolder", options["executor-system-folder"].as().c_str(), true); + if(options.count("executor-system-folder")) + setenv("SystemFolder", options["executor-system-folder"].as().c_str(), true); - return ChildProcess(options["executor-path"].as(), args, timeout) == 0; + return ChildProcess(options["executor-path"].as(), args, timeout) == 0; } void Executor::GetOptions(options_description &desc) { - desc.add_options() - ("executor-path", po::value()->default_value("executor"),"path to executor") - ("executor-system-folder", po::value(), - "system folder for executor (overrides SystemFolder environment variable)") - ("executor-option", po::value>(), - "pass an option to executor") - ; + desc.add_options() + ("executor-path", po::value()->default_value("executor"),"path to executor") + ("executor-system-folder", po::value(), + "system folder for executor (overrides SystemFolder environment variable)") + ("executor-option", po::value>(), + "pass an option to executor") + ; } bool Executor::CheckOptions(variables_map &options) { - if(options.count("executor-path") == 0) - return false; - return CheckExecutable(options["executor-path"].as()); + if(options.count("executor-path") == 0) + return false; + return CheckExecutable(options["executor-path"].as()); } std::unique_ptr Executor::MakeLauncher(variables_map &options) { - return std::unique_ptr(new ExecutorLauncher(options)); + return std::unique_ptr(new ExecutorLauncher(options)); } diff --git a/LaunchAPPL/Client/Executor.h b/LaunchAPPL/Client/Executor.h index 57dc584416..5a79261da8 100644 --- a/LaunchAPPL/Client/Executor.h +++ b/LaunchAPPL/Client/Executor.h @@ -6,11 +6,11 @@ class Executor : public LaunchMethod { public: - virtual std::string GetName() { return "executor"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "executor"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // EXECUTOR_H diff --git a/LaunchAPPL/Client/LaunchAPPL.cc b/LaunchAPPL/Client/LaunchAPPL.cc index 8d98707286..32745a1446 100644 --- a/LaunchAPPL/Client/LaunchAPPL.cc +++ b/LaunchAPPL/Client/LaunchAPPL.cc @@ -9,13 +9,13 @@ #include "Launcher.h" #if defined(__APPLE__) -# define ResType MacResType -# include -# undef ResType -# if TARGET_CPU_PPC -# include "Classic.h" -# endif -# include "Carbon.h" +# define ResType MacResType +# include +# undef ResType +# if TARGET_CPU_PPC +# include "Classic.h" +# endif +# include "Carbon.h" #endif #include "Executor.h" #include "MiniVMac.h" @@ -37,224 +37,224 @@ static vector launchMethods; static void RegisterLaunchMethods() { - vector methods = { + vector methods = { #if defined(__APPLE__) -# if TARGET_CPU_PPC - new Classic(), -# endif - new Carbon(), +# if TARGET_CPU_PPC + new Classic(), +# endif + new Carbon(), #endif - new Executor(), new MiniVMac(), - new SSH(), + new Executor(), new MiniVMac(), + new SSH(), new Serial(), new TCP(), new SharedFile() - // #### Add new `LaunchMethod`s here. - }; - - for(LaunchMethod *m : methods) - { - if(m->CheckPlatform()) - launchMethods.push_back(m); - } + // #### Add new `LaunchMethod`s here. + }; + + for(LaunchMethod *m : methods) + { + if(m->CheckPlatform()) + launchMethods.push_back(m); + } } static void usage() { - std::cerr << "Usage: " << "LaunchAPPL [options] appl-file\n"; - std::cerr << desc << std::endl; - std::cerr << "Defaults are read from:\n"; - for(string str : configFiles) - { - std::cerr << "\t" << str; - if(!std::ifstream(str)) - std::cerr << " (not found)"; - std::cerr << std::endl; - } - std::cerr << std::endl; + std::cerr << "Usage: " << "LaunchAPPL [options] appl-file\n"; + std::cerr << desc << std::endl; + std::cerr << "Defaults are read from:\n"; + for(string str : configFiles) + { + std::cerr << "\t" << str; + if(!std::ifstream(str)) + std::cerr << " (not found)"; + std::cerr << std::endl; + } + std::cerr << std::endl; - vector configuredMethods, unconfiguredMethods; - for(LaunchMethod *method : launchMethods) - (method->CheckOptions(options) ? configuredMethods : unconfiguredMethods) - .push_back(method->GetName()); + vector configuredMethods, unconfiguredMethods; + for(LaunchMethod *method : launchMethods) + (method->CheckOptions(options) ? configuredMethods : unconfiguredMethods) + .push_back(method->GetName()); - if(!configuredMethods.empty()) - { - std::cerr << "Available emulators/environments:\n"; - for(string m : configuredMethods) - std::cerr << "\t" << m << std::endl; - } - if(!unconfiguredMethods.empty()) - { - std::cerr << "Emulators/environments needing more configuration:\n"; - for(string m : unconfiguredMethods) - std::cerr << "\t" << m << std::endl; - } + if(!configuredMethods.empty()) + { + std::cerr << "Available emulators/environments:\n"; + for(string m : configuredMethods) + std::cerr << "\t" << m << std::endl; + } + if(!unconfiguredMethods.empty()) + { + std::cerr << "Emulators/environments needing more configuration:\n"; + for(string m : unconfiguredMethods) + std::cerr << "\t" << m << std::endl; + } - if(options.count("emulator")) - { - string e = options["emulator"].as(); - std::cerr << "\nChosen emulator/environment: " << e; - if(std::find(configuredMethods.begin(), configuredMethods.end(), e) - != configuredMethods.end()) - std::cerr << "\n"; - else if(std::find(unconfiguredMethods.begin(), unconfiguredMethods.end(), e) - != unconfiguredMethods.end()) - std::cerr << " (needs more configuration)\n"; - else - std::cerr << " (UNKNOWN)\n"; - } - else - { - std::cerr << "\nNo emulator/environment chosen (-e)\n"; - } + if(options.count("emulator")) + { + string e = options["emulator"].as(); + std::cerr << "\nChosen emulator/environment: " << e; + if(std::find(configuredMethods.begin(), configuredMethods.end(), e) + != configuredMethods.end()) + std::cerr << "\n"; + else if(std::find(unconfiguredMethods.begin(), unconfiguredMethods.end(), e) + != unconfiguredMethods.end()) + std::cerr << " (needs more configuration)\n"; + else + std::cerr << " (UNKNOWN)\n"; + } + else + { + std::cerr << "\nNo emulator/environment chosen (-e)\n"; + } } void MakeExecutable(string filepath); int main(int argc, char *argv[]) { - RegisterLaunchMethods(); - configFiles = { string(getenv("HOME")) + "/.LaunchAPPL.cfg", RETRO68_PREFIX "/LaunchAPPL.cfg"}; + RegisterLaunchMethods(); + configFiles = { string(getenv("HOME")) + "/.LaunchAPPL.cfg", RETRO68_PREFIX "/LaunchAPPL.cfg"}; - desc.add_options() - ("help,h", "show this help message") - ("list-emulators,l", "get the list of available, fully configured emulators/environments") - ("make-executable,x", po::value(), "make a MacBinary file executable") - ; - po::options_description configdesc; - configdesc.add_options() - ("emulator,e", po::value(), "what emulator/environment to use") - ; - for(LaunchMethod *lm : launchMethods) - lm->GetOptions(configdesc); - desc.add(configdesc); + desc.add_options() + ("help,h", "show this help message") + ("list-emulators,l", "get the list of available, fully configured emulators/environments") + ("make-executable,x", po::value(), "make a MacBinary file executable") + ; + po::options_description configdesc; + configdesc.add_options() + ("emulator,e", po::value(), "what emulator/environment to use") + ; + for(LaunchMethod *lm : launchMethods) + lm->GetOptions(configdesc); + desc.add(configdesc); - desc.add_options() - ("timeout,t", po::value(),"abort after timeout") + desc.add_options() + ("timeout,t", po::value(),"abort after timeout") ("upgrade-server", "upgrade the server application") - ; - po::options_description hidden, alldesc; - hidden.add_options() - ("application,a", po::value(), "application" ) - ; - alldesc.add(desc).add(hidden); - try - { - auto parsed = po::command_line_parser(argc, argv) - .options(alldesc) - .positional(po::positional_options_description().add("application", -1)) - .style(po::command_line_style::default_style) - .run(); + ; + po::options_description hidden, alldesc; + hidden.add_options() + ("application,a", po::value(), "application" ) + ; + alldesc.add(desc).add(hidden); + try + { + auto parsed = po::command_line_parser(argc, argv) + .options(alldesc) + .positional(po::positional_options_description().add("application", -1)) + .style(po::command_line_style::default_style) + .run(); - po::store(parsed, options); - } - catch(po::error& e) - { - std::cerr << "ERROR: " << e.what() << std::endl << std::endl; - usage(); - return 1; - } + po::store(parsed, options); + } + catch(po::error& e) + { + std::cerr << "ERROR: " << e.what() << std::endl << std::endl; + usage(); + return 1; + } - for(string configFileName : configFiles) - { - try - { - std::ifstream cfg(configFileName); - if(cfg) - { - auto parsed = po::parse_config_file(cfg,configdesc,false); + for(string configFileName : configFiles) + { + try + { + std::ifstream cfg(configFileName); + if(cfg) + { + auto parsed = po::parse_config_file(cfg,configdesc,false); - po::store(parsed, options); - } - } - catch(po::error& e) - { - std::cerr << "CONFIG FILE ERROR: " << e.what() << std::endl << std::endl; - usage(); - return 1; - } - } + po::store(parsed, options); + } + } + catch(po::error& e) + { + std::cerr << "CONFIG FILE ERROR: " << e.what() << std::endl << std::endl; + usage(); + return 1; + } + } - po::notify(options); + po::notify(options); - vector commandModes = {"application", "help", "make-executable", "list-emulators"}; - int nModes = 0; - string mode; + vector commandModes = {"application", "help", "make-executable", "list-emulators"}; + int nModes = 0; + string mode; - for(string aMode : commandModes) - { - if(options.count(aMode)) - { - nModes++; - mode = aMode; - } - } - if(nModes > 1) - { - std::cerr << "Need to specify either an application file or exactly one of "; - for(int i = 1, n = commandModes.size(); i < n-1; i++) - std::cerr << "--" << commandModes[i] << ", "; - std::cerr << "or " << commandModes.back() << "." << std::endl << std::endl; - usage(); - return 1; - } - if(mode == "" || mode == "help") - { - usage(); - return 0; - } - else if(mode == "make-executable") - { - string fn = options["make-executable"].as(); - MakeExecutable(fn); - return 0; - } - else if(mode == "list-emulators") - { - for(LaunchMethod *method : launchMethods) - if(method->CheckOptions(options)) - std::cout << method->GetName() << std::endl; - return 0; - } + for(string aMode : commandModes) + { + if(options.count(aMode)) + { + nModes++; + mode = aMode; + } + } + if(nModes > 1) + { + std::cerr << "Need to specify either an application file or exactly one of "; + for(int i = 1, n = commandModes.size(); i < n-1; i++) + std::cerr << "--" << commandModes[i] << ", "; + std::cerr << "or " << commandModes.back() << "." << std::endl << std::endl; + usage(); + return 1; + } + if(mode == "" || mode == "help") + { + usage(); + return 0; + } + else if(mode == "make-executable") + { + string fn = options["make-executable"].as(); + MakeExecutable(fn); + return 0; + } + else if(mode == "list-emulators") + { + for(LaunchMethod *method : launchMethods) + if(method->CheckOptions(options)) + std::cout << method->GetName() << std::endl; + return 0; + } - if(!options.count("emulator")) - { - std::cerr << "ERROR: emulator/environment not specified.\n"; - usage(); - return 1; - } + if(!options.count("emulator")) + { + std::cerr << "ERROR: emulator/environment not specified.\n"; + usage(); + return 1; + } - LaunchMethod *method = NULL; - for(LaunchMethod *lm : launchMethods) - { - if(lm->GetName() == options["emulator"].as()) - { - method = lm; - break; - } - } - if(!method) - { - std::cerr << "ERROR: unknown emulator/environment: " << options["emulator"].as() << "\n"; - return 1; - } + LaunchMethod *method = NULL; + for(LaunchMethod *lm : launchMethods) + { + if(lm->GetName() == options["emulator"].as()) + { + method = lm; + break; + } + } + if(!method) + { + std::cerr << "ERROR: unknown emulator/environment: " << options["emulator"].as() << "\n"; + return 1; + } - if(!method->CheckOptions(options)) - { - std::cerr << "Need more configuration.\n"; - usage(); - return 1; - } + if(!method->CheckOptions(options)) + { + std::cerr << "Need more configuration.\n"; + usage(); + return 1; + } - std::unique_ptr launcher = method->MakeLauncher(options); + std::unique_ptr launcher = method->MakeLauncher(options); - int timeout = options.count("timeout") ? options["timeout"].as() : 0; + int timeout = options.count("timeout") ? options["timeout"].as() : 0; - bool result = launcher->Go(timeout); + bool result = launcher->Go(timeout); - launcher->DumpOutput(); + launcher->DumpOutput(); - return result ? 0 : 1; + return result ? 0 : 1; } diff --git a/LaunchAPPL/Client/LaunchMethod.cc b/LaunchAPPL/Client/LaunchMethod.cc index c2ee674c24..18f7433fe3 100644 --- a/LaunchAPPL/Client/LaunchMethod.cc +++ b/LaunchAPPL/Client/LaunchMethod.cc @@ -16,10 +16,10 @@ void LaunchMethod::GetOptions(boost::program_options::options_description &desc) bool LaunchMethod::CheckPlatform() { - return true; + return true; } bool LaunchMethod::CheckOptions(boost::program_options::variables_map &options) { - return true; + return true; } diff --git a/LaunchAPPL/Client/LaunchMethod.h b/LaunchAPPL/Client/LaunchMethod.h index 3c4e307b1d..db958734ad 100644 --- a/LaunchAPPL/Client/LaunchMethod.h +++ b/LaunchAPPL/Client/LaunchMethod.h @@ -18,52 +18,52 @@ class Launcher; class LaunchMethod { public: - typedef boost::program_options::options_description options_description; - typedef boost::program_options::variables_map variables_map; + typedef boost::program_options::options_description options_description; + typedef boost::program_options::variables_map variables_map; - LaunchMethod(); - virtual ~LaunchMethod(); + LaunchMethod(); + virtual ~LaunchMethod(); - /** - * @brief GetName - * @return the name of the launch method, as it will be specified on the command line - */ - virtual std::string GetName() = 0; + /** + * @brief GetName + * @return the name of the launch method, as it will be specified on the command line + */ + virtual std::string GetName() = 0; - /** - * @brief GetOptions - * @param desc - * - * Add any command line options for this LaunchMethod - * to the options_description structure. - */ - virtual void GetOptions(options_description& desc); + /** + * @brief GetOptions + * @param desc + * + * Add any command line options for this LaunchMethod + * to the options_description structure. + */ + virtual void GetOptions(options_description& desc); - /** - * @brief CheckPlatform - * - * Check whether this is the right kind of machine to use this method. - * For things like Apple's Classic Environment, which is only available on some system versions. - * The default implementation returns true. - */ - virtual bool CheckPlatform(); + /** + * @brief CheckPlatform + * + * Check whether this is the right kind of machine to use this method. + * For things like Apple's Classic Environment, which is only available on some system versions. + * The default implementation returns true. + */ + virtual bool CheckPlatform(); - /** - * @brief CheckOptions - * @param options - * @return are we ready to run? - * - * Check whether all necessary options have been specified. - * Don't output error messages here, this is also called when outputting usage information - */ - virtual bool CheckOptions(variables_map& options); + /** + * @brief CheckOptions + * @param options + * @return are we ready to run? + * + * Check whether all necessary options have been specified. + * Don't output error messages here, this is also called when outputting usage information + */ + virtual bool CheckOptions(variables_map& options); - /** - * @brief MakeLauncher - * @param options - * @return a new instance of a subclass of Launcher which will do the actual work - */ - virtual std::unique_ptr MakeLauncher(variables_map& options) = 0; + /** + * @brief MakeLauncher + * @param options + * @return a new instance of a subclass of Launcher which will do the actual work + */ + virtual std::unique_ptr MakeLauncher(variables_map& options) = 0; protected: }; diff --git a/LaunchAPPL/Client/Launcher.cc b/LaunchAPPL/Client/Launcher.cc index 3094b323d9..16649b6976 100644 --- a/LaunchAPPL/Client/Launcher.cc +++ b/LaunchAPPL/Client/Launcher.cc @@ -11,47 +11,47 @@ using std::vector; Launcher::Launcher(boost::program_options::variables_map &options) : options(options) { - string fn = options["application"].as(); - - if(fn == "-") - { - std::stringstream tmp; - tmp << std::cin.rdbuf(); - if(!app.read(tmp, ResourceFile::Format::macbin)) - throw std::runtime_error("Could not load application from stdin."); - } - else - { - app.assign(fn); - if(!app.read()) - throw std::runtime_error("Could not load application file."); - } - - tempDir = fs::absolute(fs::unique_path()); - fs::create_directories(tempDir); + string fn = options["application"].as(); + + if(fn == "-") + { + std::stringstream tmp; + tmp << std::cin.rdbuf(); + if(!app.read(tmp, ResourceFile::Format::macbin)) + throw std::runtime_error("Could not load application from stdin."); + } + else + { + app.assign(fn); + if(!app.read()) + throw std::runtime_error("Could not load application file."); + } + + tempDir = fs::absolute(fs::unique_path()); + fs::create_directories(tempDir); - appPath = tempDir / "Application"; - outPath = tempDir / "out"; + appPath = tempDir / "Application"; + outPath = tempDir / "out"; - fs::ofstream out(outPath); + fs::ofstream out(outPath); } Launcher::Launcher(boost::program_options::variables_map &options, ResourceFile::Format f) : Launcher(options) { - app.assign(appPath.string(), f); - app.write(); + app.assign(appPath.string(), f); + app.write(); } void Launcher::DumpOutput() { - fs::ifstream in(outPath); - std::cout << in.rdbuf(); + fs::ifstream in(outPath); + std::cout << in.rdbuf(); } Launcher::~Launcher() { - fs::remove_all(tempDir); + fs::remove_all(tempDir); } diff --git a/LaunchAPPL/Client/Launcher.h b/LaunchAPPL/Client/Launcher.h index d47cced085..14e49998e5 100644 --- a/LaunchAPPL/Client/Launcher.h +++ b/LaunchAPPL/Client/Launcher.h @@ -14,61 +14,61 @@ class Launcher { protected: - boost::program_options::variables_map& options; + boost::program_options::variables_map& options; - ResourceFile app; - boost::filesystem::path tempDir, appPath, outPath; - bool keepTempFiles; + ResourceFile app; + boost::filesystem::path tempDir, appPath, outPath; + bool keepTempFiles; public: - /** - * @brief Launcher - * @param options - * - * Create a Launcher object and set up a temporary directory to play in. - * Reads the Applicatio specified on the command line into the `app` member variable. - * Also create an empty file named 'out' in the temporary directory, for test suite programs. - */ - Launcher(boost::program_options::variables_map& options); + /** + * @brief Launcher + * @param options + * + * Create a Launcher object and set up a temporary directory to play in. + * Reads the Applicatio specified on the command line into the `app` member variable. + * Also create an empty file named 'out' in the temporary directory, for test suite programs. + */ + Launcher(boost::program_options::variables_map& options); - /** - * @brief Launcher - * @param options - * @param f - * - * Create a Launcher object, set up a temporary directory - * and store the application to be executed at `appPath` in the temporary directory, - * using format `f`. - */ - Launcher(boost::program_options::variables_map& options, ResourceFile::Format f); + /** + * @brief Launcher + * @param options + * @param f + * + * Create a Launcher object, set up a temporary directory + * and store the application to be executed at `appPath` in the temporary directory, + * using format `f`. + */ + Launcher(boost::program_options::variables_map& options, ResourceFile::Format f); - /** - * @brief ~Launcher - * Delete our temporary directory. - */ - virtual ~Launcher(); + /** + * @brief ~Launcher + * Delete our temporary directory. + */ + virtual ~Launcher(); - /** - * @brief Go - * @param timeout - * @return true for success - * - * Launch the application, return true on success and false on error or timeout. - */ - virtual bool Go(int timeout = 0) = 0; + /** + * @brief Go + * @param timeout + * @return true for success + * + * Launch the application, return true on success and false on error or timeout. + */ + virtual bool Go(int timeout = 0) = 0; - /** - * @brief DumpOutput - * - * After the application has been run, copy the contents of the 'out' file to stdout. - */ - virtual void DumpOutput(); + /** + * @brief DumpOutput + * + * After the application has been run, copy the contents of the 'out' file to stdout. + */ + virtual void DumpOutput(); - /** - * @brief KeepTempFiles - * Inhibit deletion of the temporary directory. - */ - void KeepTempFiles() { keepTempFiles = true; } + /** + * @brief KeepTempFiles + * Inhibit deletion of the temporary directory. + */ + void KeepTempFiles() { keepTempFiles = true; } }; #endif // LAUNCHER_H diff --git a/LaunchAPPL/Client/MakeExecutable.cc b/LaunchAPPL/Client/MakeExecutable.cc index 5d3f5c58e6..2707881f56 100644 --- a/LaunchAPPL/Client/MakeExecutable.cc +++ b/LaunchAPPL/Client/MakeExecutable.cc @@ -11,43 +11,43 @@ namespace fs = boost::filesystem; void MakeExecutable(string fn) { - ResourceFile rsrcFile(fn); - if(!rsrcFile.read()) - { - std::cerr << "Cannot read application file: " << fn << std::endl; - exit(1); - } - if(!rsrcFile.hasPlainDataFork()) - { - std::cerr << "--make-executable can not be used with this data format.\n"; - exit(1); - } + ResourceFile rsrcFile(fn); + if(!rsrcFile.read()) + { + std::cerr << "Cannot read application file: " << fn << std::endl; + exit(1); + } + if(!rsrcFile.hasPlainDataFork()) + { + std::cerr << "--make-executable can not be used with this data format.\n"; + exit(1); + } - string headerString = "#!" RETRO68_PREFIX "/bin/LaunchAPPL\n"; + string headerString = "#!" RETRO68_PREFIX "/bin/LaunchAPPL\n"; - bool hadShebang = false; - if(rsrcFile.data.size()) - { - if(headerString.substr(2) == "#!") - { - string::size_type eol = headerString.find('\n'); - if(eol != string::npos && eol >= 13 && eol < 4096) - { - if(headerString.substr(eol-11,11) == "/LaunchAPPL") - hadShebang = true; - } - } + bool hadShebang = false; + if(rsrcFile.data.size()) + { + if(headerString.substr(2) == "#!") + { + string::size_type eol = headerString.find('\n'); + if(eol != string::npos && eol >= 13 && eol < 4096) + { + if(headerString.substr(eol-11,11) == "/LaunchAPPL") + hadShebang = true; + } + } - if(!hadShebang) - { - std::cerr << "Unfortunately, the application already has a data fork.\n"; - std::cerr << "LaunchAPPL --make-executable does not currently work for PowerPC apps.\n"; - // TODO: if it's a PEF container, move it back a little and update cfrg - exit(1); - } - } + if(!hadShebang) + { + std::cerr << "Unfortunately, the application already has a data fork.\n"; + std::cerr << "LaunchAPPL --make-executable does not currently work for PowerPC apps.\n"; + // TODO: if it's a PEF container, move it back a little and update cfrg + exit(1); + } + } - std::fstream(fn, std::ios::in | std::ios::out | std::ios::binary) << headerString; + std::fstream(fn, std::ios::in | std::ios::out | std::ios::binary) << headerString; - fs::permissions(fs::path(fn), fs::owner_exe | fs::group_exe | fs::others_exe | fs::add_perms); + fs::permissions(fs::path(fn), fs::owner_exe | fs::group_exe | fs::others_exe | fs::add_perms); } diff --git a/LaunchAPPL/Client/MiniVMac.h b/LaunchAPPL/Client/MiniVMac.h index 0f83aa4ad8..011593c438 100644 --- a/LaunchAPPL/Client/MiniVMac.h +++ b/LaunchAPPL/Client/MiniVMac.h @@ -6,11 +6,11 @@ class MiniVMac : public LaunchMethod { public: - virtual std::string GetName() { return "minivmac"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "minivmac"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // MINIVMAC_H diff --git a/LaunchAPPL/Client/SSH.cc b/LaunchAPPL/Client/SSH.cc index 8286341cd3..f29ef858ad 100644 --- a/LaunchAPPL/Client/SSH.cc +++ b/LaunchAPPL/Client/SSH.cc @@ -16,10 +16,10 @@ using std::vector; class SSHLauncher : public Launcher { public: - SSHLauncher(po::variables_map& options); - virtual ~SSHLauncher(); + SSHLauncher(po::variables_map& options); + virtual ~SSHLauncher(); - virtual bool Go(int timeout = 0); + virtual bool Go(int timeout = 0); }; @@ -36,115 +36,115 @@ SSHLauncher::~SSHLauncher() static void insertArgs(vector& args, po::variables_map& options, string name) { - if(options.count(name)) - { - auto extraArgs = SplitArguments(options[name].as>()); - args.insert(args.end(), extraArgs.begin(), extraArgs.end()); - } + if(options.count(name)) + { + auto extraArgs = SplitArguments(options[name].as>()); + args.insert(args.end(), extraArgs.begin(), extraArgs.end()); + } } bool SSHLauncher::Go(int timeout) { - std::vector args; - args.push_back(options["ssh-host"].as()); - insertArgs(args, options, "ssh-args"); - args.push_back("--"); - args.push_back(options["ssh-remote-path"].as()); - insertArgs(args, options, "ssh-remote-args"); - if(timeout) - { - args.push_back("--timeout"); - args.push_back(boost::lexical_cast(timeout)); - } - args.push_back("-"); + std::vector args; + args.push_back(options["ssh-host"].as()); + insertArgs(args, options, "ssh-args"); + args.push_back("--"); + args.push_back(options["ssh-remote-path"].as()); + insertArgs(args, options, "ssh-remote-args"); + if(timeout) + { + args.push_back("--timeout"); + args.push_back(boost::lexical_cast(timeout)); + } + args.push_back("-"); - std::string program = options["ssh-path"].as(); + std::string program = options["ssh-path"].as(); - std::vector argv; - argv.push_back(program.c_str()); - for(std::string& s : args) - argv.push_back(s.c_str()); - argv.push_back(NULL); + std::vector argv; + argv.push_back(program.c_str()); + for(std::string& s : args) + argv.push_back(s.c_str()); + argv.push_back(NULL); - int fd[2]; - pipe(fd); - const int READ_END = 0; - const int WRITE_END = 1; + int fd[2]; + pipe(fd); + const int READ_END = 0; + const int WRITE_END = 1; - pid_t pid = fork(); - if(pid < 0) - { - perror("unable to fork"); - return 1; - } - else if(pid == 0) - { - dup2(fd[READ_END], STDIN_FILENO); - close(fd[WRITE_END]); - close(fd[READ_END]); + pid_t pid = fork(); + if(pid < 0) + { + perror("unable to fork"); + return 1; + } + else if(pid == 0) + { + dup2(fd[READ_END], STDIN_FILENO); + close(fd[WRITE_END]); + close(fd[READ_END]); - execvp(argv[0], const_cast (argv.data())); - perror("exec failed"); - std::cerr << "Tried to execute: " << program; - for(auto a : args) - std::cerr << " " << a; - std::cerr << std::endl; - _exit(1); - } - else - { - close(fd[READ_END]); + execvp(argv[0], const_cast (argv.data())); + perror("exec failed"); + std::cerr << "Tried to execute: " << program; + for(auto a : args) + std::cerr << " " << a; + std::cerr << std::endl; + _exit(1); + } + else + { + close(fd[READ_END]); - std::ostringstream tmp; - app.write(tmp, ResourceFile::Format::macbin); - const std::string data = tmp.str(); + std::ostringstream tmp; + app.write(tmp, ResourceFile::Format::macbin); + const std::string data = tmp.str(); - write(fd[WRITE_END], data.data(), data.size()); - close(fd[WRITE_END]); + write(fd[WRITE_END], data.data(), data.size()); + close(fd[WRITE_END]); - int wstatus; - int result = 0; - do - { - result = waitpid(pid, &wstatus, 0); - } while(result == -1 && errno == EINTR); + int wstatus; + int result = 0; + do + { + result = waitpid(pid, &wstatus, 0); + } while(result == -1 && errno == EINTR); - if(!WIFEXITED(wstatus)) - { - return false; - } - else - { - //int exitcode = WEXITSTATUS(wstatus); - return true; - } - } + if(!WIFEXITED(wstatus)) + { + return false; + } + else + { + //int exitcode = WEXITSTATUS(wstatus); + return true; + } + } } void SSH::GetOptions(options_description &desc) { - desc.add_options() - ("ssh-path", po::value()->default_value("ssh"),"ssh command to use") - ("ssh-host", po::value(), - "[username@]address of remote host") - ("ssh-args", po::value>(), - "additional arguments for ssh") - ("ssh-remote-path", po::value()->default_value("LaunchAPPL"), - "path to LaunchAPPL on remote host") - ("ssh-remote-args", po::value>(), - "additional arguments for LaunchAPPL on remote host") - ; + desc.add_options() + ("ssh-path", po::value()->default_value("ssh"),"ssh command to use") + ("ssh-host", po::value(), + "[username@]address of remote host") + ("ssh-args", po::value>(), + "additional arguments for ssh") + ("ssh-remote-path", po::value()->default_value("LaunchAPPL"), + "path to LaunchAPPL on remote host") + ("ssh-remote-args", po::value>(), + "additional arguments for LaunchAPPL on remote host") + ; } bool SSH::CheckOptions(variables_map &options) { - return options.count("ssh-host") != 0; + return options.count("ssh-host") != 0; } std::unique_ptr SSH::MakeLauncher(variables_map &options) { - return std::unique_ptr(new SSHLauncher(options)); + return std::unique_ptr(new SSHLauncher(options)); } diff --git a/LaunchAPPL/Client/SSH.h b/LaunchAPPL/Client/SSH.h index 24adf34ef5..ffe19d3efa 100644 --- a/LaunchAPPL/Client/SSH.h +++ b/LaunchAPPL/Client/SSH.h @@ -6,11 +6,11 @@ class SSH : public LaunchMethod { public: - virtual std::string GetName() { return "ssh"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "ssh"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // SSH_H diff --git a/LaunchAPPL/Client/Serial.cc b/LaunchAPPL/Client/Serial.cc index 9f1319723d..f37652af78 100644 --- a/LaunchAPPL/Client/Serial.cc +++ b/LaunchAPPL/Client/Serial.cc @@ -36,7 +36,7 @@ class SerialLauncher : public StreamBasedLauncher SerialStream stream; ReliableStream rStream; public: - SerialLauncher(po::variables_map& options); + SerialLauncher(po::variables_map& options); }; @@ -146,10 +146,10 @@ void Serial::GetOptions(options_description &desc) bool Serial::CheckOptions(variables_map &options) { - return true; + return true; } std::unique_ptr Serial::MakeLauncher(variables_map &options) { - return std::unique_ptr(new SerialLauncher(options)); + return std::unique_ptr(new SerialLauncher(options)); } diff --git a/LaunchAPPL/Client/Serial.h b/LaunchAPPL/Client/Serial.h index f34c7a7bae..291e346906 100644 --- a/LaunchAPPL/Client/Serial.h +++ b/LaunchAPPL/Client/Serial.h @@ -6,11 +6,11 @@ class Serial : public LaunchMethod { public: - virtual std::string GetName() { return "serial"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "serial"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // EXECUTOR_H diff --git a/LaunchAPPL/Client/SharedFile.cc b/LaunchAPPL/Client/SharedFile.cc index 96ea07b65c..d935b04a3f 100644 --- a/LaunchAPPL/Client/SharedFile.cc +++ b/LaunchAPPL/Client/SharedFile.cc @@ -30,7 +30,7 @@ class SharedFileLauncher : public StreamBasedLauncher { SharedFileStream stream; public: - SharedFileLauncher(po::variables_map& options); + SharedFileLauncher(po::variables_map& options); }; SharedFileStream::SharedFileStream(po::variables_map &options) @@ -90,10 +90,10 @@ void SharedFile::GetOptions(options_description &desc) bool SharedFile::CheckOptions(variables_map &options) { - return options.count("shared-directory") != 0; + return options.count("shared-directory") != 0; } std::unique_ptr SharedFile::MakeLauncher(variables_map &options) { - return std::unique_ptr(new SharedFileLauncher(options)); + return std::unique_ptr(new SharedFileLauncher(options)); } diff --git a/LaunchAPPL/Client/SharedFile.h b/LaunchAPPL/Client/SharedFile.h index 7554c67023..582d0f3162 100644 --- a/LaunchAPPL/Client/SharedFile.h +++ b/LaunchAPPL/Client/SharedFile.h @@ -5,9 +5,9 @@ class SharedFile : public LaunchMethod { public: - virtual std::string GetName() { return "shared"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "shared"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; diff --git a/LaunchAPPL/Client/StreamBasedLauncher.h b/LaunchAPPL/Client/StreamBasedLauncher.h index cda6867aad..b5fe6214b3 100644 --- a/LaunchAPPL/Client/StreamBasedLauncher.h +++ b/LaunchAPPL/Client/StreamBasedLauncher.h @@ -12,11 +12,11 @@ class StreamBasedLauncher : public Launcher std::vector outputBytes; bool upgradeMode = false; public: - StreamBasedLauncher(boost::program_options::variables_map& options); - virtual ~StreamBasedLauncher(); + StreamBasedLauncher(boost::program_options::variables_map& options); + virtual ~StreamBasedLauncher(); - virtual bool Go(int timeout = 0); - virtual void DumpOutput(); + virtual bool Go(int timeout = 0); + virtual void DumpOutput(); protected: void SetupStream(WaitableStream* aStream, Stream* wrapped = nullptr); diff --git a/LaunchAPPL/Client/TCP.cc b/LaunchAPPL/Client/TCP.cc index 00c9c592fb..26d66ddd39 100644 --- a/LaunchAPPL/Client/TCP.cc +++ b/LaunchAPPL/Client/TCP.cc @@ -34,7 +34,7 @@ class TCPLauncher : public StreamBasedLauncher { TCPStream stream; public: - TCPLauncher(po::variables_map& options); + TCPLauncher(po::variables_map& options); }; @@ -85,10 +85,10 @@ void TCP::GetOptions(options_description &desc) bool TCP::CheckOptions(variables_map &options) { - return options.count("tcp-address") != 0; + return options.count("tcp-address") != 0; } std::unique_ptr TCP::MakeLauncher(variables_map &options) { - return std::unique_ptr(new TCPLauncher(options)); + return std::unique_ptr(new TCPLauncher(options)); } diff --git a/LaunchAPPL/Client/TCP.h b/LaunchAPPL/Client/TCP.h index e4f6d0fd9f..569b3a21ac 100644 --- a/LaunchAPPL/Client/TCP.h +++ b/LaunchAPPL/Client/TCP.h @@ -6,11 +6,11 @@ class TCP : public LaunchMethod { public: - virtual std::string GetName() { return "tcp"; } - virtual void GetOptions(options_description& desc); - virtual bool CheckOptions(variables_map& options); + virtual std::string GetName() { return "tcp"; } + virtual void GetOptions(options_description& desc); + virtual bool CheckOptions(variables_map& options); - virtual std::unique_ptr MakeLauncher(variables_map& options); + virtual std::unique_ptr MakeLauncher(variables_map& options); }; #endif // EXECUTOR_H diff --git a/LaunchAPPL/Client/Utilities.cc b/LaunchAPPL/Client/Utilities.cc index e9514cdb94..10a25184eb 100644 --- a/LaunchAPPL/Client/Utilities.cc +++ b/LaunchAPPL/Client/Utilities.cc @@ -13,90 +13,90 @@ using std::vector; int ChildProcess(string program, vector args, int timeout) { - std::vector argv; - argv.push_back(program.c_str()); - for(string& s : args) - argv.push_back(s.c_str()); - argv.push_back(NULL); + std::vector argv; + argv.push_back(program.c_str()); + for(string& s : args) + argv.push_back(s.c_str()); + argv.push_back(NULL); - pid_t pid = fork(); - if(pid < 0) - { - perror("unable to fork"); - return 1; - } - else if(pid == 0) - { - pid_t worker_pid = timeout ? fork() : 0; - if(worker_pid < 0) - { - perror("unable to fork"); - _exit(1); - } - if(worker_pid == 0) - { - execvp(argv[0], const_cast (argv.data())); - perror("exec failed"); - std::cerr << "Tried to execute: " << program; - for(auto a : args) - std::cerr << " " << a; - std::cerr << std::endl; - _exit(1); - } + pid_t pid = fork(); + if(pid < 0) + { + perror("unable to fork"); + return 1; + } + else if(pid == 0) + { + pid_t worker_pid = timeout ? fork() : 0; + if(worker_pid < 0) + { + perror("unable to fork"); + _exit(1); + } + if(worker_pid == 0) + { + execvp(argv[0], const_cast (argv.data())); + perror("exec failed"); + std::cerr << "Tried to execute: " << program; + for(auto a : args) + std::cerr << " " << a; + std::cerr << std::endl; + _exit(1); + } - pid_t timeout_pid = fork(); - if(timeout_pid < 0) - { - perror("unable to fork"); - _exit(1); - } - if(timeout_pid == 0) - { - sleep(timeout); - _exit(0); - } - int wstatus; - pid_t exited_pid = wait(&wstatus); - if(exited_pid == worker_pid) - { - kill(timeout_pid, SIGKILL); - wait(NULL); - if(!WIFEXITED(wstatus)) - { - return 1; - } - else - { - int exitcode = WEXITSTATUS(wstatus); - _exit(exitcode); - } - } - else - { - kill(worker_pid, SIGKILL); - wait(NULL); - _exit(1); - } - } - else - { - int wstatus; - int result = 0; - do - { - result = waitpid(pid, &wstatus, 0); - } while(result == -1 && errno == EINTR); + pid_t timeout_pid = fork(); + if(timeout_pid < 0) + { + perror("unable to fork"); + _exit(1); + } + if(timeout_pid == 0) + { + sleep(timeout); + _exit(0); + } + int wstatus; + pid_t exited_pid = wait(&wstatus); + if(exited_pid == worker_pid) + { + kill(timeout_pid, SIGKILL); + wait(NULL); + if(!WIFEXITED(wstatus)) + { + return 1; + } + else + { + int exitcode = WEXITSTATUS(wstatus); + _exit(exitcode); + } + } + else + { + kill(worker_pid, SIGKILL); + wait(NULL); + _exit(1); + } + } + else + { + int wstatus; + int result = 0; + do + { + result = waitpid(pid, &wstatus, 0); + } while(result == -1 && errno == EINTR); - if(!WIFEXITED(wstatus)) - { - return 1; - } - else - { - int exitcode = WEXITSTATUS(wstatus); - return exitcode; - } - } + if(!WIFEXITED(wstatus)) + { + return 1; + } + else + { + int exitcode = WEXITSTATUS(wstatus); + return exitcode; + } + } } @@ -104,89 +104,89 @@ int ChildProcess(string program, vector args, int timeout) bool CheckExecutable(std::string program) { - if(access(program.c_str(), X_OK) == 0) - return true; - if(program.find("/") != std::string::npos) - return false; - const char *PATH = getenv("PATH"); + if(access(program.c_str(), X_OK) == 0) + return true; + if(program.find("/") != std::string::npos) + return false; + const char *PATH = getenv("PATH"); - if(PATH) - { - bool endFound = false; - do - { - const char *end = strchr(PATH, ':'); - if(!end) - { - end = strchr(PATH, '\0'); - endFound = true; - } - std::string pathElement(PATH, end); + if(PATH) + { + bool endFound = false; + do + { + const char *end = strchr(PATH, ':'); + if(!end) + { + end = strchr(PATH, '\0'); + endFound = true; + } + std::string pathElement(PATH, end); - if(pathElement == "") - pathElement = "."; + if(pathElement == "") + pathElement = "."; - fs::path f = fs::path(pathElement) / program; + fs::path f = fs::path(pathElement) / program; - if(access(f.string().c_str(), X_OK) == 0) - return true; + if(access(f.string().c_str(), X_OK) == 0) + return true; - PATH = end + 1; - } while(!endFound); - } + PATH = end + 1; + } while(!endFound); + } - return false; + return false; } vector SplitArguments(std::string str) { - bool backslash = false; - bool quote = false; - bool begun = false; - vector args; + bool backslash = false; + bool quote = false; + bool begun = false; + vector args; - for(char c : str) - { - if(!backslash && !quote && isspace(c)) - { - begun = false; - } - else if(!backslash && c == '"') - { - quote = !quote; - if(quote && !begun) - { - args.emplace_back(); - begun = true; - } - } - else if(!backslash && c == '\\') - { - backslash = true; - } - else - { - backslash = false; + for(char c : str) + { + if(!backslash && !quote && isspace(c)) + { + begun = false; + } + else if(!backslash && c == '"') + { + quote = !quote; + if(quote && !begun) + { + args.emplace_back(); + begun = true; + } + } + else if(!backslash && c == '\\') + { + backslash = true; + } + else + { + backslash = false; - if(!begun) - { - args.emplace_back(); - begun = true; - } - args.back() += c; - } - } + if(!begun) + { + args.emplace_back(); + begun = true; + } + args.back() += c; + } + } - return args; + return args; } vector SplitArguments(vector strs) { - vector args; - for(string str : strs) - { - vector args1 = SplitArguments(str); - args.insert(args.end(), args1.begin(), args1.end()); - } - return args; + vector args; + for(string str : strs) + { + vector args1 = SplitArguments(str); + args.insert(args.end(), args1.begin(), args1.end()); + } + return args; } diff --git a/LaunchAPPL/Server/LaunchAPPLServer.cc b/LaunchAPPL/Server/LaunchAPPLServer.cc index 0108b6ce65..d4a78e5258 100644 --- a/LaunchAPPL/Server/LaunchAPPLServer.cc +++ b/LaunchAPPL/Server/LaunchAPPLServer.cc @@ -645,20 +645,20 @@ int main() #if TARGET_CPU_68K && !TARGET_RT_MAC_CFM short& ROM85 = *(short*) 0x028E; - Boolean is128KROM = (ROM85 > 0); - Boolean hasWaitNextEvent = false; + Boolean is128KROM = (ROM85 > 0); + Boolean hasWaitNextEvent = false; Boolean hasGestalt = false; Boolean hasAppleEvents = false; hasIconUtils = false; hasColorQD = false; - if (is128KROM) - { - UniversalProcPtr trapUnimpl = GetToolTrapAddress(_Unimplemented); + if (is128KROM) + { + UniversalProcPtr trapUnimpl = GetToolTrapAddress(_Unimplemented); UniversalProcPtr trapWaitNextEvent = GetToolTrapAddress(_WaitNextEvent); UniversalProcPtr trapGestalt = GetOSTrapAddress(_Gestalt); - hasWaitNextEvent = (trapWaitNextEvent != trapUnimpl); + hasWaitNextEvent = (trapWaitNextEvent != trapUnimpl); hasGestalt = (trapGestalt != trapUnimpl); if(hasGestalt) @@ -676,10 +676,10 @@ int main() err = Gestalt(gestaltStandardFileAttr, &response); hasSys7StdFile = err == noErr && (response & (1 << gestaltStandardFile58)) != 0; } - } + } #else #if !TARGET_API_MAC_CARBON - const Boolean hasWaitNextEvent = true; + const Boolean hasWaitNextEvent = true; #endif const Boolean hasGestalt = true; const Boolean hasAppleEvents = true; @@ -816,5 +816,5 @@ int main() } WritePrefs(); - return 0; + return 0; } diff --git a/LaunchAPPL/Server/MacSerialStream.cc b/LaunchAPPL/Server/MacSerialStream.cc index 34cfa2e22f..fbc45d0237 100644 --- a/LaunchAPPL/Server/MacSerialStream.cc +++ b/LaunchAPPL/Server/MacSerialStream.cc @@ -67,7 +67,7 @@ void MacSerialStream::write(const void* p, size_t n) pb.ioParam.ioRefNum = outRefNum; pb.ioParam.ioBuffer = (Ptr)p; pb.ioParam.ioReqCount = n; - /*OSErr err =*/ PBWriteSync(&pb); + /*OSErr err =*/ PBWriteSync(&pb); } void MacSerialStream::idle() diff --git a/LaunchAPPL/Server/MacTCPStream.cc b/LaunchAPPL/Server/MacTCPStream.cc index 5953d553d6..0207e40304 100644 --- a/LaunchAPPL/Server/MacTCPStream.cc +++ b/LaunchAPPL/Server/MacTCPStream.cc @@ -48,13 +48,13 @@ void MacTCPStream::startListening() readPB.ioCRefNum = refNum; readPB.tcpStream = tcpStream; - readPB.csCode = TCPPassiveOpen; - readPB.ioResult = 1; - readPB.csParam.open.ulpTimeoutValue = 5;// ### - readPB.csParam.open.ulpTimeoutAction = 1; - readPB.csParam.open.validityFlags = 0xC0; - readPB.csParam.open.commandTimeoutValue = 0; - readPB.csParam.open.localPort = 1984; + readPB.csCode = TCPPassiveOpen; + readPB.ioResult = 1; + readPB.csParam.open.ulpTimeoutValue = 5;// ### + readPB.csParam.open.ulpTimeoutAction = 1; + readPB.csParam.open.validityFlags = 0xC0; + readPB.csParam.open.commandTimeoutValue = 0; + readPB.csParam.open.localPort = 1984; PBControlAsync((ParmBlkPtr)&readPB); } @@ -74,7 +74,7 @@ MacTCPStream::~MacTCPStream() memset(&pb, 0, sizeof(pb)); pb.ioCRefNum = refNum; pb.tcpStream = tcpStream; - pb.csCode = TCPRelease; + pb.csCode = TCPRelease; PBControlSync((ParmBlkPtr)&pb); } diff --git a/LaunchAPPL/Server/OpenTptStream.cc b/LaunchAPPL/Server/OpenTptStream.cc index 5aa56587f3..aee07695cc 100644 --- a/LaunchAPPL/Server/OpenTptStream.cc +++ b/LaunchAPPL/Server/OpenTptStream.cc @@ -110,7 +110,7 @@ OpenTptStream::~OpenTptStream() { endpoint->SetNonBlocking(); if(connected) - endpoint->SndDisconnect(&call); + endpoint->SndDisconnect(&call); endpoint->Unbind(); OTCloseProvider(endpoint); } diff --git a/PEFTools/MakeImport.cc b/PEFTools/MakeImport.cc index 5539c335dc..79085469b9 100755 --- a/PEFTools/MakeImport.cc +++ b/PEFTools/MakeImport.cc @@ -40,328 +40,328 @@ bool verboseFlag = false; struct CFragMember { - string name; - uint32_t architecture; - uint8_t usage; - char *data; - uint32_t length; - - CFragMember() : architecture(0), usage(0), data(0), length(0) {} - CFragMember(string n, uint32_t a, uint8_t u, char *d, uint32_t l) - : name(n), architecture(a), usage(u), data(d), length(l) - { - } + string name; + uint32_t architecture; + uint8_t usage; + char *data; + uint32_t length; + + CFragMember() : architecture(0), usage(0), data(0), length(0) {} + CFragMember(string n, uint32_t a, uint8_t u, char *d, uint32_t l) + : name(n), architecture(a), usage(u), data(d), length(l) + { + } }; void RunCommand(const char *command, std::vector args) { - std::vector ptrs; - ptrs.push_back(command); - for(auto& s : args) - ptrs.push_back(s.c_str()); - ptrs.push_back(NULL); + std::vector ptrs; + ptrs.push_back(command); + for(auto& s : args) + ptrs.push_back(s.c_str()); + ptrs.push_back(NULL); - pid_t pid = fork(); - if(pid == -1) - { - perror(command); - exit(1); - } + pid_t pid = fork(); + if(pid == -1) + { + perror(command); + exit(1); + } - if(pid) - { - int status = 0; - while(waitpid(pid, &status, 0) == -1 && errno == EINTR) - ; - if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) - { - std::cerr << command << " failed.\n"; - exit(1); - } - } - else - { - execvp(command, const_cast(ptrs.data())); - perror("exec"); - exit(1); - } + if(pid) + { + int status = 0; + while(waitpid(pid, &status, 0) == -1 && errno == EINTR) + ; + if(!WIFEXITED(status) || WEXITSTATUS(status) != 0) + { + std::cerr << command << " failed.\n"; + exit(1); + } + } + else + { + execvp(command, const_cast(ptrs.data())); + perror("exec"); + exit(1); + } } void MakeImportLibrary(char *pefptr, size_t pefsize, fs::path dest, fs::path tmpdir) { - PEFContainerHeader *containerHeader = (PEFContainerHeader*) pefptr; - eswap(containerHeader); + PEFContainerHeader *containerHeader = (PEFContainerHeader*) pefptr; + eswap(containerHeader); - assert(containerHeader->tag1 == 'Joy!'); - assert(containerHeader->tag2 == 'peff'); + assert(containerHeader->tag1 == 'Joy!'); + assert(containerHeader->tag2 == 'peff'); - PEFSectionHeader *sectionHeaders - = (PEFSectionHeader*) (pefptr + kPEFFirstSectionHeaderOffset); + PEFSectionHeader *sectionHeaders + = (PEFSectionHeader*) (pefptr + kPEFFirstSectionHeaderOffset); - PEFSectionHeader *loaderHeader = NULL; - UInt16 n = containerHeader->sectionCount; - for(UInt16 i=0; i < n; i++) - { - eswap(§ionHeaders[i]); - if(sectionHeaders[i].sectionKind == kPEFLoaderSection) - loaderHeader = §ionHeaders[i]; - } + PEFSectionHeader *loaderHeader = NULL; + UInt16 n = containerHeader->sectionCount; + for(UInt16 i=0; i < n; i++) + { + eswap(§ionHeaders[i]); + if(sectionHeaders[i].sectionKind == kPEFLoaderSection) + loaderHeader = §ionHeaders[i]; + } - PEFLoaderInfoHeader *loaderInfoHeader - = (PEFLoaderInfoHeader*) (pefptr + loaderHeader->containerOffset); - eswap(loaderInfoHeader); - - UInt32 hashTableSize = 1; - UInt32 hashTablePower = loaderInfoHeader->exportHashTablePower; - while(hashTablePower--) - hashTableSize *= 2; - - UInt32 nSymbols = loaderInfoHeader->exportedSymbolCount; - - const char *symbols /* use char pointer to avoid packing issues */ - = (pefptr + loaderHeader->containerOffset - + loaderInfoHeader->exportHashOffset - + hashTableSize * sizeof(PEFExportedSymbolHashSlot) - + nSymbols * sizeof(PEFExportedSymbolKey)); - - const char *stringTable = pefptr - + loaderHeader->containerOffset - + loaderInfoHeader->loaderStringsOffset; - /*const char *stringTableEnd = pefptr - + loaderHeader->containerOffset - + loaderInfoHeader->exportHashOffset;*/ - vector< pair< const char *, UInt8 > > classesAndNamePtrs; - - for(UInt32 i=0; i < nSymbols; i++) - { - PEFExportedSymbol *sym = (PEFExportedSymbol*) (symbols + 10*i); - eswap(sym); + PEFLoaderInfoHeader *loaderInfoHeader + = (PEFLoaderInfoHeader*) (pefptr + loaderHeader->containerOffset); + eswap(loaderInfoHeader); + + UInt32 hashTableSize = 1; + UInt32 hashTablePower = loaderInfoHeader->exportHashTablePower; + while(hashTablePower--) + hashTableSize *= 2; + + UInt32 nSymbols = loaderInfoHeader->exportedSymbolCount; + + const char *symbols /* use char pointer to avoid packing issues */ + = (pefptr + loaderHeader->containerOffset + + loaderInfoHeader->exportHashOffset + + hashTableSize * sizeof(PEFExportedSymbolHashSlot) + + nSymbols * sizeof(PEFExportedSymbolKey)); + + const char *stringTable = pefptr + + loaderHeader->containerOffset + + loaderInfoHeader->loaderStringsOffset; + /*const char *stringTableEnd = pefptr + + loaderHeader->containerOffset + + loaderInfoHeader->exportHashOffset;*/ + vector< pair< const char *, UInt8 > > classesAndNamePtrs; + + for(UInt32 i=0; i < nSymbols; i++) + { + PEFExportedSymbol *sym = (PEFExportedSymbol*) (symbols + 10*i); + eswap(sym); - UInt8 symclass = PEFExportedSymbolClass(sym->classAndName); - UInt32 nameoffset = PEFExportedSymbolNameOffset(sym->classAndName); - - const char *nameptr - = stringTable + nameoffset; - - classesAndNamePtrs.push_back( make_pair(nameptr, symclass) ); - } - std::sort(classesAndNamePtrs.begin(), classesAndNamePtrs.end()); - - vector< pair > exportedSymbols; - for(UInt32 i=0; i < nSymbols; i++) - { - UInt8 symclass = classesAndNamePtrs[i].second; - const char *namestart = classesAndNamePtrs[i].first; - - string name; - if(i + 1 < nSymbols) - { - const char *nameend = classesAndNamePtrs[i+1].first; - name = string(namestart,nameend); - } - else - name = string(namestart); - - exportedSymbols.push_back( make_pair( name, symclass ) ); - } - std::sort(exportedSymbols.begin(), exportedSymbols.end()); - - fs::path stub_exp(tmpdir / "__stub.exp"), - stub_s(tmpdir / "__stub.s"), - stub_o(tmpdir / "__stub.o"); + UInt8 symclass = PEFExportedSymbolClass(sym->classAndName); + UInt32 nameoffset = PEFExportedSymbolNameOffset(sym->classAndName); + + const char *nameptr + = stringTable + nameoffset; + + classesAndNamePtrs.push_back( make_pair(nameptr, symclass) ); + } + std::sort(classesAndNamePtrs.begin(), classesAndNamePtrs.end()); + + vector< pair > exportedSymbols; + for(UInt32 i=0; i < nSymbols; i++) + { + UInt8 symclass = classesAndNamePtrs[i].second; + const char *namestart = classesAndNamePtrs[i].first; + + string name; + if(i + 1 < nSymbols) + { + const char *nameend = classesAndNamePtrs[i+1].first; + name = string(namestart,nameend); + } + else + name = string(namestart); + + exportedSymbols.push_back( make_pair( name, symclass ) ); + } + std::sort(exportedSymbols.begin(), exportedSymbols.end()); + + fs::path stub_exp(tmpdir / "__stub.exp"), + stub_s(tmpdir / "__stub.s"), + stub_o(tmpdir / "__stub.o"); - { - fs::ofstream expFile(stub_exp); - fs::ofstream sFile(stub_s); - sFile << "\t.toc\n"; - for(UInt32 i=0; i< nSymbols; i++) - { - string& sym = exportedSymbols[i].first; - if(exportedSymbols[i].second == kPEFTVectorSymbol) - { - expFile << sym << endl; - sFile << ".text" << endl; - sFile << "\t.globl " << sym << endl; - sFile << "\t.globl ." << sym << endl; - sFile << "\t.csect " << sym << "[DS]" << endl; - sFile << sym << ':' << endl; - sFile << ".long ." << sym << ", TOC[tc0], 0" << endl; - sFile << ".text" << endl; - sFile << '.' << sym << ':' << endl; - sFile << "\tblr" << endl; - } - else if(exportedSymbols[i].second == kPEFDataSymbol) - { - expFile << sym << endl; - sFile << "\t.globl " << sym << endl; - sFile << "\t.csect .data[RW],3" << endl; - sFile << "\t.align 2" << endl; - sFile << sym << ':' << endl; - sFile << "\t.long\t42" << endl; - } - } - - //cerr << "Generating: " << name << " -> " << libname << endl; - RunCommand("powerpc-apple-macos-as", std::vector { - stub_s.string(), "-o", stub_o.string() - }); - RunCommand("powerpc-apple-macos-ld", std::vector { - "-shared", "--no-check-sections", "-bexport:" + stub_exp.string(), - "-o", dest.string(), stub_o.string() - }); - } + { + fs::ofstream expFile(stub_exp); + fs::ofstream sFile(stub_s); + sFile << "\t.toc\n"; + for(UInt32 i=0; i< nSymbols; i++) + { + string& sym = exportedSymbols[i].first; + if(exportedSymbols[i].second == kPEFTVectorSymbol) + { + expFile << sym << endl; + sFile << ".text" << endl; + sFile << "\t.globl " << sym << endl; + sFile << "\t.globl ." << sym << endl; + sFile << "\t.csect " << sym << "[DS]" << endl; + sFile << sym << ':' << endl; + sFile << ".long ." << sym << ", TOC[tc0], 0" << endl; + sFile << ".text" << endl; + sFile << '.' << sym << ':' << endl; + sFile << "\tblr" << endl; + } + else if(exportedSymbols[i].second == kPEFDataSymbol) + { + expFile << sym << endl; + sFile << "\t.globl " << sym << endl; + sFile << "\t.csect .data[RW],3" << endl; + sFile << "\t.align 2" << endl; + sFile << sym << ':' << endl; + sFile << "\t.long\t42" << endl; + } + } + + //cerr << "Generating: " << name << " -> " << libname << endl; + RunCommand("powerpc-apple-macos-as", std::vector { + stub_s.string(), "-o", stub_o.string() + }); + RunCommand("powerpc-apple-macos-ld", std::vector { + "-shared", "--no-check-sections", "-bexport:" + stub_exp.string(), + "-o", dest.string(), stub_o.string() + }); + } } bool MakeImportLibraryMulti(fs::path path, fs::path libname) { - ResourceFile resFile(path.string()); - assert(resFile.read()); + ResourceFile resFile(path.string()); + assert(resFile.read()); - std::vector data(resFile.data.begin(), resFile.data.end()); + std::vector data(resFile.data.begin(), resFile.data.end()); - char *dataPtr = data.data(); - - std::vector members; + char *dataPtr = data.data(); + + std::vector members; - if(data.size() < 8 || std::string(data.begin(), data.begin()+8) != "Joy!peff") - { - std::cerr << "Not a PEF shared library. Ignoring.\n"; - return false; - } - - if(resFile.resources.resources.find(ResRef("cfrg",0)) == resFile.resources.resources.end()) - { - std::cerr << "No 'cfrg' resource found.\n"; - exit(1); - } + if(data.size() < 8 || std::string(data.begin(), data.begin()+8) != "Joy!peff") + { + std::cerr << "Not a PEF shared library. Ignoring.\n"; + return false; + } + + if(resFile.resources.resources.find(ResRef("cfrg",0)) == resFile.resources.resources.end()) + { + std::cerr << "No 'cfrg' resource found.\n"; + exit(1); + } - Resource& cfrgRes = resFile.resources.resources[ResRef("cfrg",0)]; + Resource& cfrgRes = resFile.resources.resources[ResRef("cfrg",0)]; - CFragResource *cfrg = (CFragResource *)cfrgRes.getData().data(); - eswap(cfrg); + CFragResource *cfrg = (CFragResource *)cfrgRes.getData().data(); + eswap(cfrg); - CFragResourceMember *member = &(cfrg -> firstMember); + CFragResourceMember *member = &(cfrg -> firstMember); - for(UInt16 i = 0; i < cfrg->memberCount; i++) - { - eswap(member); - string membername = - string(member->name+1, member->name+1+member->name[0]); - members.emplace_back( - membername, - member->architecture, - member->usage, - dataPtr + member->offset, - member->length); + for(UInt16 i = 0; i < cfrg->memberCount; i++) + { + eswap(member); + string membername = + string(member->name+1, member->name+1+member->name[0]); + members.emplace_back( + membername, + member->architecture, + member->usage, + dataPtr + member->offset, + member->length); - member = (CFragResourceMember*) (((char*)member) + member->memberSize); - } + member = (CFragResourceMember*) (((char*)member) + member->memberSize); + } - if(!std::any_of(members.begin(), members.end(), [](const auto& member) { - return member.architecture == 'pwpc' || member.architecture == '\?\?\?\?'; - })) - { - std::cerr << "Does not contain a PowerPC variant. Ignoring.\n"; - return false; - } + if(!std::any_of(members.begin(), members.end(), [](const auto& member) { + return member.architecture == 'pwpc' || member.architecture == '\?\?\?\?'; + })) + { + std::cerr << "Does not contain a PowerPC variant. Ignoring.\n"; + return false; + } - fs::path tmpdir = libname.parent_path() / fs::unique_path("makeimport-tmp-%%%%-%%%%-%%%%-%%%%"); - fs::create_directory(tmpdir); - try - { - fs::path archiveTmp(tmpdir / "__archive.a"); - std::vector arArguments { "cq", archiveTmp.string() }; + fs::path tmpdir = libname.parent_path() / fs::unique_path("makeimport-tmp-%%%%-%%%%-%%%%-%%%%"); + fs::create_directory(tmpdir); + try + { + fs::path archiveTmp(tmpdir / "__archive.a"); + std::vector arArguments { "cq", archiveTmp.string() }; - int memberIndex = 0; - - for(auto &member : members) - { - std::ostringstream memberNameStream; - - // classic MacOS shared library names are in MacRoman and - // may contain wierd characters; the shared library name is used - // as the file name for the archive member, so there can be problems. - // - // We encode the file name to hex (and add a human readable name). - // MakePEF contains corresponding decoder logic. - - memberNameStream << "imp__"; - - for(char c : member.name) - { - if(isalnum(c)) - memberNameStream << c; - } - memberNameStream << "_"; - for(char c : member.name) - { - int cc = (unsigned char) c; - memberNameStream << std::setw(2) << std::setfill('0') << std::hex - << cc; - } - memberNameStream << "_" << memberIndex++; - string memberName = memberNameStream.str(); - - if(member.usage == 0 /* import library */ - || member.usage == 3 /* stub library */) - ; - else if(member.usage == 4 /* weak stub library */) - memberName += "__weak"; - - if(verboseFlag) - { - char archStr[5]; - archStr[0] = member.architecture >> 24; - archStr[1] = member.architecture >> 16; - archStr[2] = member.architecture >> 8; - archStr[3] = member.architecture; - archStr[4] = 0; - std::cerr << memberName << " (" << archStr << ")\n"; - } - - if(member.architecture == 'pwpc' - || member.architecture == '\?\?\?\?') - { + int memberIndex = 0; + + for(auto &member : members) + { + std::ostringstream memberNameStream; + + // classic MacOS shared library names are in MacRoman and + // may contain wierd characters; the shared library name is used + // as the file name for the archive member, so there can be problems. + // + // We encode the file name to hex (and add a human readable name). + // MakePEF contains corresponding decoder logic. + + memberNameStream << "imp__"; + + for(char c : member.name) + { + if(isalnum(c)) + memberNameStream << c; + } + memberNameStream << "_"; + for(char c : member.name) + { + int cc = (unsigned char) c; + memberNameStream << std::setw(2) << std::setfill('0') << std::hex + << cc; + } + memberNameStream << "_" << memberIndex++; + string memberName = memberNameStream.str(); + + if(member.usage == 0 /* import library */ + || member.usage == 3 /* stub library */) + ; + else if(member.usage == 4 /* weak stub library */) + memberName += "__weak"; + + if(verboseFlag) + { + char archStr[5]; + archStr[0] = member.architecture >> 24; + archStr[1] = member.architecture >> 16; + archStr[2] = member.architecture >> 8; + archStr[3] = member.architecture; + archStr[4] = 0; + std::cerr << memberName << " (" << archStr << ")\n"; + } + + if(member.architecture == 'pwpc' + || member.architecture == '\?\?\?\?') + { - fs::path shlib_file(tmpdir / (memberName + ".o")); - MakeImportLibrary(member.data, member.length, - shlib_file, tmpdir); - arArguments.push_back(shlib_file.string()); - } - } + fs::path shlib_file(tmpdir / (memberName + ".o")); + MakeImportLibrary(member.data, member.length, + shlib_file, tmpdir); + arArguments.push_back(shlib_file.string()); + } + } - RunCommand("powerpc-apple-macos-ar", arArguments); - fs::rename(archiveTmp, libname); - } - catch(...) - { - fs::remove_all(tmpdir); - throw; - } - fs::remove_all(tmpdir); + RunCommand("powerpc-apple-macos-ar", arArguments); + fs::rename(archiveTmp, libname); + } + catch(...) + { + fs::remove_all(tmpdir); + throw; + } + fs::remove_all(tmpdir); - return true; + return true; } int main (int argc, char * const argv[]) { - //printf("%d\n",argc); - if(argc != 3) - { - cerr << "Usage: makeimport " << endl; - return 1; - } - - int fd = open(argv[1], O_RDONLY, 0); - if(fd < 0) - { - perror(argv[1]); - return 1; - } - - if(!MakeImportLibraryMulti(argv[1], argv[2])) + //printf("%d\n",argc); + if(argc != 3) + { + cerr << "Usage: makeimport " << endl; + return 1; + } + + int fd = open(argv[1], O_RDONLY, 0); + if(fd < 0) + { + perror(argv[1]); + return 1; + } + + if(!MakeImportLibraryMulti(argv[1], argv[2])) return 1; - close(fd); + close(fd); return 0; } diff --git a/PEFTools/MakePEF.cc b/PEFTools/MakePEF.cc index dbd80f25dd..8060795320 100755 --- a/PEFTools/MakePEF.cc +++ b/PEFTools/MakePEF.cc @@ -31,520 +31,520 @@ bool verboseFlag = false; inline int getI16(const void *xx) { - const unsigned char *x = (const unsigned char*)xx; - return (x[0] << 8) | x[1]; + const unsigned char *x = (const unsigned char*)xx; + return (x[0] << 8) | x[1]; } inline int getI32(const void *xx) { - const unsigned char *x = (const unsigned char*)xx; - return (x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]; + const unsigned char *x = (const unsigned char*)xx; + return (x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]; } inline int getI8(const void *xx) { - return *(const unsigned char*)xx; + return *(const unsigned char*)xx; } template inline int get(const ch (&x) [n]) { - switch(n) - { - case 1: return getI8(x); - case 2: return getI16(x); - case 4: return getI32(x); - default: abort(); - } + switch(n) + { + case 1: return getI8(x); + case 2: return getI16(x); + case 4: return getI32(x); + default: abort(); + } } class ImportLib { public: - std::string path, base, mem; - std::vector imports; - std::vector xcoffImportIndices; + std::string path, base, mem; + std::vector imports; + std::vector xcoffImportIndices; - int nameOffset; - bool weak; - - std::vector symNameOffsets; - - ImportLib(std::string path, std::string base, std::string mem) - : path(path), base(base), mem(mem), weak(false) - { - } + int nameOffset; + bool weak; + + std::vector symNameOffsets; + + ImportLib(std::string path, std::string base, std::string mem) + : path(path), base(base), mem(mem), weak(false) + { + } }; void mkpef(const std::string& inFn, const std::string& outFn) { - std::ifstream in(inFn); + std::ifstream in(inFn); - external_filehdr xcoffHeader; - external_aouthdr aoutHeader; + external_filehdr xcoffHeader; + external_aouthdr aoutHeader; - in.read((char*) &xcoffHeader, sizeof(xcoffHeader)); - assert((size_t)get(xcoffHeader.f_opthdr) >= sizeof(aoutHeader)); - in.read((char*)&aoutHeader, sizeof(aoutHeader)); - in.seekg(get(xcoffHeader.f_opthdr) - sizeof(aoutHeader),std::ios_base::cur); - - if(verboseFlag) - { - std::cerr << "flags: " << std::hex << get(xcoffHeader.f_flags) << std::dec << std::endl; - std::cerr << "symptr: " << get(xcoffHeader.f_symptr) << std::endl; - std::cerr << "nsyms: " << get(xcoffHeader.f_nsyms) << std::endl; - } + in.read((char*) &xcoffHeader, sizeof(xcoffHeader)); + assert((size_t)get(xcoffHeader.f_opthdr) >= sizeof(aoutHeader)); + in.read((char*)&aoutHeader, sizeof(aoutHeader)); + in.seekg(get(xcoffHeader.f_opthdr) - sizeof(aoutHeader),std::ios_base::cur); + + if(verboseFlag) + { + std::cerr << "flags: " << std::hex << get(xcoffHeader.f_flags) << std::dec << std::endl; + std::cerr << "symptr: " << get(xcoffHeader.f_symptr) << std::endl; + std::cerr << "nsyms: " << get(xcoffHeader.f_nsyms) << std::endl; + } - std::map xcoffSections; - std::map xcoffSectionNumbers; + std::map xcoffSections; + std::map xcoffSectionNumbers; - int nSections = get(xcoffHeader.f_nscns); - for(int i=0;i importLibs; - std::vector importedSymbolIndices; - int totalImportedSyms = 0; + std::vector importLibs; + std::vector importedSymbolIndices; + int totalImportedSyms = 0; - std::vector relocInstructions; + std::vector relocInstructions; - { - external_scnhdr xcoffLoaderSection = xcoffSections[".loader"]; - external_ldhdr xcoffLoaderHeader; + { + external_scnhdr xcoffLoaderSection = xcoffSections[".loader"]; + external_ldhdr xcoffLoaderHeader; - char * loaderSectionPtr = (char*)alloca(get(xcoffLoaderSection.s_size)); - in.seekg(get(xcoffLoaderSection.s_scnptr)); - in.read(loaderSectionPtr, get(xcoffLoaderSection.s_size)); - - xcoffLoaderHeader = *(external_ldhdr*)loaderSectionPtr; + char * loaderSectionPtr = (char*)alloca(get(xcoffLoaderSection.s_size)); + in.seekg(get(xcoffLoaderSection.s_scnptr)); + in.read(loaderSectionPtr, get(xcoffLoaderSection.s_size)); + + xcoffLoaderHeader = *(external_ldhdr*)loaderSectionPtr; - char *p = loaderSectionPtr + get(xcoffLoaderHeader.l_impoff); - for(int i=0; i loaderStringTable; - int loaderStringTableSize = 0; - - for(unsigned i=1;i loaderStringTable; + int loaderStringTableSize = 0; + + for(unsigned i=1;i 6) - { - if(name.substr(name.length()-6,6) == "__weak") - { - name = name.substr(0,name.length()-6); - imp.weak = true; - } - } - - if(name.length() > 5) - { - // the shared library name has been encoded as hex by MakeImport - // in order to avoid potential file name issues - // classic MacOS shared library names are in MacRoman and - // may contain wierd characters; the shared library name is used - // as the file name for the archive member, so there can be problems. - if(name.substr(0,5) == "imp__") - { - std::string realName; - - int i; - int n = name.size(); - for(i = 5; i < n && name[i] != '_'; i++) - ; - ++i; - for(; i + 1 < n && name[i] != '_'; i+=2) - { - char c1 = tolower(name[i]); - char c2 = tolower(name[i+1]); - assert(isdigit(c1) || (c1 >= 'a' && c1 <= 'f')); - assert(isdigit(c2) || (c2 >= 'a' && c2 <= 'f')); - int c = (c1 >= 'a' ? c1 - 'a' + 10 : c1 - '0') * 16 - + (c2 >= 'a' ? c2 - 'a' + 10 : c2 - '0'); - realName += (char)c; - } - name = realName; - } - } - - if(verboseFlag) - { - std::cerr << "PEF name \"" << name << '"'; - if(imp.weak) - std::cerr << " (weak)"; - std::cerr << " at " << std::hex << loaderStringTableSize << std::dec - << std::endl; - } - importLibs[i].nameOffset = loaderStringTableSize; - loaderStringTable.push_back(name); - loaderStringTableSize += name.length() + 1; - - for(unsigned j=0;j 6) + { + if(name.substr(name.length()-6,6) == "__weak") + { + name = name.substr(0,name.length()-6); + imp.weak = true; + } + } + + if(name.length() > 5) + { + // the shared library name has been encoded as hex by MakeImport + // in order to avoid potential file name issues + // classic MacOS shared library names are in MacRoman and + // may contain wierd characters; the shared library name is used + // as the file name for the archive member, so there can be problems. + if(name.substr(0,5) == "imp__") + { + std::string realName; + + int i; + int n = name.size(); + for(i = 5; i < n && name[i] != '_'; i++) + ; + ++i; + for(; i + 1 < n && name[i] != '_'; i+=2) + { + char c1 = tolower(name[i]); + char c2 = tolower(name[i+1]); + assert(isdigit(c1) || (c1 >= 'a' && c1 <= 'f')); + assert(isdigit(c2) || (c2 >= 'a' && c2 <= 'f')); + int c = (c1 >= 'a' ? c1 - 'a' + 10 : c1 - '0') * 16 + + (c2 >= 'a' ? c2 - 'a' + 10 : c2 - '0'); + realName += (char)c; + } + name = realName; + } + } + + if(verboseFlag) + { + std::cerr << "PEF name \"" << name << '"'; + if(imp.weak) + std::cerr << " (weak)"; + std::cerr << " at " << std::hex << loaderStringTableSize << std::dec + << std::endl; + } + importLibs[i].nameOffset = loaderStringTableSize; + loaderStringTable.push_back(name); + loaderStringTableSize += name.length() + 1; + + for(unsigned j=0;j= argc) - { - std::cerr << "makepef: -o requires an argument.\n"; - return 1; - } - if(hadOutput) - { - std::cerr << "makepef: -o can only be used once.\n"; - return 1; - } - outputFn = argv[i]; - hadOutput = true; - } - else - { - if(hadInput) - { - std::cerr << "makepef: can only handle one input file.\n"; - return 1; - } - inputFn = argv[i]; - hadInput = true; - } - } - if(!hadInput) - { - std::cerr << "makepef: no input file specified.\n"; - return 1; - } - - if(!hadOutput) - { - std::cerr << "makepef: no output file specified.\n"; - return 1; - } - mkpef(inputFn, outputFn); + bool hadInput = false; + std::string inputFn; + bool hadOutput = false; + std::string outputFn = ""; + + for(int i=1;i= argc) + { + std::cerr << "makepef: -o requires an argument.\n"; + return 1; + } + if(hadOutput) + { + std::cerr << "makepef: -o can only be used once.\n"; + return 1; + } + outputFn = argv[i]; + hadOutput = true; + } + else + { + if(hadInput) + { + std::cerr << "makepef: can only handle one input file.\n"; + return 1; + } + inputFn = argv[i]; + hadInput = true; + } + } + if(!hadInput) + { + std::cerr << "makepef: no input file specified.\n"; + return 1; + } + + if(!hadOutput) + { + std::cerr << "makepef: no output file specified.\n"; + return 1; + } + mkpef(inputFn, outputFn); return 0; } diff --git a/PEFTools/PEF.h b/PEFTools/PEF.h index c9d0ef7da4..ebc0d417dd 100644 --- a/PEFTools/PEF.h +++ b/PEFTools/PEF.h @@ -21,9 +21,9 @@ */ #define __MACTYPES__ #define __TYPES__ -typedef uint8_t UInt8; -typedef int8_t SInt8; -typedef uint16_t UInt16; +typedef uint8_t UInt8; +typedef int8_t SInt8; +typedef uint16_t UInt16; typedef int16_t SInt16; typedef uint32_t UInt32; typedef int32_t SInt32; @@ -46,55 +46,55 @@ typedef struct {} FSSpec, *FSSpecPtr; /* Deal with differences between versions of PEFBinaryFormat.h */ #ifndef PEFRelocComposeSetPosition_1st #define PEFRelocComposeSetPosition_1st(fullOffset) \ - ( 0xA000 | ((UInt16) (((UInt32)(fullOffset)) >> 16) ) ) + ( 0xA000 | ((UInt16) (((UInt32)(fullOffset)) >> 16) ) ) #define PEFRelocComposeSetPosition_2nd(fullOffset) \ - ( (UInt16) ((UInt32)(fullOffset) & 0xFFFF) ) + ( (UInt16) ((UInt32)(fullOffset) & 0xFFFF) ) #define PEFRelocComposeLgByImport_1st(fullIndex) \ - ( 0xA400 | ((UInt16) (((UInt32)(fullIndex)) >> 16) ) ) + ( 0xA400 | ((UInt16) (((UInt32)(fullIndex)) >> 16) ) ) #define PEFRelocComposeLgByImport_2nd(fullIndex) \ - ( (UInt16) ((UInt32)(fullIndex) & 0xFFFF) ) + ( (UInt16) ((UInt32)(fullIndex) & 0xFFFF) ) #endif template void eswap(T *data, const char * format) { - int endianTest = 1; - if(*(char*)&endianTest == 0) - return; + int endianTest = 1; + if(*(char*)&endianTest == 0) + return; - char *p = reinterpret_cast(data); - const char *q = format; - while(char c = *q++) - { - assert(p <= reinterpret_cast(data) + sizeof(T)); - if(c == 'L') - { - std::swap(p[0], p[3]); - std::swap(p[1], p[2]); - p += 4; - } - else if(c == 's') - { - std::swap(p[0], p[1]); - p += 2; - } - else if(c == '*') - { - return; - } - else - { - assert(c == '.'); - ++p; - } - } + char *p = reinterpret_cast(data); + const char *q = format; + while(char c = *q++) + { + assert(p <= reinterpret_cast(data) + sizeof(T)); + if(c == 'L') + { + std::swap(p[0], p[3]); + std::swap(p[1], p[2]); + p += 4; + } + else if(c == 's') + { + std::swap(p[0], p[1]); + p += 2; + } + else if(c == '*') + { + return; + } + else + { + assert(c == '.'); + ++p; + } + } - assert(p == reinterpret_cast(data) + sizeof(T)); + assert(p == reinterpret_cast(data) + sizeof(T)); } #define DEFINE_ESWAP(T, S) \ - inline void eswap(T* data) { eswap(data, S); } + inline void eswap(T* data) { eswap(data, S); } DEFINE_ESWAP(PEFContainerHeader, "LLLLLLLLssL") DEFINE_ESWAP(PEFSectionHeader, "LLLLLL....") @@ -107,37 +107,37 @@ DEFINE_ESWAP(PEFExportedSymbol, "LLs") struct CFragResourceMember { - uint32_t architecture; - uint16_t reservedA; - uint8_t reservedB; - uint8_t updateLevel; - uint32_t currentVersion; - uint32_t oldDefVersion; - uint32_t uUsage1; - uint16_t uUsage2; - uint8_t usage; - uint8_t where; - uint32_t offset; - uint32_t length; - uint32_t uWhere1; - uint16_t uWhere2; - uint16_t extensionCount; - uint16_t memberSize; - unsigned char name[16]; + uint32_t architecture; + uint16_t reservedA; + uint8_t reservedB; + uint8_t updateLevel; + uint32_t currentVersion; + uint32_t oldDefVersion; + uint32_t uUsage1; + uint16_t uUsage2; + uint8_t usage; + uint8_t where; + uint32_t offset; + uint32_t length; + uint32_t uWhere1; + uint16_t uWhere2; + uint16_t extensionCount; + uint16_t memberSize; + unsigned char name[16]; }; struct CFragResource { - uint32_t reservedA; - uint32_t reservedB; - uint16_t reservedC; - uint16_t version; - uint32_t reservedD; - uint32_t reservedE; - uint32_t reservedF; - uint32_t reservedG; - uint16_t reservedH; - uint16_t memberCount; - CFragResourceMember firstMember; + uint32_t reservedA; + uint32_t reservedB; + uint16_t reservedC; + uint16_t version; + uint32_t reservedD; + uint32_t reservedE; + uint32_t reservedF; + uint32_t reservedG; + uint16_t reservedH; + uint16_t memberCount; + CFragResourceMember firstMember; }; diff --git a/PEFTools/rs6000.h b/PEFTools/rs6000.h index acb6f0ca12..02b66b1985 100644 --- a/PEFTools/rs6000.h +++ b/PEFTools/rs6000.h @@ -21,13 +21,13 @@ /********************** FILE HEADER **********************/ struct external_filehdr { - char f_magic[2]; /* magic number */ - char f_nscns[2]; /* number of sections */ - char f_timdat[4]; /* time & date stamp */ - char f_symptr[4]; /* file pointer to symtab */ - char f_nsyms[4]; /* number of symtab entries */ - char f_opthdr[2]; /* sizeof(optional hdr) */ - char f_flags[2]; /* flags */ + char f_magic[2]; /* magic number */ + char f_nscns[2]; /* number of sections */ + char f_timdat[4]; /* time & date stamp */ + char f_symptr[4]; /* file pointer to symtab */ + char f_nsyms[4]; /* number of symtab entries */ + char f_opthdr[2]; /* sizeof(optional hdr) */ + char f_flags[2]; /* flags */ }; /* IBM RS/6000 */ @@ -35,12 +35,12 @@ struct external_filehdr { #define U802ROMAGIC 0735 /* readonly sharable text segments */ #define U802TOCMAGIC 0737 /* readonly text segments and TOC */ -#define BADMAG(x) \ - ((x).f_magic != U802ROMAGIC && (x).f_magic != U802WRMAGIC && \ - (x).f_magic != U802TOCMAGIC) +#define BADMAG(x) \ + ((x).f_magic != U802ROMAGIC && (x).f_magic != U802WRMAGIC && \ + (x).f_magic != U802TOCMAGIC) -#define FILHDR struct external_filehdr -#define FILHSZ 20 +#define FILHDR struct external_filehdr +#define FILHSZ 20 /********************** AOUT "OPTIONAL HEADER" **********************/ @@ -48,28 +48,28 @@ struct external_filehdr { typedef struct { - unsigned char magic[2]; /* type of file */ - unsigned char vstamp[2]; /* version stamp */ - unsigned char tsize[4]; /* text size in bytes, padded to FW bdry */ - unsigned char dsize[4]; /* initialized data " " */ - unsigned char bsize[4]; /* uninitialized data " " */ - unsigned char entry[4]; /* entry pt. */ - unsigned char text_start[4]; /* base of text used for this file */ - unsigned char data_start[4]; /* base of data used for this file */ - unsigned char o_toc[4]; /* address of TOC */ - unsigned char o_snentry[2]; /* section number of entry point */ - unsigned char o_sntext[2]; /* section number of .text section */ - unsigned char o_sndata[2]; /* section number of .data section */ - unsigned char o_sntoc[2]; /* section number of TOC */ - unsigned char o_snloader[2]; /* section number of .loader section */ - unsigned char o_snbss[2]; /* section number of .bss section */ - unsigned char o_algntext[2]; /* .text alignment */ - unsigned char o_algndata[2]; /* .data alignment */ - unsigned char o_modtype[2]; /* module type (??) */ - unsigned char o_cputype[2]; /* cpu type */ - unsigned char o_maxstack[4]; /* max stack size (??) */ - unsigned char o_maxdata[4]; /* max data size (??) */ - unsigned char o_resv2[12]; /* reserved */ + unsigned char magic[2]; /* type of file */ + unsigned char vstamp[2]; /* version stamp */ + unsigned char tsize[4]; /* text size in bytes, padded to FW bdry */ + unsigned char dsize[4]; /* initialized data " " */ + unsigned char bsize[4]; /* uninitialized data " " */ + unsigned char entry[4]; /* entry pt. */ + unsigned char text_start[4]; /* base of text used for this file */ + unsigned char data_start[4]; /* base of data used for this file */ + unsigned char o_toc[4]; /* address of TOC */ + unsigned char o_snentry[2]; /* section number of entry point */ + unsigned char o_sntext[2]; /* section number of .text section */ + unsigned char o_sndata[2]; /* section number of .data section */ + unsigned char o_sntoc[2]; /* section number of TOC */ + unsigned char o_snloader[2]; /* section number of .loader section */ + unsigned char o_snbss[2]; /* section number of .bss section */ + unsigned char o_algntext[2]; /* .text alignment */ + unsigned char o_algndata[2]; /* .data alignment */ + unsigned char o_modtype[2]; /* module type (??) */ + unsigned char o_cputype[2]; /* cpu type */ + unsigned char o_maxstack[4]; /* max stack size (??) */ + unsigned char o_maxdata[4]; /* max data size (??) */ + unsigned char o_resv2[12]; /* reserved */ } AOUTHDR; @@ -81,20 +81,20 @@ AOUTHDR; struct external_scnhdr { - char s_name[8]; /* section name */ - char s_paddr[4]; /* physical address, aliased s_nlib */ - char s_vaddr[4]; /* virtual address */ - char s_size[4]; /* section size */ - char s_scnptr[4]; /* file ptr to raw data for section */ - char s_relptr[4]; /* file ptr to relocation */ - char s_lnnoptr[4]; /* file ptr to line numbers */ - char s_nreloc[2]; /* number of relocation entries */ - char s_nlnno[2]; /* number of line number entries*/ - char s_flags[4]; /* flags */ + char s_name[8]; /* section name */ + char s_paddr[4]; /* physical address, aliased s_nlib */ + char s_vaddr[4]; /* virtual address */ + char s_size[4]; /* section size */ + char s_scnptr[4]; /* file ptr to raw data for section */ + char s_relptr[4]; /* file ptr to relocation */ + char s_lnnoptr[4]; /* file ptr to line numbers */ + char s_nreloc[2]; /* number of relocation entries */ + char s_nlnno[2]; /* number of line number entries*/ + char s_flags[4]; /* flags */ }; -#define SCNHDR struct external_scnhdr -#define SCNHSZ 40 +#define SCNHDR struct external_scnhdr +#define SCNHSZ 40 /********************** LINE NUMBERS **********************/ @@ -104,23 +104,23 @@ struct external_scnhdr { * symbol table index of the function name. */ struct external_lineno { - union { - char l_symndx[4]; /* function name symbol index, iff l_lnno == 0*/ - char l_paddr[4]; /* (physical) address of line number */ - } l_addr; - char l_lnno[2]; /* line number */ + union { + char l_symndx[4]; /* function name symbol index, iff l_lnno == 0*/ + char l_paddr[4]; /* (physical) address of line number */ + } l_addr; + char l_lnno[2]; /* line number */ }; -#define LINENO struct external_lineno -#define LINESZ 6 +#define LINENO struct external_lineno +#define LINESZ 6 /********************** SYMBOLS **********************/ -#define E_SYMNMLEN 8 /* # characters in a symbol name */ -#define E_FILNMLEN 14 /* # characters in a file name */ -#define E_DIMNUM 4 /* # array dimensions in auxiliary entry */ +#define E_SYMNMLEN 8 /* # characters in a symbol name */ +#define E_FILNMLEN 14 /* # characters in a file name */ +#define E_DIMNUM 4 /* # array dimensions in auxiliary entry */ struct external_syment { @@ -140,33 +140,33 @@ struct external_syment -#define N_BTMASK (017) -#define N_TMASK (060) -#define N_BTSHFT (4) -#define N_TSHIFT (2) +#define N_BTMASK (017) +#define N_TMASK (060) +#define N_BTSHFT (4) +#define N_TSHIFT (2) union external_auxent { - struct { - char x_tagndx[4]; /* str, un, or enum tag indx */ - union { - struct { - char x_lnno[2]; /* declaration line number */ - char x_size[2]; /* str/union/array size */ - } x_lnsz; - char x_fsize[4]; /* size of function */ - } x_misc; - union { - struct { /* if ISFCN, tag, or .bb */ - char x_lnnoptr[4]; /* ptr to fcn line # */ - char x_endndx[4]; /* entry ndx past block end */ - } x_fcn; - struct { /* if ISARY, up to 4 dimen. */ - char x_dimen[E_DIMNUM][2]; - } x_ary; - } x_fcnary; - char x_tvndx[2]; /* tv index */ - } x_sym; + struct { + char x_tagndx[4]; /* str, un, or enum tag indx */ + union { + struct { + char x_lnno[2]; /* declaration line number */ + char x_size[2]; /* str/union/array size */ + } x_lnsz; + char x_fsize[4]; /* size of function */ + } x_misc; + union { + struct { /* if ISFCN, tag, or .bb */ + char x_lnnoptr[4]; /* ptr to fcn line # */ + char x_endndx[4]; /* entry ndx past block end */ + } x_fcn; + struct { /* if ISARY, up to 4 dimen. */ + char x_dimen[E_DIMNUM][2]; + } x_ary; + } x_fcnary; + char x_tvndx[2]; /* tv index */ + } x_sym; struct { union { @@ -179,35 +179,35 @@ union external_auxent { char x_ftype[1]; } x_file; - struct { - char x_scnlen[4]; /* section length */ - char x_nreloc[2]; /* # relocation entries */ - char x_nlinno[2]; /* # line numbers */ - } x_scn; + struct { + char x_scnlen[4]; /* section length */ + char x_nreloc[2]; /* # relocation entries */ + char x_nlinno[2]; /* # line numbers */ + } x_scn; struct { - char x_tvfill[4]; /* tv fill value */ - char x_tvlen[2]; /* length of .tv */ - char x_tvran[2][2]; /* tv range */ - } x_tv; /* info about .tv section (in auxent of symbol .tv)) */ + char x_tvfill[4]; /* tv fill value */ + char x_tvlen[2]; /* length of .tv */ + char x_tvran[2][2]; /* tv range */ + } x_tv; /* info about .tv section (in auxent of symbol .tv)) */ - struct { - unsigned char x_scnlen[4]; - unsigned char x_parmhash[4]; - unsigned char x_snhash[2]; - unsigned char x_smtyp[1]; - unsigned char x_smclas[1]; - unsigned char x_stab[4]; - unsigned char x_snstab[2]; - } x_csect; + struct { + unsigned char x_scnlen[4]; + unsigned char x_parmhash[4]; + unsigned char x_snhash[2]; + unsigned char x_smtyp[1]; + unsigned char x_smclas[1]; + unsigned char x_stab[4]; + unsigned char x_snstab[2]; + } x_csect; }; -#define SYMENT struct external_syment -#define SYMESZ 18 -#define AUXENT union external_auxent -#define AUXESZ 18 -#define DBXMASK 0x80 /* for dbx storage mask */ +#define SYMENT struct external_syment +#define SYMESZ 18 +#define AUXENT union external_auxent +#define AUXESZ 18 +#define DBXMASK 0x80 /* for dbx storage mask */ #define SYMNAME_IN_DEBUG(symptr) ((symptr)->n_sclass & DBXMASK) @@ -255,10 +255,10 @@ struct external_ldsym { bfd_byte _l_name[E_SYMNMLEN]; struct - { - bfd_byte _l_zeroes[4]; - bfd_byte _l_offset[4]; - } _l_l; + { + bfd_byte _l_zeroes[4]; + bfd_byte _l_offset[4]; + } _l_l; } _l; bfd_byte l_value[4]; bfd_byte l_scnum[2]; diff --git a/ResourceFiles/BinaryIO.cc b/ResourceFiles/BinaryIO.cc index b8bf73b3ec..d33771299a 100644 --- a/ResourceFiles/BinaryIO.cc +++ b/ResourceFiles/BinaryIO.cc @@ -6,45 +6,45 @@ void byte(std::ostream& out, int byte) { - out.put((unsigned char)byte); + out.put((unsigned char)byte); } void word(std::ostream& out, int word) { - byte(out,(word >> 8) & 0xFF); - byte(out,word & 0xFF); + byte(out,(word >> 8) & 0xFF); + byte(out,word & 0xFF); } void ostype(std::ostream& out, ResType type) { - longword(out, type); + longword(out, type); } void longword(std::ostream& out, int longword) { - byte(out,(longword >> 24) & 0xFF); - byte(out,(longword >> 16) & 0xFF); - byte(out,(longword >> 8) & 0xFF); - byte(out,longword & 0xFF); + byte(out,(longword >> 24) & 0xFF); + byte(out,(longword >> 16) & 0xFF); + byte(out,(longword >> 8) & 0xFF); + byte(out,longword & 0xFF); } int byte(std::istream& in) { - return in.get() & 0xFF; + return in.get() & 0xFF; } int word(std::istream& in) { - int a = byte(in); - int b = byte(in); - return (a << 8) | b; + int a = byte(in); + int b = byte(in); + return (a << 8) | b; } ResType ostype(std::istream& in) { - return longword(in); + return longword(in); } int longword(std::istream& in) { - int a = byte(in); - int b = byte(in); - int c = byte(in); - int d = byte(in); - return (a << 24) | (b << 16) | (c << 8) | d; + int a = byte(in); + int b = byte(in); + int c = byte(in); + int d = byte(in); + return (a << 24) | (b << 16) | (c << 8) | d; } diff --git a/ResourceFiles/CMakeLists.txt b/ResourceFiles/CMakeLists.txt index 6458ee4e77..f500a53c76 100644 --- a/ResourceFiles/CMakeLists.txt +++ b/ResourceFiles/CMakeLists.txt @@ -18,16 +18,16 @@ find_package(Boost COMPONENTS filesystem system REQUIRED) add_library(ResourceFiles - ResourceFork.h ResourceFork.cc - BinaryIO.h BinaryIO.cc - ResType.h ResType.cc - ResourceFile.h ResourceFile.cc - ) + ResourceFork.h ResourceFork.cc + BinaryIO.h BinaryIO.cc + ResType.h ResType.cc + ResourceFile.h ResourceFile.cc + ) target_link_libraries(ResourceFiles ${Boost_LIBRARIES} ${CMAKE_INSTALL_PREFIX}/lib/libhfs.a) target_include_directories(ResourceFiles PUBLIC . - PRIVATE ${CMAKE_INSTALL_PREFIX}/include - ${Boost_INCLUDE_DIR}) + PRIVATE ${CMAKE_INSTALL_PREFIX}/include + ${Boost_INCLUDE_DIR}) find_package(Boost COMPONENTS program_options REQUIRED) diff --git a/ResourceFiles/ResInfo.cc b/ResourceFiles/ResInfo.cc index 6bc01bb72e..963d511e13 100644 --- a/ResourceFiles/ResInfo.cc +++ b/ResourceFiles/ResInfo.cc @@ -11,134 +11,134 @@ static po::options_description desc; map formats { #ifdef __APPLE__ - {"real", ResourceFile::Format::real}, + {"real", ResourceFile::Format::real}, #endif - {"macbin", ResourceFile::Format::macbin}, - {"basilisk", ResourceFile::Format::basilisk}, - {"applesingle", ResourceFile::Format::applesingle}, - {"underscore_appledouble", ResourceFile::Format::underscore_appledouble} + {"macbin", ResourceFile::Format::macbin}, + {"basilisk", ResourceFile::Format::basilisk}, + {"applesingle", ResourceFile::Format::applesingle}, + {"underscore_appledouble", ResourceFile::Format::underscore_appledouble} }; map reverseFormats; static void usage() { - std::cerr << "Usage: " << "ResInfo [options] input-file\n"; - std::cerr << desc << std::endl; - std::cerr << "Available Resource Fork formats are:\n"; - for(auto p : formats) - std::cerr << " " << p.first << std::endl; + std::cerr << "Usage: " << "ResInfo [options] input-file\n"; + std::cerr << desc << std::endl; + std::cerr << "Available Resource Fork formats are:\n"; + for(auto p : formats) + std::cerr << " " << p.first << std::endl; } int main(int argc, char *argv[]) { - desc.add_options() - ("help,h", "show this help message") - ("type,t", "print file type") - ("creator,c", "print creator code") - ("all,a", "print all info") - ("format,f", "print format") - ("count,n", "print number of resources") - ("size,s", "show data fork size") - ("filename,l", "echo input file name") - ("set-format,F", po::value(), "resource fork format)") - ; - po::options_description hidden, alldesc; - hidden.add_options() - ("input", po::value>(), "input file" ) - ; - alldesc.add(desc).add(hidden); + desc.add_options() + ("help,h", "show this help message") + ("type,t", "print file type") + ("creator,c", "print creator code") + ("all,a", "print all info") + ("format,f", "print format") + ("count,n", "print number of resources") + ("size,s", "show data fork size") + ("filename,l", "echo input file name") + ("set-format,F", po::value(), "resource fork format)") + ; + po::options_description hidden, alldesc; + hidden.add_options() + ("input", po::value>(), "input file" ) + ; + alldesc.add(desc).add(hidden); - po::variables_map options; - try - { - auto parsed = po::command_line_parser(argc, argv) - .options(alldesc) - .positional(po::positional_options_description().add("input", -1)) - .style(po::command_line_style::default_style) - .run(); + po::variables_map options; + try + { + auto parsed = po::command_line_parser(argc, argv) + .options(alldesc) + .positional(po::positional_options_description().add("input", -1)) + .style(po::command_line_style::default_style) + .run(); - po::store(parsed, options); - } - catch(po::error& e) - { - std::cerr << "ERROR: " << e.what() << std::endl << std::endl; - usage(); - return 1; - } + po::store(parsed, options); + } + catch(po::error& e) + { + std::cerr << "ERROR: " << e.what() << std::endl << std::endl; + usage(); + return 1; + } - po::notify(options); + po::notify(options); - if(options.count("help") || !options.count("input")) - { - usage(); - return 0; - } - - for(auto p : formats) - reverseFormats[p.second] = p.first; + if(options.count("help") || !options.count("input")) + { + usage(); + return 0; + } + + for(auto p : formats) + reverseFormats[p.second] = p.first; - bool showFilename = options.count("filename"); - bool showType = options.count("type") != 0; - bool showCreator = options.count("creator") != 0; - bool showFormat = options.count("format") != 0; - bool showCount = options.count("count") != 0; - bool showSize = options.count("size") != 0; + bool showFilename = options.count("filename"); + bool showType = options.count("type") != 0; + bool showCreator = options.count("creator") != 0; + bool showFormat = options.count("format") != 0; + bool showCount = options.count("count") != 0; + bool showSize = options.count("size") != 0; - ResourceFile::Format format = ResourceFile::Format::autodetect; - - if(options.count("all")) - showType = showCreator = showFormat = showCount = showSize = true; - - if(options.count("set-format")) - { - string s = options["set-format"].as(); - if(formats.find(s) != formats.end()) - format = formats[s]; - else - { - std::cerr << "Unknown format " << s << std::endl << std::endl; - usage(); - exit(1); - } - } - - if(options.count("input")) - for(std::string fn : options["input"].as>()) - { - ResourceFile rsrcFile(fn, format); - - if(!rsrcFile.read()) - { - std::cerr << "Can't read file.\n"; - return 1; - } - - std::ostringstream out; - if(showType) - out << " " << rsrcFile.type; - if(showCreator) - out << " " << rsrcFile.creator; - if(showFormat) - out << " " << reverseFormats[rsrcFile.format]; - if(showCount) - out << " " << rsrcFile.resources.resources.size(); - if(showSize) - out << " " << rsrcFile.data.size(); + ResourceFile::Format format = ResourceFile::Format::autodetect; + + if(options.count("all")) + showType = showCreator = showFormat = showCount = showSize = true; + + if(options.count("set-format")) + { + string s = options["set-format"].as(); + if(formats.find(s) != formats.end()) + format = formats[s]; + else + { + std::cerr << "Unknown format " << s << std::endl << std::endl; + usage(); + exit(1); + } + } + + if(options.count("input")) + for(std::string fn : options["input"].as>()) + { + ResourceFile rsrcFile(fn, format); + + if(!rsrcFile.read()) + { + std::cerr << "Can't read file.\n"; + return 1; + } + + std::ostringstream out; + if(showType) + out << " " << rsrcFile.type; + if(showCreator) + out << " " << rsrcFile.creator; + if(showFormat) + out << " " << reverseFormats[rsrcFile.format]; + if(showCount) + out << " " << rsrcFile.resources.resources.size(); + if(showSize) + out << " " << rsrcFile.data.size(); - string str = out.str(); - if(str.size()) - { - if(showFilename) - std::cout << fn << ": "; - std::cout << out.str().substr(1) << std::endl; - } - else - { - if(showFilename) - std::cout << fn << std::endl; - } - } + string str = out.str(); + if(str.size()) + { + if(showFilename) + std::cout << fn << ": "; + std::cout << out.str().substr(1) << std::endl; + } + else + { + if(showFilename) + std::cout << fn << std::endl; + } + } return 0; } diff --git a/ResourceFiles/ResType.cc b/ResourceFiles/ResType.cc index 87ece75f3e..545480b1c9 100644 --- a/ResourceFiles/ResType.cc +++ b/ResourceFiles/ResType.cc @@ -4,55 +4,55 @@ ResType::ResType(const std::string &str) { - auto p = str.begin(); - auto e = str.end(); + auto p = str.begin(); + auto e = str.end(); - assert(str.size() == 4); + assert(str.size() == 4); - x = 0; - while(p != e) - { - x <<= 8; - x |= (*p) & 0xFF; - ++p; - } + x = 0; + while(p != e) + { + x <<= 8; + x |= (*p) & 0xFF; + ++p; + } } ResType::ResType(const char *s) { - auto p = s; - auto e = s + 4; + auto p = s; + auto e = s + 4; - assert(s[0] && s[1] && s[2] && s[3] && !s[4]); + assert(s[0] && s[1] && s[2] && s[3] && !s[4]); - x = 0; - while(p != e) - { - x <<= 8; - x |= (*p) & 0xFF; - ++p; - } + x = 0; + while(p != e) + { + x <<= 8; + x |= (*p) & 0xFF; + ++p; + } } ResType::operator std::string() { - char c1 = static_cast(x >> 24); - char c2 = static_cast(x >> 16); - char c3 = static_cast(x >> 8); - char c4 = static_cast(x); + char c1 = static_cast(x >> 24); + char c2 = static_cast(x >> 16); + char c3 = static_cast(x >> 8); + char c4 = static_cast(x); - return std::string{ c1, c2, c3, c4 }; + return std::string{ c1, c2, c3, c4 }; } std::ostream &operator<<(std::ostream &out, ResType t) { - char c1 = static_cast((int)t >> 24); - char c2 = static_cast((int)t >> 16); - char c3 = static_cast((int)t >> 8); - char c4 = static_cast((int)t); + char c1 = static_cast((int)t >> 24); + char c2 = static_cast((int)t >> 16); + char c3 = static_cast((int)t >> 8); + char c4 = static_cast((int)t); - out << "'" << c1 << c2 << c3 << c4 << "'"; - return out; + out << "'" << c1 << c2 << c3 << c4 << "'"; + return out; } diff --git a/ResourceFiles/ResType.h b/ResourceFiles/ResType.h index 1134fbc40f..dcb10b852a 100644 --- a/ResourceFiles/ResType.h +++ b/ResourceFiles/ResType.h @@ -6,30 +6,30 @@ class ResType { - int x; + int x; public: - ResType() : x(0) {} - ResType(int x) : x(x) {} - ResType(const std::string& s); - ResType(const char* s); + ResType() : x(0) {} + ResType(int x) : x(x) {} + ResType(const std::string& s); + ResType(const char* s); - operator int() const { return x; } - bool operator<(ResType y) const { return x < y.x; } + operator int() const { return x; } + bool operator<(ResType y) const { return x < y.x; } - operator std::string(); + operator std::string(); }; std::ostream& operator<<(std::ostream& out, ResType t); struct ResRef : public std::pair { - ResRef() : std::pair(ResType(), 0) {} - ResRef(ResType t, int id) : std::pair(t,id) {} + ResRef() : std::pair(ResType(), 0) {} + ResRef(ResType t, int id) : std::pair(t,id) {} - ResType& type() { return first; } - ResType type() const { return first; } - short& id() { return second; } - short id() const { return second; } + ResType& type() { return first; } + ResType type() const { return first; } + short& id() { return second; } + short id() const { return second; } }; #endif // RESTYPE_H diff --git a/ResourceFiles/ResourceFile.cc b/ResourceFiles/ResourceFile.cc index dbdb100085..678ca55811 100644 --- a/ResourceFiles/ResourceFile.cc +++ b/ResourceFiles/ResourceFile.cc @@ -17,94 +17,94 @@ namespace fs = boost::filesystem; // CRC 16 table lookup array static unsigned short CRC16Table[256] = - {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, - 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, - 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, - 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, - 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, - 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, - 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, - 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, - 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, - 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, - 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, - 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, - 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, - 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, - 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, - 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, - 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, - 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, - 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, - 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, - 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, - 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, - 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0}; + {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, + 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, + 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, + 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, + 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, + 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, + 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, + 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, + 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, + 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, + 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, + 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, + 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, + 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, + 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, + 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, + 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, + 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, + 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, + 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, + 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, + 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, + 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0}; // CalculateCRC static unsigned short CalculateCRC(unsigned short CRC, const char* dataBlock, int dataSize) { - while (dataSize) - { - CRC = (CRC << 8) ^ CRC16Table[((*dataBlock) ^ (CRC >> 8)) & 0x00FF]; - dataBlock++; - dataSize--; - } + while (dataSize) + { + CRC = (CRC << 8) ^ CRC16Table[((*dataBlock) ^ (CRC >> 8)) & 0x00FF]; + dataBlock++; + dataSize--; + } - return CRC; + return CRC; } static void writeMacBinary(std::ostream& out, std::string filename, - ResType type, ResType creator, - const Resources& rsrc, const std::string& data) + ResType type, ResType creator, + const Resources& rsrc, const std::string& data) { - std::ostringstream resstream; - rsrc.writeFork(resstream); + std::ostringstream resstream; + rsrc.writeFork(resstream); - const std::string& rsrcBytes = resstream.str(); + const std::string& rsrcBytes = resstream.str(); - std::ostringstream header; - byte(header, 0); - byte(header, filename.size()); - header << filename; - while((int)header.tellp() < 65) - byte(header,0); - ostype(header, type); - ostype(header, creator); - byte(header, 0); // flags - byte(header, 0); - word(header, 0); // position.v - word(header, 0); // position.h - word(header, 0); // folder id - byte(header, 0); // protected flag - byte(header, 0); - longword(header, (int)data.size()); - longword(header, (int)rsrcBytes.size()); - longword(header, 0); // creation date - longword(header, 0); // modification date - while((int)header.tellp() < 124) - byte(header,0); - std::string headerData = header.str(); - out << headerData; - word(out, CalculateCRC(0, &headerData[0], headerData.size())); - word(out, 0); - out << data; - while((int)out.tellp() % 128) - byte(out,0); - rsrc.writeFork(out); - while((int)out.tellp() % 128) - byte(out,0); + std::ostringstream header; + byte(header, 0); + byte(header, filename.size()); + header << filename; + while((int)header.tellp() < 65) + byte(header,0); + ostype(header, type); + ostype(header, creator); + byte(header, 0); // flags + byte(header, 0); + word(header, 0); // position.v + word(header, 0); // position.h + word(header, 0); // folder id + byte(header, 0); // protected flag + byte(header, 0); + longword(header, (int)data.size()); + longword(header, (int)rsrcBytes.size()); + longword(header, 0); // creation date + longword(header, 0); // modification date + while((int)header.tellp() < 124) + byte(header,0); + std::string headerData = header.str(); + out << headerData; + word(out, CalculateCRC(0, &headerData[0], headerData.size())); + word(out, 0); + out << data; + while((int)out.tellp() % 128) + byte(out,0); + rsrc.writeFork(out); + while((int)out.tellp() % 128) + byte(out,0); } @@ -115,7 +115,7 @@ ResourceFile::ResourceFile() ResourceFile::ResourceFile(std::string path, ResourceFile::Format f) { - assign(path, f); + assign(path, f); } ResourceFile::~ResourceFile() @@ -125,464 +125,464 @@ ResourceFile::~ResourceFile() static bool CheckAppleDouble(fs::path path, std::string prefix) { - fs::path adPath = path.parent_path() / (prefix + path.filename().string()); - fs::ifstream in(adPath); - if(in) - { - int magic1 = longword(in); + fs::path adPath = path.parent_path() / (prefix + path.filename().string()); + fs::ifstream in(adPath); + if(in) + { + int magic1 = longword(in); - if(in && magic1 == 0x00051607) - { - int magic2 = longword(in); - if(in && magic2 == 0x00020000) - return true; - } - } - return false; + if(in && magic1 == 0x00051607) + { + int magic2 = longword(in); + if(in && magic2 == 0x00020000) + return true; + } + } + return false; } bool ResourceFile::assign(std::string pathstring, ResourceFile::Format f) { - this->pathstring = pathstring; - fs::path path(pathstring); + this->pathstring = pathstring; + fs::path path(pathstring); - this->filename = path.stem().string(); - fs::path rsrcPath = path.parent_path() / ".rsrc" / path.filename(); - fs::path finfPath = path.parent_path() / ".finf" / path.filename(); + this->filename = path.stem().string(); + fs::path rsrcPath = path.parent_path() / ".rsrc" / path.filename(); + fs::path finfPath = path.parent_path() / ".finf" / path.filename(); - format = f; - if(format == Format::autodetect) - { - if(path.extension() == ".bin") - format = Format::macbin; - else if(path.extension() == ".as") - format = Format::applesingle; - else if(path.extension() == ".dsk" || path.extension() == ".img") - format = Format::diskimage; - else if(path.filename().string().substr(0,2) == "._") - { - path = path.parent_path() / path.filename().string().substr(2); - format = Format::underscore_appledouble; - this->pathstring = path.string(); - } - else if(path.filename().string()[0] == '%') - { - path = path.parent_path() / path.filename().string().substr(1); - format = Format::percent_appledouble; - this->pathstring = path.string(); - } - //else if(fs::exists(rsrcPath)) - // format = Format::basilisk; - } - if(format == Format::autodetect) - { - if(CheckAppleDouble(path, "._")) - format = Format::underscore_appledouble; - if(CheckAppleDouble(path, "%")) - format = Format::percent_appledouble; - } - if(format == Format::autodetect) - { - fs::ifstream in(path); - if(in) - { - int magic1 = longword(in); - if(in && magic1 == 0x00051600) - { - int magic2 = longword(in); - if(in && magic2 == 0x00020000) - format = Format::applesingle; - } - } - } - if(format == Format::autodetect) - { + format = f; + if(format == Format::autodetect) + { + if(path.extension() == ".bin") + format = Format::macbin; + else if(path.extension() == ".as") + format = Format::applesingle; + else if(path.extension() == ".dsk" || path.extension() == ".img") + format = Format::diskimage; + else if(path.filename().string().substr(0,2) == "._") + { + path = path.parent_path() / path.filename().string().substr(2); + format = Format::underscore_appledouble; + this->pathstring = path.string(); + } + else if(path.filename().string()[0] == '%') + { + path = path.parent_path() / path.filename().string().substr(1); + format = Format::percent_appledouble; + this->pathstring = path.string(); + } + //else if(fs::exists(rsrcPath)) + // format = Format::basilisk; + } + if(format == Format::autodetect) + { + if(CheckAppleDouble(path, "._")) + format = Format::underscore_appledouble; + if(CheckAppleDouble(path, "%")) + format = Format::percent_appledouble; + } + if(format == Format::autodetect) + { + fs::ifstream in(path); + if(in) + { + int magic1 = longword(in); + if(in && magic1 == 0x00051600) + { + int magic2 = longword(in); + if(in && magic2 == 0x00020000) + format = Format::applesingle; + } + } + } + if(format == Format::autodetect) + { #ifdef __APPLE__ - format = Format::real; + format = Format::real; #else - format = Format::basilisk; + format = Format::basilisk; #endif - } -// std::cout << "assigned: " << pathstring << " format " << (int)format << "\n"; - return true; + } +// std::cout << "assigned: " << pathstring << " format " << (int)format << "\n"; + return true; } bool ResourceFile::read(std::istream& in, Format f) { - switch(f) - { - case Format::applesingle: - { - if(longword(in) != 0x00051600) - return false; - if(longword(in) != 0x00020000) - return false; - in.seekg(24); - int n = word(in); - for(int i = 0; i < n; i++) - { - in.seekg(26 + i * 12); - int what = longword(in); - int off = longword(in); - int len = longword(in); - in.seekg(off); - switch(what) - { - case 1: - { - std::vector buf(len); - in.read(buf.data(), len); - data = std::string(buf.begin(), buf.end()); - } - break; - case 2: - resources = Resources(in); - break; - case 9: - type = ostype(in); - creator = ostype(in); - break; - } - } - } - break; - case Format::macbin: - { - if(byte(in) != 0) - return false; - if(byte(in) > 63) - return false; - in.seekg(65); - type = ostype(in); - creator = ostype(in); - in.seekg(83); - int datasize = longword(in); - //int rsrcsize = longword(in); + switch(f) + { + case Format::applesingle: + { + if(longword(in) != 0x00051600) + return false; + if(longword(in) != 0x00020000) + return false; + in.seekg(24); + int n = word(in); + for(int i = 0; i < n; i++) + { + in.seekg(26 + i * 12); + int what = longword(in); + int off = longword(in); + int len = longword(in); + in.seekg(off); + switch(what) + { + case 1: + { + std::vector buf(len); + in.read(buf.data(), len); + data = std::string(buf.begin(), buf.end()); + } + break; + case 2: + resources = Resources(in); + break; + case 9: + type = ostype(in); + creator = ostype(in); + break; + } + } + } + break; + case Format::macbin: + { + if(byte(in) != 0) + return false; + if(byte(in) > 63) + return false; + in.seekg(65); + type = ostype(in); + creator = ostype(in); + in.seekg(83); + int datasize = longword(in); + //int rsrcsize = longword(in); - in.seekg(0); - char header[124]; - in.read(header, 124); - unsigned short crc = CalculateCRC(0,header,124); - if(word(in) != crc) - return false; - in.seekg(128); - std::vector buf(datasize); - in.read(buf.data(), datasize); - data = std::string(buf.begin(), buf.end()); - datasize = ((int)datasize + 0x7F) & ~0x7F; - in.seekg(128 + datasize); - resources = Resources(in); - } - break; - default: - return false; - } - return true; + in.seekg(0); + char header[124]; + in.read(header, 124); + unsigned short crc = CalculateCRC(0,header,124); + if(word(in) != crc) + return false; + in.seekg(128); + std::vector buf(datasize); + in.read(buf.data(), datasize); + data = std::string(buf.begin(), buf.end()); + datasize = ((int)datasize + 0x7F) & ~0x7F; + in.seekg(128 + datasize); + resources = Resources(in); + } + break; + default: + return false; + } + return true; } bool ResourceFile::read() { - fs::path path(pathstring); + fs::path path(pathstring); - type = creator = 0x3F3F3F3F; + type = creator = 0x3F3F3F3F; - if(isSingleFork(format)) - { - fs::ifstream in(path); - return read(in, format); - } + if(isSingleFork(format)) + { + fs::ifstream in(path); + return read(in, format); + } - switch(format) - { - case Format::basilisk: - { - fs::ifstream dataIn(path); - if(!dataIn) - return false; - data = std::string(std::istreambuf_iterator(dataIn), - std::istreambuf_iterator()); + switch(format) + { + case Format::basilisk: + { + fs::ifstream dataIn(path); + if(!dataIn) + return false; + data = std::string(std::istreambuf_iterator(dataIn), + std::istreambuf_iterator()); - fs::ifstream rsrcIn(path.parent_path() / ".rsrc" / path.filename()); - if(rsrcIn) - resources = Resources(rsrcIn); - fs::ifstream finfIn(path.parent_path() / ".finf" / path.filename()); - if(finfIn) - { - type = ostype(finfIn); - creator = ostype(finfIn); - } - } - break; + fs::ifstream rsrcIn(path.parent_path() / ".rsrc" / path.filename()); + if(rsrcIn) + resources = Resources(rsrcIn); + fs::ifstream finfIn(path.parent_path() / ".finf" / path.filename()); + if(finfIn) + { + type = ostype(finfIn); + creator = ostype(finfIn); + } + } + break; #ifdef __APPLE__ - case Format::real: - { - fs::ifstream dataIn(path); - if(!dataIn) - return false; - data = std::string(std::istreambuf_iterator(dataIn), - std::istreambuf_iterator()); - fs::ifstream rsrcIn(path / "..namedfork" / "rsrc"); - if(rsrcIn) - resources = Resources(rsrcIn); + case Format::real: + { + fs::ifstream dataIn(path); + if(!dataIn) + return false; + data = std::string(std::istreambuf_iterator(dataIn), + std::istreambuf_iterator()); + fs::ifstream rsrcIn(path / "..namedfork" / "rsrc"); + if(rsrcIn) + resources = Resources(rsrcIn); - char finf[32]; - int n = getxattr(path.c_str(), XATTR_FINDERINFO_NAME, - finf, 32, 0, 0); - if(n > 0) - { - std::istringstream finfIn(std::string(finf, finf+n)); - type = ostype(finfIn); - creator = ostype(finfIn); - } - } - break; + char finf[32]; + int n = getxattr(path.c_str(), XATTR_FINDERINFO_NAME, + finf, 32, 0, 0); + if(n > 0) + { + std::istringstream finfIn(std::string(finf, finf+n)); + type = ostype(finfIn); + creator = ostype(finfIn); + } + } + break; #endif - case Format::underscore_appledouble: - case Format::percent_appledouble: - { - fs::ifstream dataIn(path); - data = std::string(std::istreambuf_iterator(dataIn), - std::istreambuf_iterator()); + case Format::underscore_appledouble: + case Format::percent_appledouble: + { + fs::ifstream dataIn(path); + data = std::string(std::istreambuf_iterator(dataIn), + std::istreambuf_iterator()); - std::string prefix = format == Format::underscore_appledouble ? - "._" : "%"; + std::string prefix = format == Format::underscore_appledouble ? + "._" : "%"; - fs::path adPath = path.parent_path() / (prefix + path.filename().string()); - fs::ifstream in(adPath); - if(longword(in) != 0x00051607) - return false; - if(longword(in) != 0x00020000) - return false; - in.seekg(24); - int n = word(in); - for(int i = 0; i < n; i++) - { - in.seekg(26 + i * 12); - int what = longword(in); - int off = longword(in); - //int len = longword(in); - in.seekg(off); - switch(what) - { - case 2: - resources = Resources(in); - break; - case 9: - type = ostype(in); - creator = ostype(in); - break; - } - } - } - break; - default: - return false; - } - return true; + fs::path adPath = path.parent_path() / (prefix + path.filename().string()); + fs::ifstream in(adPath); + if(longword(in) != 0x00051607) + return false; + if(longword(in) != 0x00020000) + return false; + in.seekg(24); + int n = word(in); + for(int i = 0; i < n; i++) + { + in.seekg(26 + i * 12); + int what = longword(in); + int off = longword(in); + //int len = longword(in); + in.seekg(off); + switch(what) + { + case 2: + resources = Resources(in); + break; + case 9: + type = ostype(in); + creator = ostype(in); + break; + } + } + } + break; + default: + return false; + } + return true; } bool ResourceFile::write(std::ostream& out, Format f) { - switch(f) - { - case Format::macbin: - { - writeMacBinary(out, filename, type, creator, resources, data); - } - break; - case Format::applesingle: - { - longword(out, 0x00051600); - longword(out, 0x00020000); - for(int i = 0; i < 16; i++) - byte(out, 0); - word(out, 3); - std::streampos entries = out.tellp(); - for(int i = 0; i < 3*3; i++) - longword(out, 0); - std::streampos dataStart = out.tellp(); - out << data; - std::streampos rsrcStart = out.tellp(); - resources.writeFork(out); - std::streampos finfStart = out.tellp(); - ostype(out, type); - ostype(out, creator); - for(int i = 8; i < 32; i++) - byte(out, 0); - out.seekp(entries); - longword(out, 1); - longword(out, dataStart); - longword(out, rsrcStart - dataStart); - longword(out, 2); - longword(out, rsrcStart); - longword(out, finfStart - rsrcStart); - longword(out, 9); - longword(out, finfStart); - longword(out, 32); - } - break; - default: - return false; - } - return true; + switch(f) + { + case Format::macbin: + { + writeMacBinary(out, filename, type, creator, resources, data); + } + break; + case Format::applesingle: + { + longword(out, 0x00051600); + longword(out, 0x00020000); + for(int i = 0; i < 16; i++) + byte(out, 0); + word(out, 3); + std::streampos entries = out.tellp(); + for(int i = 0; i < 3*3; i++) + longword(out, 0); + std::streampos dataStart = out.tellp(); + out << data; + std::streampos rsrcStart = out.tellp(); + resources.writeFork(out); + std::streampos finfStart = out.tellp(); + ostype(out, type); + ostype(out, creator); + for(int i = 8; i < 32; i++) + byte(out, 0); + out.seekp(entries); + longword(out, 1); + longword(out, dataStart); + longword(out, rsrcStart - dataStart); + longword(out, 2); + longword(out, rsrcStart); + longword(out, finfStart - rsrcStart); + longword(out, 9); + longword(out, finfStart); + longword(out, 32); + } + break; + default: + return false; + } + return true; } bool ResourceFile::write() { - fs::path path(pathstring); + fs::path path(pathstring); - if(isSingleFork(format)) - { - fs::ofstream out(path); - return write(out, format); - } + if(isSingleFork(format)) + { + fs::ofstream out(path); + return write(out, format); + } - switch(format) - { - case Format::basilisk: - { - fs::create_directory(path.parent_path() / ".rsrc"); - fs::create_directory(path.parent_path() / ".finf"); + switch(format) + { + case Format::basilisk: + { + fs::create_directory(path.parent_path() / ".rsrc"); + fs::create_directory(path.parent_path() / ".finf"); - fs::ofstream dataOut(path); - fs::ofstream rsrcOut(path.parent_path() / ".rsrc" / path.filename()); - fs::ofstream finfOut(path.parent_path() / ".finf" / path.filename()); + fs::ofstream dataOut(path); + fs::ofstream rsrcOut(path.parent_path() / ".rsrc" / path.filename()); + fs::ofstream finfOut(path.parent_path() / ".finf" / path.filename()); - dataOut << data; - resources.writeFork(rsrcOut); + dataOut << data; + resources.writeFork(rsrcOut); - ostype(finfOut, type); - ostype(finfOut, creator); - for(int i = 8; i < 32; i++) - byte(finfOut, 0); - } - break; + ostype(finfOut, type); + ostype(finfOut, creator); + for(int i = 8; i < 32; i++) + byte(finfOut, 0); + } + break; #ifdef __APPLE__ - case Format::real: - { - fs::ofstream dataOut(path); - fs::ofstream rsrcOut(path / "..namedfork" / "rsrc"); - std::ostringstream finfOut; + case Format::real: + { + fs::ofstream dataOut(path); + fs::ofstream rsrcOut(path / "..namedfork" / "rsrc"); + std::ostringstream finfOut; - dataOut << data; - resources.writeFork(rsrcOut); + dataOut << data; + resources.writeFork(rsrcOut); - ostype(finfOut, type); - ostype(finfOut, creator); - for(int i = 8; i < 32; i++) - byte(finfOut, 0); - setxattr(path.c_str(), XATTR_FINDERINFO_NAME, - finfOut.str().data(), 32, 0, 0); - } - break; + ostype(finfOut, type); + ostype(finfOut, creator); + for(int i = 8; i < 32; i++) + byte(finfOut, 0); + setxattr(path.c_str(), XATTR_FINDERINFO_NAME, + finfOut.str().data(), 32, 0, 0); + } + break; #endif - case Format::underscore_appledouble: - case Format::percent_appledouble: - { - fs::ofstream dataOut(path); + case Format::underscore_appledouble: + case Format::percent_appledouble: + { + fs::ofstream dataOut(path); - dataOut << data; + dataOut << data; - std::string prefix = format == Format::underscore_appledouble ? - "._" : "%"; + std::string prefix = format == Format::underscore_appledouble ? + "._" : "%"; - fs::path adPath = path.parent_path() / (prefix + path.filename().string()); + fs::path adPath = path.parent_path() / (prefix + path.filename().string()); - fs::ofstream out(adPath); + fs::ofstream out(adPath); - longword(out, 0x00051607); - longword(out, 0x00020000); + longword(out, 0x00051607); + longword(out, 0x00020000); - for(int i = 0; i < 16; i++) - byte(out, 0); - word(out, 2); - std::streampos entries = out.tellp(); - for(int i = 0; i < 2*3; i++) - longword(out, 0); - std::streampos rsrcStart = out.tellp(); - resources.writeFork(out); - std::streampos finfStart = out.tellp(); - ostype(out, type); - ostype(out, creator); - for(int i = 8; i < 32; i++) - byte(out, 0); - out.seekp(entries); - longword(out, 2); - longword(out, rsrcStart); - longword(out, finfStart - rsrcStart); - longword(out, 9); - longword(out, finfStart); - longword(out, 32); - } - break; + for(int i = 0; i < 16; i++) + byte(out, 0); + word(out, 2); + std::streampos entries = out.tellp(); + for(int i = 0; i < 2*3; i++) + longword(out, 0); + std::streampos rsrcStart = out.tellp(); + resources.writeFork(out); + std::streampos finfStart = out.tellp(); + ostype(out, type); + ostype(out, creator); + for(int i = 8; i < 32; i++) + byte(out, 0); + out.seekp(entries); + longword(out, 2); + longword(out, rsrcStart); + longword(out, finfStart - rsrcStart); + longword(out, 9); + longword(out, finfStart); + longword(out, 32); + } + break; - case Format::diskimage: - { - std::ostringstream rsrcOut; - resources.writeFork(rsrcOut); - std::string rsrc = rsrcOut.str(); - int size = rsrc.size(); + case Format::diskimage: + { + std::ostringstream rsrcOut; + resources.writeFork(rsrcOut); + std::string rsrc = rsrcOut.str(); + int size = rsrc.size(); - size += 20 * 1024; - size += 800*1024 - size % (800*1024); + size += 20 * 1024; + size += 800*1024 - size % (800*1024); - fs::ofstream(path, std::ios::binary | std::ios::trunc).seekp(size-1).put(0); + fs::ofstream(path, std::ios::binary | std::ios::trunc).seekp(size-1).put(0); - hfs_format(pathstring.c_str(), 0, 0, path.stem().string().substr(0,27).c_str(), 0, NULL); - hfsvol *vol = hfs_mount(pathstring.c_str(), 0, HFS_MODE_RDWR); - if(!vol) - return false; - //hfs_setvol(vol, ) - hfsfile *file = hfs_create(vol, (path.stem().string().substr(0,31)).c_str(), - ((std::string)type).c_str(), ((std::string)creator).c_str()); - hfs_setfork(file, 0); - hfs_write(file, data.data(), data.size()); - hfs_setfork(file, 1); - hfs_write(file, rsrc.data(), rsrc.size()); + hfs_format(pathstring.c_str(), 0, 0, path.stem().string().substr(0,27).c_str(), 0, NULL); + hfsvol *vol = hfs_mount(pathstring.c_str(), 0, HFS_MODE_RDWR); + if(!vol) + return false; + //hfs_setvol(vol, ) + hfsfile *file = hfs_create(vol, (path.stem().string().substr(0,31)).c_str(), + ((std::string)type).c_str(), ((std::string)creator).c_str()); + hfs_setfork(file, 0); + hfs_write(file, data.data(), data.size()); + hfs_setfork(file, 1); + hfs_write(file, rsrc.data(), rsrc.size()); - hfs_close(file); - hfs_umount(vol); + hfs_close(file); + hfs_umount(vol); - } - break; + } + break; - default: - return false; - } - return true; + default: + return false; + } + return true; } bool ResourceFile::hasPlainDataFork(ResourceFile::Format f) { - switch(f) - { + switch(f) + { #ifdef __APPLE__ - case Format::real: + case Format::real: #endif - case Format::basilisk: - case Format::underscore_appledouble: - case Format::percent_appledouble: - return true; - default: - return false; - } + case Format::basilisk: + case Format::underscore_appledouble: + case Format::percent_appledouble: + return true; + default: + return false; + } } bool ResourceFile::hasPlainDataFork() { - return hasPlainDataFork(format); + return hasPlainDataFork(format); } bool ResourceFile::isSingleFork(Format f) { - switch(f) - { - case Format::macbin: - case Format::applesingle: - return true; - default: - return false; - } + switch(f) + { + case Format::macbin: + case Format::applesingle: + return true; + default: + return false; + } } diff --git a/ResourceFiles/ResourceFile.h b/ResourceFiles/ResourceFile.h index cc0f520d7e..ab3ccccb85 100644 --- a/ResourceFiles/ResourceFile.h +++ b/ResourceFiles/ResourceFile.h @@ -11,44 +11,44 @@ class ResourceFile { public: - enum class Format - { - autodetect, + enum class Format + { + autodetect, #ifdef __APPLE__ - real, + real, #endif - macbin, - diskimage, - basilisk, - applesingle, - underscore_appledouble, - percent_appledouble - }; + macbin, + diskimage, + basilisk, + applesingle, + underscore_appledouble, + percent_appledouble + }; - ResourceFile(); - ResourceFile(std::string path, Format f = Format::autodetect); - ~ResourceFile(); + ResourceFile(); + ResourceFile(std::string path, Format f = Format::autodetect); + ~ResourceFile(); - bool assign(std::string path, Format f = Format::autodetect); + bool assign(std::string path, Format f = Format::autodetect); - bool read(std::istream& in, Format f); - bool write(std::ostream& in, Format f); + bool read(std::istream& in, Format f); + bool write(std::ostream& in, Format f); - bool read(); - bool write(); + bool read(); + bool write(); - static bool hasPlainDataFork(Format f); - bool hasPlainDataFork(); + static bool hasPlainDataFork(Format f); + bool hasPlainDataFork(); - static bool isSingleFork(Format f); + static bool isSingleFork(Format f); - std::string pathstring; - std::string filename; - Format format; - ResType type; - ResType creator; - Resources resources; - std::string data; + std::string pathstring; + std::string filename; + Format format; + ResType type; + ResType creator; + Resources resources; + std::string data; }; #endif // RESOURCEFILE_H diff --git a/ResourceFiles/ResourceFork.cc b/ResourceFiles/ResourceFork.cc index bcaf77a722..bf9a58750f 100644 --- a/ResourceFiles/ResourceFork.cc +++ b/ResourceFiles/ResourceFork.cc @@ -7,156 +7,156 @@ void Resources::addResources(const Resources& res) { - for(auto& rr : res.resources) - addResource(rr.second); + for(auto& rr : res.resources) + addResource(rr.second); } void Resources::writeFork(std::ostream& out) const { - std::streampos start = out.tellp(); - longword(out,0x100); - longword(out,0); - longword(out,0); - longword(out,0); - for(int i = 0; i < 0x100 - 16; i++) - byte(out, 0); + std::streampos start = out.tellp(); + longword(out,0x100); + longword(out,0); + longword(out,0); + longword(out,0); + for(int i = 0; i < 0x100 - 16; i++) + byte(out, 0); - std::map< ResType, std::map > resourceInfos; - std::streampos datastart = out.tellp(); - for(auto& rr : resources) - { - const Resource& r = rr.second; - const std::string& data = r.getData(); - unsigned offset = out.tellp() - datastart; - offset = (r.getAttr() << 24) | (offset & 0xFFFFFF); - resourceInfos[ r.getType() ][ r.getID() ] = (int)offset; - longword(out, data.size()); - out << data; - } - std::streampos dataend = out.tellp(); + std::map< ResType, std::map > resourceInfos; + std::streampos datastart = out.tellp(); + for(auto& rr : resources) + { + const Resource& r = rr.second; + const std::string& data = r.getData(); + unsigned offset = out.tellp() - datastart; + offset = (r.getAttr() << 24) | (offset & 0xFFFFFF); + resourceInfos[ r.getType() ][ r.getID() ] = (int)offset; + longword(out, data.size()); + out << data; + } + std::streampos dataend = out.tellp(); // while(out.tellp() % 0x100) // out.put(0); - std::streampos resmap = out.tellp(); - for(int i = 0; i < 16+4+2+2; i++) - byte(out, 0); - word(out,16+4+2+2+2+2); // offset to resource type list - std::streampos resnameOffset = out.tellp(); - word(out,0); - std::streampos typelist = out.tellp(); - word(out,resourceInfos.size() - 1); - for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); - p != resourceInfos.end(); ++p) - { - if(p->second.size()) - { - ostype(out,p->first); - word(out,p->second.size()-1); - word(out,0); // replaced later - } - } - int typeIndex = 0; - int nameOffset = 0; - for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); - p != resourceInfos.end(); ++p) - { - if(p->second.size()) - { - std::streampos pos = out.tellp(); - out.seekp((int)typelist + 2 + 8 * typeIndex + 6); - word(out, pos - typelist); - out.seekp(pos); - typeIndex++; + std::streampos resmap = out.tellp(); + for(int i = 0; i < 16+4+2+2; i++) + byte(out, 0); + word(out,16+4+2+2+2+2); // offset to resource type list + std::streampos resnameOffset = out.tellp(); + word(out,0); + std::streampos typelist = out.tellp(); + word(out,resourceInfos.size() - 1); + for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); + p != resourceInfos.end(); ++p) + { + if(p->second.size()) + { + ostype(out,p->first); + word(out,p->second.size()-1); + word(out,0); // replaced later + } + } + int typeIndex = 0; + int nameOffset = 0; + for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); + p != resourceInfos.end(); ++p) + { + if(p->second.size()) + { + std::streampos pos = out.tellp(); + out.seekp((int)typelist + 2 + 8 * typeIndex + 6); + word(out, pos - typelist); + out.seekp(pos); + typeIndex++; - for(std::map::iterator q = p->second.begin(); q != p->second.end(); ++q) - { - std::string name = resources.find(ResRef(p->first, q->first))->second.getName(); - word(out,q->first); - if(name.size() == 0) - word(out,-1); - else - { - word(out, nameOffset); - nameOffset += (name.size() > 255 ? 255 : name.size()) + 1; - } - longword(out,q->second); - longword(out,0); - } - } - } - std::streampos resnames = out.tellp(); - out.seekp(resnameOffset); - word(out, resnames - resmap); - out.seekp(resnames); + for(std::map::iterator q = p->second.begin(); q != p->second.end(); ++q) + { + std::string name = resources.find(ResRef(p->first, q->first))->second.getName(); + word(out,q->first); + if(name.size() == 0) + word(out,-1); + else + { + word(out, nameOffset); + nameOffset += (name.size() > 255 ? 255 : name.size()) + 1; + } + longword(out,q->second); + longword(out,0); + } + } + } + std::streampos resnames = out.tellp(); + out.seekp(resnameOffset); + word(out, resnames - resmap); + out.seekp(resnames); - for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); - p != resourceInfos.end(); ++p) - { - for(std::map::iterator q = p->second.begin(); q != p->second.end(); ++q) - { - std::string name = resources.find(ResRef(p->first, q->first))->second.getName(); - if(name.size() > 0) - { - int sz = name.size() > 255 ? 255 : name.size(); - byte(out, sz); - for(int i = 0; i < sz; i++) - byte(out, name[i]); - } - } - } + for(std::map< ResType, std::map >::iterator p = resourceInfos.begin(); + p != resourceInfos.end(); ++p) + { + for(std::map::iterator q = p->second.begin(); q != p->second.end(); ++q) + { + std::string name = resources.find(ResRef(p->first, q->first))->second.getName(); + if(name.size() > 0) + { + int sz = name.size() > 255 ? 255 : name.size(); + byte(out, sz); + for(int i = 0; i < sz; i++) + byte(out, name[i]); + } + } + } - std::streampos end = out.tellp(); - out.seekp(start + std::streampos(4)); - longword(out, resmap - start); - longword(out, dataend - start - std::streampos(0x100)); - longword(out, end - resmap); - out.seekp(end); + std::streampos end = out.tellp(); + out.seekp(start + std::streampos(4)); + longword(out, resmap - start); + longword(out, dataend - start - std::streampos(0x100)); + longword(out, end - resmap); + out.seekp(end); } Resources::Resources(std::istream &in) { - std::streampos start = in.tellg(); - int resdataOffset = longword(in); - int resmapOffset = longword(in); + std::streampos start = in.tellg(); + int resdataOffset = longword(in); + int resmapOffset = longword(in); - in.seekg(start + std::streampos(resmapOffset + 16 + 4 + 2 + 2)); - int typeListOffset = word(in); - int nameListOffset = word(in); - int nTypes = (word(in) + 1) & 0xFFFF; + in.seekg(start + std::streampos(resmapOffset + 16 + 4 + 2 + 2)); + int typeListOffset = word(in); + int nameListOffset = word(in); + int nTypes = (word(in) + 1) & 0xFFFF; - for(int i = 0; i < nTypes; i++) - { - in.seekg(start + std::streampos(resmapOffset + typeListOffset + 2 + i * 8)); - std::string type = ostype(in); - int nRes = (word(in) + 1) & 0xFFFF; - int refListOffset = word(in); + for(int i = 0; i < nTypes; i++) + { + in.seekg(start + std::streampos(resmapOffset + typeListOffset + 2 + i * 8)); + std::string type = ostype(in); + int nRes = (word(in) + 1) & 0xFFFF; + int refListOffset = word(in); - for(int j = 0; j < nRes; j++) - { - in.seekg(start + std::streampos(resmapOffset + typeListOffset + refListOffset + j * 12)); - int id = (short) word(in); - int nameOffset = word(in); - int attr = byte(in); - int off1 = byte(in); - int off2 = byte(in); - int off3 = byte(in); - int offset = (off1 << 16) | (off2 << 8) | off3; - std::string name; - if(nameOffset != 0xFFFF) - { - in.seekg(start + std::streampos(resmapOffset + nameListOffset + nameOffset)); - int nameLen = byte(in); - char buf[256]; - in.read(buf, nameLen); - name = std::string(buf, nameLen); - } + for(int j = 0; j < nRes; j++) + { + in.seekg(start + std::streampos(resmapOffset + typeListOffset + refListOffset + j * 12)); + int id = (short) word(in); + int nameOffset = word(in); + int attr = byte(in); + int off1 = byte(in); + int off2 = byte(in); + int off3 = byte(in); + int offset = (off1 << 16) | (off2 << 8) | off3; + std::string name; + if(nameOffset != 0xFFFF) + { + in.seekg(start + std::streampos(resmapOffset + nameListOffset + nameOffset)); + int nameLen = byte(in); + char buf[256]; + in.read(buf, nameLen); + name = std::string(buf, nameLen); + } - in.seekg(start + std::streampos(resdataOffset + offset)); - int size = longword(in); - std::vector tmp(size); - in.read(tmp.data(), size); - std::string data(tmp.data(), size); + in.seekg(start + std::streampos(resdataOffset + offset)); + int size = longword(in); + std::vector tmp(size); + in.read(tmp.data(), size); + std::string data(tmp.data(), size); - addResource(Resource(type, id, data, name, attr)); - } - } + addResource(Resource(type, id, data, name, attr)); + } + } } diff --git a/ResourceFiles/ResourceFork.h b/ResourceFiles/ResourceFork.h index e9ed81e6e9..9ea96c7d5a 100644 --- a/ResourceFiles/ResourceFork.h +++ b/ResourceFiles/ResourceFork.h @@ -7,43 +7,43 @@ class Resource { - ResType type; - short id; - std::string name; - std::string data; - int attr; + ResType type; + short id; + std::string name; + std::string data; + int attr; public: - Resource() {} - Resource(ResType type, int id, std::string data, std::string name = "", int attr = 0) - : type(type), id(id), name(name), data(data), attr(attr) {} + Resource() {} + Resource(ResType type, int id, std::string data, std::string name = "", int attr = 0) + : type(type), id(id), name(name), data(data), attr(attr) {} - const std::string& getData() const { return data; } - inline ResType getType() const { return type; } - inline int getID() const { return id; } - inline ResRef getTypeAndID() const { return ResRef(type, id); } - std::string getName() const { return name; } - int getAttr() const { return attr; } + const std::string& getData() const { return data; } + inline ResType getType() const { return type; } + inline int getID() const { return id; } + inline ResRef getTypeAndID() const { return ResRef(type, id); } + std::string getName() const { return name; } + int getAttr() const { return attr; } }; class Fork { public: - virtual void writeFork(std::ostream& out) const { } - virtual ~Fork() {} + virtual void writeFork(std::ostream& out) const { } + virtual ~Fork() {} }; class Resources : public Fork { public: - std::map resources; + std::map resources; - Resources() {} - Resources(std::istream& in); - void writeFork(std::ostream& out) const; - void addResource(Resource res) { resources[res.getTypeAndID()] = res; } - void addResources(const Resources& res); + Resources() {} + Resources(std::istream& in); + void writeFork(std::ostream& out) const; + void addResource(Resource res) { resources[res.getTypeAndID()] = res; } + void addResources(const Resources& res); - unsigned countResources() const { return resources.size(); } + unsigned countResources() const { return resources.size(); } }; #endif // RESOURCEFORK_H diff --git a/Rez/CMakeLists.txt b/Rez/CMakeLists.txt index 02da3efc5f..f63e6b698f 100644 --- a/Rez/CMakeLists.txt +++ b/Rez/CMakeLists.txt @@ -18,9 +18,9 @@ find_package(Boost COMPONENTS wave filesystem system thread regex program_options) # Look for bison. - # We need Version 3, and Mac OS X still comes with an outdated version (2.3). - # So we just add the path where the homebrew package manager installs its - # "keg-only" version. Shouldn't hurt on Linux. + # We need Version 3, and Mac OS X still comes with an outdated version (2.3). + # So we just add the path where the homebrew package manager installs its + # "keg-only" version. Shouldn't hurt on Linux. set(CMAKE_PROGRAM_PATH ${CMAKE_PROGRAM_PATH} "/usr/local/opt/bison/bin") find_package(BISON 3.0.2) @@ -30,8 +30,8 @@ if(Boost_FOUND AND BISON_FOUND) include_directories(. ${CMAKE_CURRENT_BINARY_DIR}) set(BISON_OUTPUTS ${CMAKE_CURRENT_BINARY_DIR}/RezParser.generated.cc ${CMAKE_CURRENT_BINARY_DIR}/RezParser.generated.hh - ${CMAKE_CURRENT_BINARY_DIR}/location.hh ${CMAKE_CURRENT_BINARY_DIR}/position.hh - ${CMAKE_CURRENT_BINARY_DIR}/stack.hh) + ${CMAKE_CURRENT_BINARY_DIR}/location.hh ${CMAKE_CURRENT_BINARY_DIR}/position.hh + ${CMAKE_CURRENT_BINARY_DIR}/stack.hh) add_custom_command(OUTPUT ${BISON_OUTPUTS} COMMAND ${BISON_EXECUTABLE} @@ -42,36 +42,36 @@ add_custom_command(OUTPUT ${BISON_OUTPUTS} add_library(RezLib - RezParser.yy - ${BISON_OUTPUTS} + RezParser.yy + ${BISON_OUTPUTS} - RezLexer.h - RezLexer.cc - RezLexerWaveToken.h - RezLexerNextToken.cc + RezLexer.h + RezLexer.cc + RezLexerWaveToken.h + RezLexerNextToken.cc - RezWorld.cc - RezWorld.h + RezWorld.cc + RezWorld.h - ResourceDefinitions.cc - ResourceDefinitions.h + ResourceDefinitions.cc + ResourceDefinitions.h - Expression.cc - Expression.h + Expression.cc + Expression.h - ResourceCompiler.cc - ResourceCompiler.h + ResourceCompiler.cc + ResourceCompiler.h - ResSpec.h + ResSpec.h - Diagnostic.h Diagnostic.cc - ) + Diagnostic.h Diagnostic.cc + ) target_link_libraries(RezLib ResourceFiles ${Boost_LIBRARIES}) target_include_directories(RezLib PRIVATE ${Boost_INCLUDE_DIR}) add_executable(Rez - Rez.cc - ) + Rez.cc + ) target_link_libraries(Rez RezLib ResourceFiles ${Boost_LIBRARIES}) target_include_directories(Rez PRIVATE ${Boost_INCLUDE_DIR}) @@ -80,5 +80,5 @@ install(TARGETS Rez RUNTIME DESTINATION bin) add_subdirectory(Test) else(Boost_FOUND AND BISON_FOUND) - message(WARNING "Rez compiler will not be built; both boost and Bison 3.0.2 are required") + message(WARNING "Rez compiler will not be built; both boost and Bison 3.0.2 are required") endif(Boost_FOUND AND BISON_FOUND) diff --git a/Rez/Diagnostic.cc b/Rez/Diagnostic.cc index 11e090e439..f5d3588797 100644 --- a/Rez/Diagnostic.cc +++ b/Rez/Diagnostic.cc @@ -5,7 +5,7 @@ Diagnostic::Diagnostic() } Diagnostic::Diagnostic(Severity sev, std::string msg, yy::location loc) - : severity(sev), message(msg), location(loc) + : severity(sev), message(msg), location(loc) { } @@ -13,16 +13,16 @@ Diagnostic::Diagnostic(Severity sev, std::string msg, yy::location loc) std::ostream &operator<<(std::ostream &out, const Diagnostic &d) { - //return out << d.location << ": " << d.message; - const yy::location& loc = d.location; - if (loc.begin.filename) - out << *loc.begin.filename << ':'; - out << loc.begin.line << ':' << loc.begin.column; - out << ": "; - if(d.severity >= Diagnostic::error) - out << "error"; - else - out << "warning"; - out << ": " << d.message; - return out; + //return out << d.location << ": " << d.message; + const yy::location& loc = d.location; + if (loc.begin.filename) + out << *loc.begin.filename << ':'; + out << loc.begin.line << ':' << loc.begin.column; + out << ": "; + if(d.severity >= Diagnostic::error) + out << "error"; + else + out << "warning"; + out << ": " << d.message; + return out; } diff --git a/Rez/Diagnostic.h b/Rez/Diagnostic.h index 3e0b442089..faafb87b5d 100644 --- a/Rez/Diagnostic.h +++ b/Rez/Diagnostic.h @@ -8,22 +8,22 @@ class Diagnostic { public: - enum Severity - { - warning, - error, - fatalError - }; + enum Severity + { + warning, + error, + fatalError + }; - Diagnostic(); - Diagnostic(Severity sev, std::string msg, yy::location loc); + Diagnostic(); + Diagnostic(Severity sev, std::string msg, yy::location loc); private: - Severity severity; - std::string message; - yy::location location; + Severity severity; + std::string message; + yy::location location; - friend std::ostream& operator<<(std::ostream&, const Diagnostic&); + friend std::ostream& operator<<(std::ostream&, const Diagnostic&); }; std::ostream& operator<<(std::ostream&, const Diagnostic&); diff --git a/Rez/Expression.cc b/Rez/Expression.cc index 32381155bb..2167e49d5b 100644 --- a/Rez/Expression.cc +++ b/Rez/Expression.cc @@ -7,14 +7,14 @@ int Expression::evaluateInt(ResourceCompiler *ctx) { - error(ctx, "Expected an integer or integer expression here."); - return 0; + error(ctx, "Expected an integer or integer expression here."); + return 0; } std::string Expression::evaluateString(ResourceCompiler *ctx) { - error(ctx, "Expected a string or string expression here."); - return ""; + error(ctx, "Expected a string or string expression here."); + return ""; } Expression::~Expression() @@ -23,7 +23,7 @@ Expression::~Expression() void Expression::error(ResourceCompiler *ctx, std::string err) { - ctx->problem(Diagnostic(Diagnostic::Severity::error, err, location)); + ctx->problem(Diagnostic(Diagnostic::Severity::error, err, location)); } @@ -33,7 +33,7 @@ StringExpr::~StringExpr() std::string StringExpr::evaluateString(ResourceCompiler *ctx) { - return str; + return str; } @@ -43,13 +43,13 @@ IntExpr::~IntExpr() int IntExpr::evaluateInt(ResourceCompiler *ctx) { - return val; + return val; } void CompoundExpr::addItem(ExprPtr item) { - items.push_back(item); + items.push_back(item); } CompoundExpr::~CompoundExpr() @@ -63,46 +63,46 @@ BinaryExpr::~BinaryExpr() int BinaryExpr::evaluateInt(ResourceCompiler *ctx) { - switch(op) - { - case BinaryOp::XOR: - return a->evaluateInt(ctx) ^ b->evaluateInt(ctx); - case BinaryOp::OR: - return a->evaluateInt(ctx) | b->evaluateInt(ctx); - case BinaryOp::AND: - return a->evaluateInt(ctx) & b->evaluateInt(ctx); - case BinaryOp::SHIFTLEFT: - return a->evaluateInt(ctx) << b->evaluateInt(ctx); - case BinaryOp::SHIFTRIGHT: - return a->evaluateInt(ctx) >> b->evaluateInt(ctx); - case BinaryOp::EQUAL: - return a->evaluateInt(ctx) == b->evaluateInt(ctx); - case BinaryOp::NOTEQUAL: - return a->evaluateInt(ctx) != b->evaluateInt(ctx); - case BinaryOp::PLUS: - return a->evaluateInt(ctx) + b->evaluateInt(ctx); - case BinaryOp::MINUS: - return a->evaluateInt(ctx) - b->evaluateInt(ctx); - case BinaryOp::MULTIPLY: - return a->evaluateInt(ctx) * b->evaluateInt(ctx); - case BinaryOp::DIVIDE: - return a->evaluateInt(ctx) / b->evaluateInt(ctx); - default: - error(ctx, "Expected an integer or integer expression here."); - return 0; - } + switch(op) + { + case BinaryOp::XOR: + return a->evaluateInt(ctx) ^ b->evaluateInt(ctx); + case BinaryOp::OR: + return a->evaluateInt(ctx) | b->evaluateInt(ctx); + case BinaryOp::AND: + return a->evaluateInt(ctx) & b->evaluateInt(ctx); + case BinaryOp::SHIFTLEFT: + return a->evaluateInt(ctx) << b->evaluateInt(ctx); + case BinaryOp::SHIFTRIGHT: + return a->evaluateInt(ctx) >> b->evaluateInt(ctx); + case BinaryOp::EQUAL: + return a->evaluateInt(ctx) == b->evaluateInt(ctx); + case BinaryOp::NOTEQUAL: + return a->evaluateInt(ctx) != b->evaluateInt(ctx); + case BinaryOp::PLUS: + return a->evaluateInt(ctx) + b->evaluateInt(ctx); + case BinaryOp::MINUS: + return a->evaluateInt(ctx) - b->evaluateInt(ctx); + case BinaryOp::MULTIPLY: + return a->evaluateInt(ctx) * b->evaluateInt(ctx); + case BinaryOp::DIVIDE: + return a->evaluateInt(ctx) / b->evaluateInt(ctx); + default: + error(ctx, "Expected an integer or integer expression here."); + return 0; + } } std::string BinaryExpr::evaluateString(ResourceCompiler *ctx) { - switch(op) - { - case BinaryOp::CONCAT: - return a->evaluateString(ctx) + b->evaluateString(ctx); - default: - error(ctx, "Expected a string or string expression here."); - return ""; - } + switch(op) + { + case BinaryOp::CONCAT: + return a->evaluateString(ctx) + b->evaluateString(ctx); + default: + error(ctx, "Expected a string or string expression here."); + return ""; + } } @@ -112,122 +112,122 @@ UnaryExpr::~UnaryExpr() int UnaryExpr::evaluateInt(ResourceCompiler *ctx) { - switch(op) - { - case UnaryOp::MINUS: - return -a->evaluateInt(ctx); - case UnaryOp::COMPLEMENT: - return ~a->evaluateInt(ctx); - default: - error(ctx, "Expected an integer or integer expression here."); - return 0; - } + switch(op) + { + case UnaryOp::MINUS: + return -a->evaluateInt(ctx); + case UnaryOp::COMPLEMENT: + return ~a->evaluateInt(ctx); + default: + error(ctx, "Expected an integer or integer expression here."); + return 0; + } } IdentifierExpr::IdentifierExpr(std::string id, yy::location loc) - : Expression(loc), id(id) + : Expression(loc), id(id) { } void IdentifierExpr::addArgument(ExprPtr e) { - arguments.push_back(e); + arguments.push_back(e); } ExprPtr IdentifierExpr::lookup(ResourceCompiler *ctx) { - Subscripts sub; - for(auto arg : arguments) - sub.addSubscript(arg->evaluateInt(ctx)); - ExprPtr val = ctx->lookupIdentifier(id, sub); - if(!val) - error(ctx, "Identifier \"" + id + "\" is not defined."); - return val; + Subscripts sub; + for(auto arg : arguments) + sub.addSubscript(arg->evaluateInt(ctx)); + ExprPtr val = ctx->lookupIdentifier(id, sub); + if(!val) + error(ctx, "Identifier \"" + id + "\" is not defined."); + return val; } int IdentifierExpr::evaluateInt(ResourceCompiler *ctx) { - if(ctx->isPrePass()) - return 0; - if(ExprPtr e = lookup(ctx)) - return e->evaluateInt(ctx); - else - return 0; + if(ctx->isPrePass()) + return 0; + if(ExprPtr e = lookup(ctx)) + return e->evaluateInt(ctx); + else + return 0; } std::string IdentifierExpr::evaluateString(ResourceCompiler *ctx) { - if(ExprPtr e = lookup(ctx)) - return e->evaluateString(ctx); - else - return ""; + if(ExprPtr e = lookup(ctx)) + return e->evaluateString(ctx); + else + return ""; } CaseExpr::CaseExpr(const std::string &tag, CompoundExprPtr expr, yy::location loc) - : Expression(loc), tag(tag), expr(expr) + : Expression(loc), tag(tag), expr(expr) { } int CountOfExpr::evaluateInt(ResourceCompiler *ctx) { - assert(arg->arguments.size() == 0); - return ctx->getArrayCount(arg->id); + assert(arg->arguments.size() == 0); + return ctx->getArrayCount(arg->id); } int ArrayIndexExpr::evaluateInt(ResourceCompiler *ctx) { - assert(arg->arguments.size() == 0); - return ctx->getArrayIndex(arg->id); + assert(arg->arguments.size() == 0); + return ctx->getArrayIndex(arg->id); } std::string ReadExpr::evaluateString(ResourceCompiler *ctx) { - std::string filename = arg->evaluateString(ctx); - std::ifstream instream(filename); + std::string filename = arg->evaluateString(ctx); + std::ifstream instream(filename); if(!instream) { ctx->problem(Diagnostic(Diagnostic::Severity::error, "could not $$read file " + filename, location)); } - return std::string(std::istreambuf_iterator(instream.rdbuf()), - std::istreambuf_iterator()); + return std::string(std::istreambuf_iterator(instream.rdbuf()), + std::istreambuf_iterator()); } int UnimplementedExpr::evaluateInt(ResourceCompiler *ctx) { - std::cerr << msg << std::endl; - return 0; + std::cerr << msg << std::endl; + return 0; } std::string UnimplementedExpr::evaluateString(ResourceCompiler *ctx) { - std::cerr << msg << std::endl; - return ""; + std::cerr << msg << std::endl; + return ""; } PeekExpr::PeekExpr(ExprPtr addr, ExprPtr offset, ExprPtr size, yy::location loc) - : Expression(loc), addr(addr), offset(offset), size(size) + : Expression(loc), addr(addr), offset(offset), size(size) { } PeekExpr::PeekExpr(ExprPtr addr, int size, yy::location loc) - : Expression(loc), - addr(addr), - offset(std::make_shared(0,loc)), - size(std::make_shared(size,loc)) + : Expression(loc), + addr(addr), + offset(std::make_shared(0,loc)), + size(std::make_shared(size,loc)) { } int PeekExpr::evaluateInt(ResourceCompiler *ctx) { - int p = addr->evaluateInt(ctx) + offset->evaluateInt(ctx); - int s = size->evaluateInt(ctx); + int p = addr->evaluateInt(ctx) + offset->evaluateInt(ctx); + int s = size->evaluateInt(ctx); - return ctx->peek(p, s); + return ctx->peek(p, s); } diff --git a/Rez/Expression.h b/Rez/Expression.h index f9572a250c..5b183205f8 100644 --- a/Rez/Expression.h +++ b/Rez/Expression.h @@ -20,12 +20,12 @@ typedef std::shared_ptr CaseExprPtr; enum class BinaryOp { - XOR, OR, AND, SHIFTLEFT, SHIFTRIGHT, EQUAL, NOTEQUAL, PLUS, MINUS, MULTIPLY, DIVIDE, CONCAT + XOR, OR, AND, SHIFTLEFT, SHIFTRIGHT, EQUAL, NOTEQUAL, PLUS, MINUS, MULTIPLY, DIVIDE, CONCAT }; enum class UnaryOp { - MINUS, COMPLEMENT + MINUS, COMPLEMENT }; class TypeError @@ -35,138 +35,138 @@ class TypeError class Expression { public: - yy::location location; + yy::location location; - Expression(yy::location loc) : location(loc) {} + Expression(yy::location loc) : location(loc) {} - virtual int evaluateInt(ResourceCompiler *ctx); - virtual std::string evaluateString(ResourceCompiler *ctx); - virtual ~Expression(); + virtual int evaluateInt(ResourceCompiler *ctx); + virtual std::string evaluateString(ResourceCompiler *ctx); + virtual ~Expression(); - void error(ResourceCompiler *ctx, std::string err); + void error(ResourceCompiler *ctx, std::string err); }; class StringExpr : public Expression { - std::string str; + std::string str; public: - StringExpr(const std::string& str, yy::location loc) : Expression(loc), str(str) {} - ~StringExpr(); - virtual std::string evaluateString(ResourceCompiler *ctx); + StringExpr(const std::string& str, yy::location loc) : Expression(loc), str(str) {} + ~StringExpr(); + virtual std::string evaluateString(ResourceCompiler *ctx); }; class IntExpr : public Expression { - int val; + int val; public: - IntExpr(int val, yy::location loc) : Expression(loc), val(val) {} - ~IntExpr(); + IntExpr(int val, yy::location loc) : Expression(loc), val(val) {} + ~IntExpr(); - virtual int evaluateInt(ResourceCompiler *ctx); + virtual int evaluateInt(ResourceCompiler *ctx); }; class CompoundExpr : public Expression { - std::vector items; + std::vector items; public: - CompoundExpr(yy::location loc) : Expression(loc) {} + CompoundExpr(yy::location loc) : Expression(loc) {} - void addItem(ExprPtr item); - ExprPtr getItem(int i) const { return items[i]; } - int size() const { return items.size(); } + void addItem(ExprPtr item); + ExprPtr getItem(int i) const { return items[i]; } + int size() const { return items.size(); } - ~CompoundExpr(); + ~CompoundExpr(); }; class CaseExpr : public Expression { - std::string tag; - CompoundExprPtr expr; - friend class SwitchField; + std::string tag; + CompoundExprPtr expr; + friend class SwitchField; public: - CaseExpr(const std::string& tag, CompoundExprPtr expr, yy::location loc); + CaseExpr(const std::string& tag, CompoundExprPtr expr, yy::location loc); }; class BinaryExpr : public Expression { - BinaryOp op; - ExprPtr a, b; + BinaryOp op; + ExprPtr a, b; public: - BinaryExpr(BinaryOp op, ExprPtr a, ExprPtr b, yy::location loc) - : Expression(loc), op(op), a(a), b(b) {} - ~BinaryExpr(); + BinaryExpr(BinaryOp op, ExprPtr a, ExprPtr b, yy::location loc) + : Expression(loc), op(op), a(a), b(b) {} + ~BinaryExpr(); - virtual int evaluateInt(ResourceCompiler *ctx); - virtual std::string evaluateString(ResourceCompiler *ctx); + virtual int evaluateInt(ResourceCompiler *ctx); + virtual std::string evaluateString(ResourceCompiler *ctx); }; class UnaryExpr : public Expression { - UnaryOp op; - ExprPtr a; + UnaryOp op; + ExprPtr a; public: - UnaryExpr(UnaryOp op, ExprPtr a, yy::location loc) - : Expression(loc), op(op), a(a) {} - ~UnaryExpr(); + UnaryExpr(UnaryOp op, ExprPtr a, yy::location loc) + : Expression(loc), op(op), a(a) {} + ~UnaryExpr(); - virtual int evaluateInt(ResourceCompiler *ctx); + virtual int evaluateInt(ResourceCompiler *ctx); }; class IdentifierExpr : public Expression { public: - std::string id; - std::vector arguments; - IdentifierExpr(std::string id, yy::location loc); + std::string id; + std::vector arguments; + IdentifierExpr(std::string id, yy::location loc); - void addArgument(ExprPtr e); - ExprPtr lookup(ResourceCompiler *ctx); - virtual int evaluateInt(ResourceCompiler *ctx); - virtual std::string evaluateString(ResourceCompiler *ctx); + void addArgument(ExprPtr e); + ExprPtr lookup(ResourceCompiler *ctx); + virtual int evaluateInt(ResourceCompiler *ctx); + virtual std::string evaluateString(ResourceCompiler *ctx); }; class CountOfExpr : public Expression { - IdentifierExprPtr arg; + IdentifierExprPtr arg; public: - CountOfExpr(IdentifierExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} - virtual int evaluateInt(ResourceCompiler *ctx); + CountOfExpr(IdentifierExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} + virtual int evaluateInt(ResourceCompiler *ctx); }; class ArrayIndexExpr : public Expression { - IdentifierExprPtr arg; + IdentifierExprPtr arg; public: - ArrayIndexExpr(IdentifierExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} - virtual int evaluateInt(ResourceCompiler *ctx); + ArrayIndexExpr(IdentifierExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} + virtual int evaluateInt(ResourceCompiler *ctx); }; class ReadExpr : public Expression { - ExprPtr arg; + ExprPtr arg; public: - ReadExpr(ExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} - virtual std::string evaluateString(ResourceCompiler *ctx); + ReadExpr(ExprPtr arg, yy::location loc) : Expression(loc), arg(arg) {} + virtual std::string evaluateString(ResourceCompiler *ctx); }; class UnimplementedExpr : public Expression { - std::string msg; + std::string msg; public: - UnimplementedExpr(std::string msg, yy::location loc) : Expression(loc), msg(msg) {} - virtual int evaluateInt(ResourceCompiler *ctx); - virtual std::string evaluateString(ResourceCompiler *ctx); + UnimplementedExpr(std::string msg, yy::location loc) : Expression(loc), msg(msg) {} + virtual int evaluateInt(ResourceCompiler *ctx); + virtual std::string evaluateString(ResourceCompiler *ctx); }; class PeekExpr : public Expression { - ExprPtr addr; - ExprPtr offset; - ExprPtr size; + ExprPtr addr; + ExprPtr offset; + ExprPtr size; public: - PeekExpr(ExprPtr addr, ExprPtr offset, ExprPtr size, yy::location loc); - PeekExpr(ExprPtr addr, int size, yy::location loc); - virtual int evaluateInt(ResourceCompiler *ctx); + PeekExpr(ExprPtr addr, ExprPtr offset, ExprPtr size, yy::location loc); + PeekExpr(ExprPtr addr, int size, yy::location loc); + virtual int evaluateInt(ResourceCompiler *ctx); }; #endif // EXPRESSION_H diff --git a/Rez/ResSpec.h b/Rez/ResSpec.h index 305817da0a..ddc8d6e6c8 100644 --- a/Rez/ResSpec.h +++ b/Rez/ResSpec.h @@ -6,19 +6,19 @@ class ResSpec : public ResRef { - int attr_; - std::string name_; + int attr_; + std::string name_; public: - ResSpec() : attr_(0) {} - ResSpec(ResType type, int id, int attr = 0, std::string name = "") - : ResRef(type, id), attr_(attr), name_(name) - {} + ResSpec() : attr_(0) {} + ResSpec(ResType type, int id, int attr = 0, std::string name = "") + : ResRef(type, id), attr_(attr), name_(name) + {} - int& attr() { return attr_; } - int attr() const { return attr_; } - std::string& name() { return name_; } - const std::string& name() const { return name_; } + int& attr() { return attr_; } + int attr() const { return attr_; } + std::string& name() { return name_; } + const std::string& name() const { return name_; } }; #endif // REZSPEC_H diff --git a/Rez/ResourceCompiler.cc b/Rez/ResourceCompiler.cc index 9efe0a23bc..39a6432e6a 100644 --- a/Rez/ResourceCompiler.cc +++ b/Rez/ResourceCompiler.cc @@ -5,164 +5,164 @@ #include "Diagnostic.h" ResourceCompiler::ResourceCompiler( - RezWorld& world, TypeDefinitionPtr type, CompoundExprPtr body, bool verboseFlag) - : world(world), - typeDefinition(type), - body(body), - currentField(nullptr) + RezWorld& world, TypeDefinitionPtr type, CompoundExprPtr body, bool verboseFlag) + : world(world), + typeDefinition(type), + body(body), + currentField(nullptr) { - this->verboseFlag = verboseFlag; + this->verboseFlag = verboseFlag; } BinaryOutput::BinaryOutput() - : verboseFlag(false) + : verboseFlag(false) { - reset(true); + reset(true); } void BinaryOutput::reset(bool prePass) { - currentOffset = 0; - if(!prePass) - prePassData = std::move(data); - data.clear(); - this->prePass = prePass; + currentOffset = 0; + if(!prePass) + prePassData = std::move(data); + data.clear(); + this->prePass = prePass; } std::string BinaryOutput::resourceData() { - return std::string(data.begin(), data.end()); + return std::string(data.begin(), data.end()); } void BinaryOutput::write(int nBits, int value) { - if(verboseFlag) - std::cout << "[" << nBits << " bits] = " << std::hex << value << std::dec << std::endl; + if(verboseFlag) + std::cout << "[" << nBits << " bits] = " << std::hex << value << std::dec << std::endl; - unsigned mask = 1 << (nBits-1); + unsigned mask = 1 << (nBits-1); - for(int i = 0; i < nBits; i++) - { - bool bit = (value & mask) != 0; + for(int i = 0; i < nBits; i++) + { + bool bit = (value & mask) != 0; - if(currentOffset % 8 == 0) - data.push_back(bit ? 0x80 : 0); - else if(bit) - data.back() |= (0x80 >> (currentOffset % 8)); - ++currentOffset; + if(currentOffset % 8 == 0) + data.push_back(bit ? 0x80 : 0); + else if(bit) + data.back() |= (0x80 >> (currentOffset % 8)); + ++currentOffset; - mask >>= 1; - } + mask >>= 1; + } - //currentOffset += nBits; + //currentOffset += nBits; } int BinaryOutput::peek(int bitPos, int size) { - unsigned bytePos = bitPos / 8; - unsigned endBytePos = (bitPos + size - 1) / 8 + 1; + unsigned bytePos = bitPos / 8; + unsigned endBytePos = (bitPos + size - 1) / 8 + 1; - unsigned bitPosInByte = bitPos % 8; - unsigned outPos = 32 - size; + unsigned bitPosInByte = bitPos % 8; + unsigned outPos = 32 - size; - unsigned val = 0; + unsigned val = 0; - for(unsigned i = bytePos; i != endBytePos; ++i) - { - unsigned byte; - if(i < data.size()) - byte = data[i]; - else if(i < prePassData.size()) - byte = prePassData[i]; - else - byte = 0; + for(unsigned i = bytePos; i != endBytePos; ++i) + { + unsigned byte; + if(i < data.size()) + byte = data[i]; + else if(i < prePassData.size()) + byte = prePassData[i]; + else + byte = 0; - unsigned read = byte << (bitPosInByte + 24); - val |= (read >> outPos); + unsigned read = byte << (bitPosInByte + 24); + val |= (read >> outPos); - outPos += 8 - bitPosInByte; + outPos += 8 - bitPosInByte; - bitPosInByte = 0; - } + bitPosInByte = 0; + } - return val; + return val; } ExprPtr ResourceCompiler::lookupIdentifier(std::string name, const Subscripts &sub) { - if(currentField) - { - if(ExprPtr val = currentField->lookupNamedValue(name)) - { - return val; - } - } + if(currentField) + { + if(ExprPtr val = currentField->lookupNamedValue(name)) + { + return val; + } + } - auto p = labelValues.find(std::make_pair(name, sub)); - if(p != labelValues.end()) - return p->second; + auto p = labelValues.find(std::make_pair(name, sub)); + if(p != labelValues.end()) + return p->second; - //std::cerr << "ID lookup failed: " << name << std::endl; + //std::cerr << "ID lookup failed: " << name << std::endl; - return nullptr; + return nullptr; } void ResourceCompiler::defineLabel(const std::string &name) { - labelValues[std::make_pair(name,currentSubscripts)] = std::make_shared(currentOffset, yy::location()); + labelValues[std::make_pair(name,currentSubscripts)] = std::make_shared(currentOffset, yy::location()); } void ResourceCompiler::compile() { - if(verboseFlag) std::cout << "(first pass)\n"; - reset(true); - typeDefinition->compile(body, this, true); - if(verboseFlag) std::cout << "(second pass)\n"; + if(verboseFlag) std::cout << "(first pass)\n"; + reset(true); + typeDefinition->compile(body, this, true); + if(verboseFlag) std::cout << "(second pass)\n"; - reset(false); - typeDefinition->compile(body, this, false); - if(verboseFlag) std::cout << "(done)\n"; + reset(false); + typeDefinition->compile(body, this, false); + if(verboseFlag) std::cout << "(done)\n"; } int ResourceCompiler::getArrayCount(const std::string &name) { - Subscripts sub = currentSubscripts; - for(;;) - { - auto p = arrayCounts.find(std::make_pair(name, sub)); - if(p != arrayCounts.end()) - return p->second; + Subscripts sub = currentSubscripts; + for(;;) + { + auto p = arrayCounts.find(std::make_pair(name, sub)); + if(p != arrayCounts.end()) + return p->second; - if(sub.empty()) - return 0; /* ### */ - sub.popSubscript(); - } + if(sub.empty()) + return 0; /* ### */ + sub.popSubscript(); + } } int ResourceCompiler::getArrayIndex(const std::string &arrayName) { - return curArrayIndices[arrayName]; + return curArrayIndices[arrayName]; } void ResourceCompiler::problem(Diagnostic d) { - if(!prePass) - world.problem(d); + if(!prePass) + world.problem(d); } void ResourceCompiler::beginArrayScope(std::string &arrayName, int index) { - if(arrayName != "") - { - curArrayIndices[arrayName] = index; - int& count = arrayCounts[std::make_pair(arrayName, currentSubscripts)]; - if(count < index) - count = index; - arrayCounts[std::make_pair(arrayName, Subscripts())] = count; - //std::cout << "count for " << arrayName << " is " << count << std::endl; - } - currentSubscripts.addSubscript(index); + if(arrayName != "") + { + curArrayIndices[arrayName] = index; + int& count = arrayCounts[std::make_pair(arrayName, currentSubscripts)]; + if(count < index) + count = index; + arrayCounts[std::make_pair(arrayName, Subscripts())] = count; + //std::cout << "count for " << arrayName << " is " << count << std::endl; + } + currentSubscripts.addSubscript(index); } Subscripts::Subscripts() @@ -175,26 +175,26 @@ Subscripts::~Subscripts() void Subscripts::addSubscript(int x) { - subscripts.push_back(x); + subscripts.push_back(x); } void Subscripts::popSubscript() { - subscripts.pop_back(); + subscripts.pop_back(); } bool Subscripts::operator<(const Subscripts &other) const { - if(subscripts.size() < other.subscripts.size()) - return true; - if(other.subscripts.size() < subscripts.size()) - return false; - for(int i = 0, n = subscripts.size(); i < n; i++) - { - if(subscripts[i] < other.subscripts[i]) - return true; - else if(subscripts[i] > other.subscripts[i]) - return false; - } - return false; + if(subscripts.size() < other.subscripts.size()) + return true; + if(other.subscripts.size() < subscripts.size()) + return false; + for(int i = 0, n = subscripts.size(); i < n; i++) + { + if(subscripts[i] < other.subscripts[i]) + return true; + else if(subscripts[i] > other.subscripts[i]) + return false; + } + return false; } diff --git a/Rez/ResourceCompiler.h b/Rez/ResourceCompiler.h index 890a564db5..6177339b44 100644 --- a/Rez/ResourceCompiler.h +++ b/Rez/ResourceCompiler.h @@ -10,83 +10,83 @@ class Diagnostic; class Subscripts { - std::vector subscripts; + std::vector subscripts; public: - Subscripts(); - ~Subscripts(); + Subscripts(); + ~Subscripts(); - void addSubscript(int x); - void popSubscript(); - bool operator<(const Subscripts& other) const; - bool empty() const { return subscripts.empty(); } + void addSubscript(int x); + void popSubscript(); + bool operator<(const Subscripts& other) const; + bool empty() const { return subscripts.empty(); } }; class BinaryOutput { protected: - int currentOffset; - std::vector data; - std::vector prePassData; - bool verboseFlag; - bool prePass; + int currentOffset; + std::vector data; + std::vector prePassData; + bool verboseFlag; + bool prePass; public: - BinaryOutput(); - void reset(bool prePass); + BinaryOutput(); + void reset(bool prePass); - std::string resourceData(); + std::string resourceData(); - void reserve(int nBits) { write(nBits, 0); } - void write(int nBits, int value); - int tell() { return currentOffset; } + void reserve(int nBits) { write(nBits, 0); } + void write(int nBits, int value); + int tell() { return currentOffset; } - int peek(int bitPos, int size); + int peek(int bitPos, int size); - bool isPrePass() { return prePass; } + bool isPrePass() { return prePass; } }; class ResourceCompiler : public BinaryOutput { - RezWorld& world; - TypeDefinitionPtr typeDefinition; - CompoundExprPtr body; - std::map, ExprPtr> labelValues; - std::map, int> arrayCounts; - std::map curArrayIndices; - Field* currentField; - Subscripts currentSubscripts; + RezWorld& world; + TypeDefinitionPtr typeDefinition; + CompoundExprPtr body; + std::map, ExprPtr> labelValues; + std::map, int> arrayCounts; + std::map curArrayIndices; + Field* currentField; + Subscripts currentSubscripts; - void beginArrayScope(std::string& arrayName, int index); + void beginArrayScope(std::string& arrayName, int index); public: - ResourceCompiler(RezWorld& world, TypeDefinitionPtr type, CompoundExprPtr body, bool verboseFlag); + ResourceCompiler(RezWorld& world, TypeDefinitionPtr type, CompoundExprPtr body, bool verboseFlag); - ExprPtr lookupIdentifier(std::string name, const Subscripts& sub = Subscripts()); + ExprPtr lookupIdentifier(std::string name, const Subscripts& sub = Subscripts()); - void defineLabel(const std::string& name); - void compile(); + void defineLabel(const std::string& name); + void compile(); - int getArrayCount(const std::string& arrayName); - int getArrayIndex(const std::string& arrayName); + int getArrayCount(const std::string& arrayName); + int getArrayIndex(const std::string& arrayName); - class FieldScope - { - ResourceCompiler *compiler; - public: - FieldScope(ResourceCompiler* compiler, Field *field) - : compiler(compiler) { compiler->currentField = field; } - ~FieldScope() { compiler->currentField = nullptr; } - }; + class FieldScope + { + ResourceCompiler *compiler; + public: + FieldScope(ResourceCompiler* compiler, Field *field) + : compiler(compiler) { compiler->currentField = field; } + ~FieldScope() { compiler->currentField = nullptr; } + }; - class ArrayScope - { - ResourceCompiler *compiler; - public: - ArrayScope(ResourceCompiler* compiler, std::string& arrayName, int index) - : compiler(compiler) { compiler->beginArrayScope(arrayName, index); } - ~ArrayScope() { compiler->currentSubscripts.popSubscript(); } - }; + class ArrayScope + { + ResourceCompiler *compiler; + public: + ArrayScope(ResourceCompiler* compiler, std::string& arrayName, int index) + : compiler(compiler) { compiler->beginArrayScope(arrayName, index); } + ~ArrayScope() { compiler->currentSubscripts.popSubscript(); } + }; - void problem(Diagnostic d); + void problem(Diagnostic d); }; diff --git a/Rez/ResourceDefinitions.cc b/Rez/ResourceDefinitions.cc index 32b5b09c64..585473697a 100644 --- a/Rez/ResourceDefinitions.cc +++ b/Rez/ResourceDefinitions.cc @@ -8,10 +8,10 @@ std::ostream &operator<<(std::ostream &out, TypeSpec ts) { - out << ts.getType(); - if(ts.hasID()) - out << " (" << ts.getID() << ")"; - return out; + out << ts.getType(); + if(ts.hasID()) + out << " (" << ts.getID() << ")"; + return out; } @@ -22,38 +22,38 @@ FieldList::~FieldList() void FieldList::addField(FieldPtr field, yy::location loc) { - field->location = loc; - fields.push_back(field); + field->location = loc; + fields.push_back(field); } void FieldList::addLabel(std::string name, yy::location loc) { - addField(std::make_shared(name), loc); + addField(std::make_shared(name), loc); } void FieldList::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - CompoundExprPtr compound = std::dynamic_pointer_cast(expr); - assert(compound); + CompoundExprPtr compound = std::dynamic_pointer_cast(expr); + assert(compound); - int i = 0; - for(FieldPtr f : fields) - { - if(f->needsValue()) - { - if(i >= compound->size()) - compiler->problem(Diagnostic(Diagnostic::error,"not enough values specified", compound->location)); - else - f->compile(compound->getItem(i++), compiler, prePass); - } - else - f->compile(nullptr, compiler, prePass); - } - if(i < compound->size()) - { - compiler->problem(Diagnostic(Diagnostic::error,"extra value specified", - compound->getItem(i)->location)); - } + int i = 0; + for(FieldPtr f : fields) + { + if(f->needsValue()) + { + if(i >= compound->size()) + compiler->problem(Diagnostic(Diagnostic::error,"not enough values specified", compound->location)); + else + f->compile(compound->getItem(i++), compiler, prePass); + } + else + f->compile(nullptr, compiler, prePass); + } + if(i < compound->size()) + { + compiler->problem(Diagnostic(Diagnostic::error,"extra value specified", + compound->getItem(i)->location)); + } } @@ -61,282 +61,282 @@ void FieldList::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) void SimpleField::addNamedValue(std::string n) { - if(lastNamedValue) - addNamedValue(n, std::make_shared( - BinaryOp::PLUS, lastNamedValue, std::make_shared(1, yy::location()), yy::location())); - else - addNamedValue(n, std::make_shared(0, yy::location())); + if(lastNamedValue) + addNamedValue(n, std::make_shared( + BinaryOp::PLUS, lastNamedValue, std::make_shared(1, yy::location()), yy::location())); + else + addNamedValue(n, std::make_shared(0, yy::location())); } void SimpleField::addNamedValue(std::string n, ExprPtr val) { - namedValues[n] = val; - lastNamedValue = val; + namedValues[n] = val; + lastNamedValue = val; } ExprPtr SimpleField::lookupNamedValue(std::string n) { - auto p = namedValues.find(n); - if(p != namedValues.end()) - return p->second; - else - return nullptr; + auto p = namedValues.find(n); + if(p != namedValues.end()) + return p->second; + else + return nullptr; } bool SimpleField::needsValue() { - return !value; + return !value; } void SimpleField::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - switch(type) - { - case Type::bitstring: - case Type::boolean: - case Type::byte: - case Type::integer: - case Type::longint: - compileInt(expr, compiler, prePass); - break; - case Type::string: - case Type::wstring: - case Type::pstring: - case Type::char_: - compileString(expr, compiler, prePass); - break; + switch(type) + { + case Type::bitstring: + case Type::boolean: + case Type::byte: + case Type::integer: + case Type::longint: + compileInt(expr, compiler, prePass); + break; + case Type::string: + case Type::wstring: + case Type::pstring: + case Type::char_: + compileString(expr, compiler, prePass); + break; - case Type::rect: - case Type::point: - compileCompound(expr, compiler, prePass); - break; + case Type::rect: + case Type::point: + compileCompound(expr, compiler, prePass); + break; - } + } } void SimpleField::compileString(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - std::string str; - { - ResourceCompiler::FieldScope scope(compiler, this); - str = (value ? value : expr)->evaluateString(compiler); - } + std::string str; + { + ResourceCompiler::FieldScope scope(compiler, this); + str = (value ? value : expr)->evaluateString(compiler); + } - if(arrayCount || type == Type::char_) - { - unsigned requestedSize = type == Type::char_ ? 1 : arrayCount->evaluateInt(compiler); - if(requestedSize < str.size()) - str.erase(str.begin() + requestedSize, str.end()); - else if(requestedSize > str.size()) - str.insert(str.end(),requestedSize - str.size(), '\0'); - } + if(arrayCount || type == Type::char_) + { + unsigned requestedSize = type == Type::char_ ? 1 : arrayCount->evaluateInt(compiler); + if(requestedSize < str.size()) + str.erase(str.begin() + requestedSize, str.end()); + else if(requestedSize > str.size()) + str.insert(str.end(),requestedSize - str.size(), '\0'); + } - int count = str.size(); + int count = str.size(); - if(type == Type::pstring) - { - if(count > 255) - { - str.erase(str.begin() + 255, str.end()); - count = 255; - } - compiler->write(8, count); - } - else if(type == Type::wstring) - { - if(count > 65535) - { - str.erase(str.begin() + 65535, str.end()); - count = 65535; - } - compiler->write(16, count); - } + if(type == Type::pstring) + { + if(count > 255) + { + str.erase(str.begin() + 255, str.end()); + count = 255; + } + compiler->write(8, count); + } + else if(type == Type::wstring) + { + if(count > 65535) + { + str.erase(str.begin() + 65535, str.end()); + count = 65535; + } + compiler->write(16, count); + } - for(char c : str) - compiler->write(8, c); + for(char c : str) + compiler->write(8, c); } void SimpleField::compileInt(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - int bitSize = 0; + int bitSize = 0; - switch(type) - { - case Type::bitstring: - bitSize = arrayCount->evaluateInt(compiler); - break; - case Type::boolean: - bitSize = 1; - break; - case Type::byte: - bitSize = 8; - break; - case Type::integer: - bitSize = 16; - break; - case Type::longint: - bitSize = 32; - break; - default: - assert(false); - } + switch(type) + { + case Type::bitstring: + bitSize = arrayCount->evaluateInt(compiler); + break; + case Type::boolean: + bitSize = 1; + break; + case Type::byte: + bitSize = 8; + break; + case Type::integer: + bitSize = 16; + break; + case Type::longint: + bitSize = 32; + break; + default: + assert(false); + } - int actualValue = 0; - ResourceCompiler::FieldScope scope(compiler, this); - actualValue = (value ? value : expr)->evaluateInt(compiler); + int actualValue = 0; + ResourceCompiler::FieldScope scope(compiler, this); + actualValue = (value ? value : expr)->evaluateInt(compiler); - compiler->write(bitSize, actualValue); + compiler->write(bitSize, actualValue); } void SimpleField::compileCompound(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - ExprPtr val = value ? value : expr; - if(IdentifierExprPtr id = std::dynamic_pointer_cast(val)) - { - ResourceCompiler::FieldScope scope(compiler, this); - val = id->lookup(compiler); - } + ExprPtr val = value ? value : expr; + if(IdentifierExprPtr id = std::dynamic_pointer_cast(val)) + { + ResourceCompiler::FieldScope scope(compiler, this); + val = id->lookup(compiler); + } - int count = 0; - switch(type) - { - case Type::rect: - count = 4; - break; - case Type::point: - count = 2; - break; - default: - assert(false); - } + int count = 0; + switch(type) + { + case Type::rect: + count = 4; + break; + case Type::point: + count = 2; + break; + default: + assert(false); + } - CompoundExprPtr compound = std::dynamic_pointer_cast(val); - if(!compound || compound->size() != count) - { - expr->error(compiler, std::string("expected ") + (type == Type::rect ? "rect {t,l,b,r}." : "point {v,h}.")); - return; - } - assert(compound); - assert(compound->size() == count); + CompoundExprPtr compound = std::dynamic_pointer_cast(val); + if(!compound || compound->size() != count) + { + expr->error(compiler, std::string("expected ") + (type == Type::rect ? "rect {t,l,b,r}." : "point {v,h}.")); + return; + } + assert(compound); + assert(compound->size() == count); - for(int i = 0; i < count; i++) - { - int x = compound->getItem(i)->evaluateInt(compiler); - compiler->write(16, x); - } + for(int i = 0; i < count; i++) + { + int x = compound->getItem(i)->evaluateInt(compiler); + compiler->write(16, x); + } } ArrayField::ArrayField(std::string name, ExprPtr count) - : name(name), arrayCount(count) + : name(name), arrayCount(count) { } void ArrayField::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - CompoundExprPtr compound = std::dynamic_pointer_cast(expr); - assert(compound); + CompoundExprPtr compound = std::dynamic_pointer_cast(expr); + assert(compound); - int i = 0; - int n = compound->size(); + int i = 0; + int n = compound->size(); - int iterations = 0; - while(i < n) - { - ++iterations; - ResourceCompiler::ArrayScope scope(compiler, name, iterations); - for(FieldPtr f : fields) - { - if(f->needsValue()) - { - assert(i < n); - f->compile(compound->getItem(i++), compiler, prePass); - } - else - f->compile(nullptr, compiler, prePass); - } - } + int iterations = 0; + while(i < n) + { + ++iterations; + ResourceCompiler::ArrayScope scope(compiler, name, iterations); + for(FieldPtr f : fields) + { + if(f->needsValue()) + { + assert(i < n); + f->compile(compound->getItem(i++), compiler, prePass); + } + else + f->compile(nullptr, compiler, prePass); + } + } - if(!prePass && arrayCount) - { - int expected = arrayCount->evaluateInt(compiler); - assert(expected == iterations); - } + if(!prePass && arrayCount) + { + int expected = arrayCount->evaluateInt(compiler); + assert(expected == iterations); + } } LabelField::LabelField(std::string name) - : name(name) + : name(name) { } bool LabelField::needsValue() { - return false; + return false; } void LabelField::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - compiler->defineLabel(name); + compiler->defineLabel(name); } void SwitchField::addCase(const std::string name, FieldListPtr alternative) { - cases[name] = alternative; + cases[name] = alternative; } void SwitchField::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - CaseExprPtr caseExpr = std::dynamic_pointer_cast(expr); - assert(caseExpr); + CaseExprPtr caseExpr = std::dynamic_pointer_cast(expr); + assert(caseExpr); - FieldListPtr caseDefinition = cases[caseExpr->tag]; - assert(caseDefinition); + FieldListPtr caseDefinition = cases[caseExpr->tag]; + assert(caseDefinition); - caseDefinition->compile(caseExpr->expr, compiler, prePass); + caseDefinition->compile(caseExpr->expr, compiler, prePass); } FillAlignField::FillAlignField(FillAlignField::Type type, bool isAlign, ExprPtr count) - : type(type), count(count), isAlign(isAlign) + : type(type), count(count), isAlign(isAlign) { } bool FillAlignField::needsValue() { - return false; + return false; } void FillAlignField::compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) { - int bitSize; - switch(type) - { - case Type::bit: bitSize = 1; break; - case Type::nibble: bitSize = 4; break; - case Type::byte: bitSize = 8; break; - case Type::word: bitSize = 16; break; - case Type::long_: bitSize = 32; break; - } + int bitSize; + switch(type) + { + case Type::bit: bitSize = 1; break; + case Type::nibble: bitSize = 4; break; + case Type::byte: bitSize = 8; break; + case Type::word: bitSize = 16; break; + case Type::long_: bitSize = 32; break; + } - int actualCount = 1; - if(count) - actualCount = count->evaluateInt(compiler); + int actualCount = 1; + if(count) + actualCount = count->evaluateInt(compiler); - for(int i = 0; i < actualCount; i++) - { - int n; - if(isAlign) - { - int mask = bitSize - 1; - int pos = compiler->tell(); - n = ((pos + mask) & ~mask) - pos; - } - else - n = bitSize; - compiler->write(n, 0); - } + for(int i = 0; i < actualCount; i++) + { + int n; + if(isAlign) + { + int mask = bitSize - 1; + int pos = compiler->tell(); + n = ((pos + mask) & ~mask) - pos; + } + else + n = bitSize; + compiler->write(n, 0); + } } diff --git a/Rez/ResourceDefinitions.h b/Rez/ResourceDefinitions.h index 7b59d4d8a5..f090a3852c 100644 --- a/Rez/ResourceDefinitions.h +++ b/Rez/ResourceDefinitions.h @@ -12,29 +12,29 @@ class TypeSpec { - ResType type; - int id; + ResType type; + int id; public: - static const int noID = 65536; + static const int noID = 65536; - TypeSpec() : id(noID) {} - TypeSpec(ResType type) : type(type), id(noID) {} - TypeSpec(ResType type, int id) : type(type), id(id) {} + TypeSpec() : id(noID) {} + TypeSpec(ResType type) : type(type), id(noID) {} + TypeSpec(ResType type, int id) : type(type), id(id) {} - ResType getType() const { return type; } - int getID() const { return id; } + ResType getType() const { return type; } + int getID() const { return id; } - bool hasID() const { return id != noID; } + bool hasID() const { return id != noID; } - bool operator<(TypeSpec y) const - { - if(type < y.type) - return true; - else if(y.type < type) - return false; - else - return id < y.id; - } + bool operator<(TypeSpec y) const + { + if(type < y.type) + return true; + else if(y.type < type) + return false; + else + return id < y.id; + } }; std::ostream& operator<<(std::ostream& out, TypeSpec ts); @@ -45,85 +45,85 @@ class ResourceCompiler; class Field { public: - yy::location location; + yy::location location; - virtual ~Field() = default; + virtual ~Field() = default; - virtual bool needsValue() { return true; } + virtual bool needsValue() { return true; } - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) = 0; + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass) = 0; - virtual ExprPtr lookupNamedValue(std::string) { return nullptr; } + virtual ExprPtr lookupNamedValue(std::string) { return nullptr; } }; typedef std::shared_ptr FieldPtr; class SimpleField : public Field { public: - enum class Type - { - boolean, byte, integer, longint, rect, point, char_, - pstring, wstring, string, bitstring - }; + enum class Type + { + boolean, byte, integer, longint, rect, point, char_, + pstring, wstring, string, bitstring + }; - enum class Attrs - { - none = 0, hex = 1, key = 2, unsigned_ = 4, literal = 8, binary = 16 - }; + enum class Attrs + { + none = 0, hex = 1, key = 2, unsigned_ = 4, literal = 8, binary = 16 + }; - Type type; - Attrs attrs = Attrs::none; - ExprPtr arrayCount; + Type type; + Attrs attrs = Attrs::none; + ExprPtr arrayCount; - ExprPtr value; - std::map namedValues; - ExprPtr lastNamedValue; + ExprPtr value; + std::map namedValues; + ExprPtr lastNamedValue; - void addNamedValue(std::string n); - void addNamedValue(std::string n, ExprPtr val); - ExprPtr lookupNamedValue(std::string); + void addNamedValue(std::string n); + void addNamedValue(std::string n, ExprPtr val); + ExprPtr lookupNamedValue(std::string); - virtual bool needsValue(); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + virtual bool needsValue(); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); private: - void compileString(ExprPtr expr, ResourceCompiler *compiler, bool prePass); - void compileInt(ExprPtr expr, ResourceCompiler *compiler, bool prePass); - void compileCompound(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + void compileString(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + void compileInt(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + void compileCompound(ExprPtr expr, ResourceCompiler *compiler, bool prePass); }; typedef std::shared_ptr SimpleFieldPtr; class FillAlignField : public Field { public: - enum class Type - { - bit, nibble, byte, word, long_ - }; + enum class Type + { + bit, nibble, byte, word, long_ + }; - FillAlignField(Type type, bool isAlign, ExprPtr count = ExprPtr()); - virtual bool needsValue(); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + FillAlignField(Type type, bool isAlign, ExprPtr count = ExprPtr()); + virtual bool needsValue(); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); private: - Type type; - ExprPtr count; - bool isAlign; + Type type; + ExprPtr count; + bool isAlign; }; inline SimpleField::Attrs operator|(SimpleField::Attrs a, SimpleField::Attrs b) { - return SimpleField::Attrs( int(a) | int(b) ); + return SimpleField::Attrs( int(a) | int(b) ); } class LabelField : public Field { - std::string name; + std::string name; public: - LabelField(std::string name); + LabelField(std::string name); - virtual bool needsValue(); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + virtual bool needsValue(); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); }; typedef std::shared_ptr LabelFieldPtr; @@ -131,35 +131,35 @@ typedef std::shared_ptr LabelFieldPtr; class FieldList : public Field { protected: - std::vector fields; + std::vector fields; public: - virtual ~FieldList(); - void addField(FieldPtr field, yy::location loc); - void addLabel(std::string name, yy::location loc); + virtual ~FieldList(); + void addField(FieldPtr field, yy::location loc); + void addLabel(std::string name, yy::location loc); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); }; typedef std::shared_ptr FieldListPtr; class ArrayField : public FieldList { - std::string name; - ExprPtr arrayCount; + std::string name; + ExprPtr arrayCount; public: - ArrayField(std::string name /* or empty */, ExprPtr count /* may be null*/); + ArrayField(std::string name /* or empty */, ExprPtr count /* may be null*/); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); }; typedef std::shared_ptr ArrayFieldPtr; class SwitchField : public Field { - std::map cases; + std::map cases; public: - void addCase(const std::string name, FieldListPtr alternative); + void addCase(const std::string name, FieldListPtr alternative); - virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); + virtual void compile(ExprPtr expr, ResourceCompiler *compiler, bool prePass); }; typedef std::shared_ptr SwitchFieldPtr; diff --git a/Rez/Rez.cc b/Rez/Rez.cc index d186c3a6ee..d54d7775ed 100644 --- a/Rez/Rez.cc +++ b/Rez/Rez.cc @@ -19,157 +19,157 @@ static po::options_description desc; static void usage() { - std::cerr << "Usage: " << "Rez [options] input-file\n"; - std::cerr << desc << std::endl; + std::cerr << "Usage: " << "Rez [options] input-file\n"; + std::cerr << desc << std::endl; } static void CopyBinaryResources(RezWorld& world, const std::string& fn) { - ResourceFile copyRsrc(fn); - if(!copyRsrc.read()) - { - world.problem(Diagnostic(Diagnostic::error, "Could not read binary resource file " + fn, yy::location())); - } - else if(world.verboseFlag) - { - std::cerr << "Read " << copyRsrc.resources.countResources() << " resources from " << fn << "\n"; - } + ResourceFile copyRsrc(fn); + if(!copyRsrc.read()) + { + world.problem(Diagnostic(Diagnostic::error, "Could not read binary resource file " + fn, yy::location())); + } + else if(world.verboseFlag) + { + std::cerr << "Read " << copyRsrc.resources.countResources() << " resources from " << fn << "\n"; + } - world.getResources().addResources(copyRsrc.resources); + world.getResources().addResources(copyRsrc.resources); } int main(int argc, const char *argv[]) { - desc.add_options() - ("help,h", "show this help message") - ("output,o", po::value()->default_value("rez.output.rsrc"), "output file") - ("append,a", "append to existing output file") - ("type,t", po::value()->default_value("rsrc"), "output file finder type code") - ("creator,c", po::value()->default_value("RSED"), "output file finder creator code") - ("define,D", po::value>(), "predefine preprocessor symbol") - ("include,I", po::value>(), "add include file path") - ("copy", po::value>(), "copy resources from other resource file") - ("cc", po::value>(), "also write output to another file") - ("debug,d", "debug logging") - ("data", po::value(), "copy data fork from another file") - ; - po::options_description hidden, alldesc; - hidden.add_options() - ("input", po::value>(), "input file" ) - ; - alldesc.add(desc).add(hidden); + desc.add_options() + ("help,h", "show this help message") + ("output,o", po::value()->default_value("rez.output.rsrc"), "output file") + ("append,a", "append to existing output file") + ("type,t", po::value()->default_value("rsrc"), "output file finder type code") + ("creator,c", po::value()->default_value("RSED"), "output file finder creator code") + ("define,D", po::value>(), "predefine preprocessor symbol") + ("include,I", po::value>(), "add include file path") + ("copy", po::value>(), "copy resources from other resource file") + ("cc", po::value>(), "also write output to another file") + ("debug,d", "debug logging") + ("data", po::value(), "copy data fork from another file") + ; + po::options_description hidden, alldesc; + hidden.add_options() + ("input", po::value>(), "input file" ) + ; + alldesc.add(desc).add(hidden); - po::variables_map options; - try - { - auto parsed = po::command_line_parser(argc, argv) - .options(alldesc) - .positional(po::positional_options_description().add("input", -1)) - .style(po::command_line_style::default_style) - .run(); + po::variables_map options; + try + { + auto parsed = po::command_line_parser(argc, argv) + .options(alldesc) + .positional(po::positional_options_description().add("input", -1)) + .style(po::command_line_style::default_style) + .run(); - po::store(parsed, options); - } - catch(po::error& e) - { - std::cerr << "ERROR: " << e.what() << std::endl << std::endl; - usage(); - return 1; - } + po::store(parsed, options); + } + catch(po::error& e) + { + std::cerr << "ERROR: " << e.what() << std::endl << std::endl; + usage(); + return 1; + } - po::notify(options); + po::notify(options); - if(options.count("help") - || (!options.count("input") && !options.count("copy") - && !options.count("output"))) - { - usage(); - return 0; - } + if(options.count("help") + || (!options.count("input") && !options.count("copy") + && !options.count("output"))) + { + usage(); + return 0; + } - RezWorld world; + RezWorld world; - if(options.count("debug")) - world.verboseFlag = true; + if(options.count("debug")) + world.verboseFlag = true; - std::string outfile = options["output"].as(); - ResourceFile rsrcFile(outfile); + std::string outfile = options["output"].as(); + ResourceFile rsrcFile(outfile); - if(options.count("append")) - { - rsrcFile.read(); + if(options.count("append")) + { + rsrcFile.read(); - world.getResources().addResources(rsrcFile.resources); - } + world.getResources().addResources(rsrcFile.resources); + } - if(options.count("data")) - { - std::string fn = options["data"].as(); - ResourceFile dataFile(fn); - if(!dataFile.read()) - world.problem(Diagnostic(Diagnostic::error, "Could not read dataresource file " + fn, yy::location())); - rsrcFile.data = dataFile.data; - } + if(options.count("data")) + { + std::string fn = options["data"].as(); + ResourceFile dataFile(fn); + if(!dataFile.read()) + world.problem(Diagnostic(Diagnostic::error, "Could not read dataresource file " + fn, yy::location())); + rsrcFile.data = dataFile.data; + } - if(options.count("copy")) - for(std::string fn : options["copy"].as>()) - CopyBinaryResources(world, fn); + if(options.count("copy")) + for(std::string fn : options["copy"].as>()) + CopyBinaryResources(world, fn); - if(options.count("input")) - for(std::string fn : options["input"].as>()) - { - fs::path path(fn); - if(path.extension() == ".rsrc" || path.extension() == ".bin") - { - CopyBinaryResources(world, fn); - } - else - { - try - { - RezLexer lexer(world, fn); + if(options.count("input")) + for(std::string fn : options["input"].as>()) + { + fs::path path(fn); + if(path.extension() == ".rsrc" || path.extension() == ".bin") + { + CopyBinaryResources(world, fn); + } + else + { + try + { + RezLexer lexer(world, fn); - if(options.count("define")) - for(std::string define : options["define"].as>()) - lexer.addDefine(define); - if(options.count("include")) - for(std::string path : options["include"].as>()) - lexer.addIncludePath(path); + if(options.count("define")) + for(std::string define : options["define"].as>()) + lexer.addDefine(define); + if(options.count("include")) + for(std::string path : options["include"].as>()) + lexer.addIncludePath(path); - if(world.verboseFlag) - { - std::cerr << "Compiling " << fn << "...\n"; - } + if(world.verboseFlag) + { + std::cerr << "Compiling " << fn << "...\n"; + } - RezParser parser(lexer, world); - parser.parse(); - } - catch(...) - { - world.problem(Diagnostic(Diagnostic::fatalError,"unknown error",yy::location(&fn))); - } - } - } + RezParser parser(lexer, world); + parser.parse(); + } + catch(...) + { + world.problem(Diagnostic(Diagnostic::fatalError,"unknown error",yy::location(&fn))); + } + } + } - if(world.hadErrors) - return 1; + if(world.hadErrors) + return 1; - rsrcFile.resources = world.getResources(); - rsrcFile.creator = options["creator"].as(); - rsrcFile.type = options["type"].as(); + rsrcFile.resources = world.getResources(); + rsrcFile.creator = options["creator"].as(); + rsrcFile.type = options["type"].as(); - if(world.verboseFlag) - { - std::cerr << "Writing " << rsrcFile.resources.countResources() << " resources.\n"; - } - rsrcFile.write(); + if(world.verboseFlag) + { + std::cerr << "Writing " << rsrcFile.resources.countResources() << " resources.\n"; + } + rsrcFile.write(); - if(options.count("cc")) - for(std::string ccFile : options["cc"].as>()) - { - rsrcFile.assign(ccFile); - rsrcFile.write(); - } + if(options.count("cc")) + for(std::string ccFile : options["cc"].as>()) + { + rsrcFile.assign(ccFile); + rsrcFile.write(); + } - return 0; + return 0; } diff --git a/Rez/RezLexer.cc b/Rez/RezLexer.cc index d313f0f603..2bd6bf8f17 100644 --- a/Rez/RezLexer.cc +++ b/Rez/RezLexer.cc @@ -15,112 +15,112 @@ using namespace boost::wave; static std::string readContents(std::istream&& instream) { - instream.unsetf(std::ios::skipws); + instream.unsetf(std::ios::skipws); - return std::string(std::istreambuf_iterator(instream.rdbuf()), - std::istreambuf_iterator()); + return std::string(std::istreambuf_iterator(instream.rdbuf()), + std::istreambuf_iterator()); } static std::string preFilter(std::string str) { - boost::regex endif("#endif[^\r\n]*"); - str = boost::regex_replace(str, endif, "#endif"); + boost::regex endif("#endif[^\r\n]*"); + str = boost::regex_replace(str, endif, "#endif"); - boost::regex dollar_escape("\\\\\\$([a-zA-Z0-9][a-zA-Z0-9])"); - str = boost::regex_replace(str, dollar_escape, "\\\\0x$1"); + boost::regex dollar_escape("\\\\\\$([a-zA-Z0-9][a-zA-Z0-9])"); + str = boost::regex_replace(str, dollar_escape, "\\\\0x$1"); - if(str.size() == 0 || str[str.size()-1] != '\n') - str += "\n"; - return str; + if(str.size() == 0 || str[str.size()-1] != '\n') + str += "\n"; + return str; } struct load_file_to_string_filtered { - template - class inner - { - public: - template - static void init_iterators(IterContextT &iter_ctx, - PositionT const &act_pos, language_support language) - { - typedef typename IterContextT::iterator_type iterator_type; + template + class inner + { + public: + template + static void init_iterators(IterContextT &iter_ctx, + PositionT const &act_pos, language_support language) + { + typedef typename IterContextT::iterator_type iterator_type; - // read in the file - std::ifstream instream(iter_ctx.filename.c_str()); - if (!instream.is_open()) { - BOOST_WAVE_THROW_CTX(iter_ctx.ctx, preprocess_exception, - bad_include_file, iter_ctx.filename.c_str(), act_pos); - return; - } + // read in the file + std::ifstream instream(iter_ctx.filename.c_str()); + if (!instream.is_open()) { + BOOST_WAVE_THROW_CTX(iter_ctx.ctx, preprocess_exception, + bad_include_file, iter_ctx.filename.c_str(), act_pos); + return; + } - iter_ctx.instring = preFilter(readContents(std::move(instream))); + iter_ctx.instring = preFilter(readContents(std::move(instream))); - iter_ctx.first = iterator_type( - iter_ctx.instring.begin(), iter_ctx.instring.end(), - PositionT(iter_ctx.filename), language); - iter_ctx.last = iterator_type(); - } + iter_ctx.first = iterator_type( + iter_ctx.instring.begin(), iter_ctx.instring.end(), + PositionT(iter_ctx.filename), language); + iter_ctx.last = iterator_type(); + } - private: - std::string instring; - }; + private: + std::string instring; + }; }; typedef wave::cpplexer::lex_iterator< - wave::cpplexer::lex_token<> > - lex_iterator_type; + wave::cpplexer::lex_token<> > + lex_iterator_type; typedef wave::context< - std::string::iterator, lex_iterator_type, - load_file_to_string_filtered> - context_type; + std::string::iterator, lex_iterator_type, + load_file_to_string_filtered> + context_type; typedef context_type::iterator_type pp_iterator_type; struct RezLexer::Priv { - std::string input; - context_type ctx; - pp_iterator_type iter; + std::string input; + context_type ctx; + pp_iterator_type iter; - Priv(std::string data, std::string name) - : input(data), ctx(input.begin(), input.end(), name.c_str()) - { - } + Priv(std::string data, std::string name) + : input(data), ctx(input.begin(), input.end(), name.c_str()) + { + } }; static std::string readInitial(RezWorld& world, std::string filename) { - std::ifstream in(filename); - if(!in.is_open()) - { - world.problem(Diagnostic(Diagnostic::error, - "could not open " + filename, yy::location())); - } - return readContents(std::move(in)); + std::ifstream in(filename); + if(!in.is_open()) + { + world.problem(Diagnostic(Diagnostic::error, + "could not open " + filename, yy::location())); + } + return readContents(std::move(in)); } RezLexer::RezLexer(RezWorld& world, std::string filename) - : RezLexer(world, filename, readInitial(world,filename)) + : RezLexer(world, filename, readInitial(world,filename)) { } RezLexer::RezLexer(RezWorld& world, std::string filename, const std::string &data) - : world(world), curFile(filename), lastLocation(&curFile) + : world(world), curFile(filename), lastLocation(&curFile) { - pImpl.reset(new Priv(preFilter(data), filename)); + pImpl.reset(new Priv(preFilter(data), filename)); - pImpl->ctx.add_macro_definition("DeRez=0"); - pImpl->ctx.add_macro_definition("Rez=1"); - pImpl->ctx.add_macro_definition("true=1"); - pImpl->ctx.add_macro_definition("false=0"); - pImpl->ctx.add_macro_definition("TRUE=1"); - pImpl->ctx.add_macro_definition("FALSE=0"); + pImpl->ctx.add_macro_definition("DeRez=0"); + pImpl->ctx.add_macro_definition("Rez=1"); + pImpl->ctx.add_macro_definition("true=1"); + pImpl->ctx.add_macro_definition("false=0"); + pImpl->ctx.add_macro_definition("TRUE=1"); + pImpl->ctx.add_macro_definition("FALSE=0"); - pImpl->iter = pImpl->ctx.begin(); + pImpl->iter = pImpl->ctx.begin(); } RezLexer::~RezLexer() @@ -132,61 +132,61 @@ RezLexer::~RezLexer() void RezLexer::addDefine(std::string str) { - pImpl->ctx.add_macro_definition(str); + pImpl->ctx.add_macro_definition(str); } void RezLexer::addIncludePath(std::string path) { - std::size_t pos = path.find(':'); - if(pos == std::string::npos) - { - pImpl->ctx.add_include_path(path.c_str()); - } - else - { - addIncludePath(path.substr(0,pos)); - addIncludePath(path.substr(pos + 1)); - } + std::size_t pos = path.find(':'); + if(pos == std::string::npos) + { + pImpl->ctx.add_include_path(path.c_str()); + } + else + { + addIncludePath(path.substr(0,pos)); + addIncludePath(path.substr(pos + 1)); + } } bool RezLexer::atEnd() { - return pImpl->iter == pImpl->ctx.end(); + return pImpl->iter == pImpl->ctx.end(); } RezLexer::WaveToken RezLexer::nextWave() { - try - { - if(pImpl->iter == pImpl->ctx.end()) - return WaveToken(); - else - { - WaveToken tok = *pImpl->iter++; - return tok; - } - } - catch(const preprocess_exception& e) - { - curFile = e.file_name(); - auto yypos = yy::position(&curFile, e.line_no(), e.column_no()); - yy::location loc(yypos); - lastLocation = loc; + try + { + if(pImpl->iter == pImpl->ctx.end()) + return WaveToken(); + else + { + WaveToken tok = *pImpl->iter++; + return tok; + } + } + catch(const preprocess_exception& e) + { + curFile = e.file_name(); + auto yypos = yy::position(&curFile, e.line_no(), e.column_no()); + yy::location loc(yypos); + lastLocation = loc; - world.problem(Diagnostic( - e.severity_level(e.get_errorcode()) >= util::severity_error - ? Diagnostic::error - : Diagnostic::warning, - preprocess_exception::error_text(e.get_errorcode()), loc)); - if(e.is_recoverable()) - return nextWave(); - else - return WaveToken(); - } + world.problem(Diagnostic( + e.severity_level(e.get_errorcode()) >= util::severity_error + ? Diagnostic::error + : Diagnostic::warning, + preprocess_exception::error_text(e.get_errorcode()), loc)); + if(e.is_recoverable()) + return nextWave(); + else + return WaveToken(); + } } RezLexer::WaveToken RezLexer::peekWave() { - return pImpl->iter == pImpl->ctx.end() ? WaveToken() : *pImpl->iter; + return pImpl->iter == pImpl->ctx.end() ? WaveToken() : *pImpl->iter; } diff --git a/Rez/RezLexer.h b/Rez/RezLexer.h index 29788fb26b..4fe7f036bd 100644 --- a/Rez/RezLexer.h +++ b/Rez/RezLexer.h @@ -11,28 +11,28 @@ class RezWorld; class RezLexer { - RezWorld& world; - struct Priv; - std::unique_ptr pImpl; + RezWorld& world; + struct Priv; + std::unique_ptr pImpl; - std::string curFile; - yy::location lastLocation; + std::string curFile; + yy::location lastLocation; - class WaveToken; + class WaveToken; - bool atEnd(); - WaveToken nextWave(); - WaveToken peekWave(); + bool atEnd(); + WaveToken nextWave(); + WaveToken peekWave(); public: - RezLexer(RezWorld& world, std::string filename); - RezLexer(RezWorld& world, std::string filename, const std::string& data); - ~RezLexer(); + RezLexer(RezWorld& world, std::string filename); + RezLexer(RezWorld& world, std::string filename, const std::string& data); + ~RezLexer(); - RezSymbol nextToken(); + RezSymbol nextToken(); - void addDefine(std::string str); - void addIncludePath(std::string path); + void addDefine(std::string str); + void addIncludePath(std::string path); }; #endif // REZLEXER_H diff --git a/Rez/RezLexerNextToken.cc b/Rez/RezLexerNextToken.cc index 2725e3e678..fb69bd21b0 100644 --- a/Rez/RezLexerNextToken.cc +++ b/Rez/RezLexerNextToken.cc @@ -9,287 +9,287 @@ using namespace boost::wave; static int readInt(const char *str, const char *end = NULL, int baseOverride = 0) { - int x = 0; + int x = 0; - int base = 10; + int base = 10; - if(baseOverride) - base = baseOverride; - else if(*str == '0') - { - base = 8; - ++str; - if(*str == 'x' || *str == 'X') - { - base = 16; - ++str; - } - if(*str == 'b' || *str == 'B') - { - base = 2; - ++str; - } - } - else if(*str == 'b' || *str == 'B') - { - base = 2; - ++str; - } + if(baseOverride) + base = baseOverride; + else if(*str == '0') + { + base = 8; + ++str; + if(*str == 'x' || *str == 'X') + { + base = 16; + ++str; + } + if(*str == 'b' || *str == 'B') + { + base = 2; + ++str; + } + } + else if(*str == 'b' || *str == 'B') + { + base = 2; + ++str; + } - while(str != end && *str) - { - x *= base; - if(*str >= 'a' && *str <= 'z') - x += *str - 'a' + 10; - else if(*str >= 'A' && *str <= 'Z') - x += *str - 'A' + 10; - else if(*str >= '0' && *str <= '9') - x += *str - '0'; - str++; - } + while(str != end && *str) + { + x *= base; + if(*str >= 'a' && *str <= 'z') + x += *str - 'a' + 10; + else if(*str >= 'A' && *str <= 'Z') + x += *str - 'A' + 10; + else if(*str >= '0' && *str <= '9') + x += *str - '0'; + str++; + } - return x; + return x; } static int readCharLit(const char *str) { - const char *p = str + 1; - const char *e = str + strlen(str) - 1; + const char *p = str + 1; + const char *e = str + strlen(str) - 1; - if(e - p != 4) - std::cout << "warning: CHAR LITERAL " << str << "\n"; + if(e - p != 4) + std::cout << "warning: CHAR LITERAL " << str << "\n"; - int x = 0; - while(p != e) - { - x <<= 8; - x |= (*p) & 0xFF; - ++p; - } - return x; + int x = 0; + while(p != e) + { + x <<= 8; + x |= (*p) & 0xFF; + ++p; + } + return x; } static std::string readStringLit(const char *str) { - const char *p = str + 1; - const char *e = str + strlen(str) - 1; + const char *p = str + 1; + const char *e = str + strlen(str) - 1; - std::ostringstream out; + std::ostringstream out; - while(p != e) - { - if(*p == '\\') - { - ++p; - if(p != e) - { - switch(*p) - { - case 'n': - out << '\n'; ++p; - break; - case 'r': - out << '\r'; ++p; - break; - case 't': - out << '\t'; ++p; - break; - case '0': - case '1': - case '2': - case '3': - if(p + 3 > e) - continue; - if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) - { - if(p + 4 > e) - continue; - out << (char)readInt(p+2, p+4, 16); - p += 4; - } - else - { - out << (char)readInt(p, p+3, 8); - p += 3; - } - break; - case '$': - { - if(p + 3 > e) - continue; - out << (char)readInt(p+1, p+3, 16); - p += 3; - } - break; - } - } - } - else - { - out << *p++; - } - } + while(p != e) + { + if(*p == '\\') + { + ++p; + if(p != e) + { + switch(*p) + { + case 'n': + out << '\n'; ++p; + break; + case 'r': + out << '\r'; ++p; + break; + case 't': + out << '\t'; ++p; + break; + case '0': + case '1': + case '2': + case '3': + if(p + 3 > e) + continue; + if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) + { + if(p + 4 > e) + continue; + out << (char)readInt(p+2, p+4, 16); + p += 4; + } + else + { + out << (char)readInt(p, p+3, 8); + p += 3; + } + break; + case '$': + { + if(p + 3 > e) + continue; + out << (char)readInt(p+1, p+3, 16); + p += 3; + } + break; + } + } + } + else + { + out << *p++; + } + } - return out.str(); + return out.str(); } RezSymbol RezLexer::nextToken() { - for(auto tok = nextWave(); tok != T_EOI && tok != T_EOF; tok = nextWave()) - { - if(IS_CATEGORY(tok, WhiteSpaceTokenType)) - continue; - else if(IS_CATEGORY(tok, EOLTokenType)) - continue; - else if(tok == T_PP_LINE) - { - while(tok != T_EOI && tok != T_EOF && !IS_CATEGORY(tok, EOLTokenType)) - tok = nextWave(); - continue; - } - else - { - //std::cout << "{" << std::hex << (token_id)tok << std::dec << "|" << tok.get_value() << "}\n"; + for(auto tok = nextWave(); tok != T_EOI && tok != T_EOF; tok = nextWave()) + { + if(IS_CATEGORY(tok, WhiteSpaceTokenType)) + continue; + else if(IS_CATEGORY(tok, EOLTokenType)) + continue; + else if(tok == T_PP_LINE) + { + while(tok != T_EOI && tok != T_EOF && !IS_CATEGORY(tok, EOLTokenType)) + tok = nextWave(); + continue; + } + else + { + //std::cout << "{" << std::hex << (token_id)tok << std::dec << "|" << tok.get_value() << "}\n"; - auto pos = tok.get_position(); - curFile = pos.get_file().c_str(); - auto yypos = yy::position(&curFile, pos.get_line(), pos.get_column()); - yy::location loc(yypos); - lastLocation = loc; + auto pos = tok.get_position(); + curFile = pos.get_file().c_str(); + auto yypos = yy::position(&curFile, pos.get_line(), pos.get_column()); + yy::location loc(yypos); + lastLocation = loc; - if(tok == (UnknownTokenType | '"')) - { - return RezParser::make_STRINGLIT("Hello, world.", loc); - } - else if(IS_CATEGORY(tok, IdentifierTokenType) || IS_CATEGORY(tok, KeywordTokenType) || IS_CATEGORY(tok, BoolLiteralTokenType)) - { - typedef decltype(&RezParser::make_TYPE) memfun; + if(tok == (UnknownTokenType | '"')) + { + return RezParser::make_STRINGLIT("Hello, world.", loc); + } + else if(IS_CATEGORY(tok, IdentifierTokenType) || IS_CATEGORY(tok, KeywordTokenType) || IS_CATEGORY(tok, BoolLiteralTokenType)) + { + typedef decltype(&RezParser::make_TYPE) memfun; #define KEYWORD(upper, lower) \ { lower, &RezParser::make_ ## upper } - static std::unordered_map keywords = { - KEYWORD(TYPE, "type"), - KEYWORD(RESOURCE, "resource"), - KEYWORD(DATA, "data"), - KEYWORD(READ, "read"), - KEYWORD(INCLUDE, "include"), - KEYWORD(CHANGE, "change"), - KEYWORD(DELETE, "delete"), + static std::unordered_map keywords = { + KEYWORD(TYPE, "type"), + KEYWORD(RESOURCE, "resource"), + KEYWORD(DATA, "data"), + KEYWORD(READ, "read"), + KEYWORD(INCLUDE, "include"), + KEYWORD(CHANGE, "change"), + KEYWORD(DELETE, "delete"), - KEYWORD(ARRAY,"array"), - KEYWORD(SWITCH, "switch"), - KEYWORD(CASE, "case"), - KEYWORD(AS, "as"), - KEYWORD(FILL,"fill"), - KEYWORD(ALIGN, "align"), - KEYWORD(HEX,"hex"), - KEYWORD(KEY, "key"), - KEYWORD(WIDE,"wide"), - KEYWORD(UNSIGNED, "unsigned"), + KEYWORD(ARRAY,"array"), + KEYWORD(SWITCH, "switch"), + KEYWORD(CASE, "case"), + KEYWORD(AS, "as"), + KEYWORD(FILL,"fill"), + KEYWORD(ALIGN, "align"), + KEYWORD(HEX,"hex"), + KEYWORD(KEY, "key"), + KEYWORD(WIDE,"wide"), + KEYWORD(UNSIGNED, "unsigned"), KEYWORD(BINARY, "binary"), - KEYWORD(LITERAL, "literal"), - KEYWORD(BOOLEAN, "boolean"), - KEYWORD(BIT, "bit"), - KEYWORD(NIBBLE, "nibble"), - KEYWORD(BYTE, "byte"), - KEYWORD(CHAR, "char"), - KEYWORD(WORD, "word"), - KEYWORD(INTEGER, "integer"), - KEYWORD(LONG, "long"), - KEYWORD(LONGINT, "longint"), - KEYWORD(PSTRING, "pstring"), - KEYWORD(PSTRING, "wstring"), - KEYWORD(STRING, "string"), - KEYWORD(POINT, "point"), - KEYWORD(RECT, "rect"), - KEYWORD(BITSTRING, "bitstring"), + KEYWORD(LITERAL, "literal"), + KEYWORD(BOOLEAN, "boolean"), + KEYWORD(BIT, "bit"), + KEYWORD(NIBBLE, "nibble"), + KEYWORD(BYTE, "byte"), + KEYWORD(CHAR, "char"), + KEYWORD(WORD, "word"), + KEYWORD(INTEGER, "integer"), + KEYWORD(LONG, "long"), + KEYWORD(LONGINT, "longint"), + KEYWORD(PSTRING, "pstring"), + KEYWORD(PSTRING, "wstring"), + KEYWORD(STRING, "string"), + KEYWORD(POINT, "point"), + KEYWORD(RECT, "rect"), + KEYWORD(BITSTRING, "bitstring"), - KEYWORD(INTEGER, "int"), - KEYWORD(DOLLAR, "$"), + KEYWORD(INTEGER, "int"), + KEYWORD(DOLLAR, "$"), - KEYWORD(FUN_COUNTOF, "$$countof"), - KEYWORD(FUN_ARRAYINDEX, "$$arrayindex"), - KEYWORD(FUN_READ, "$$read"), - KEYWORD(FUN_BITFIELD, "$$bitfield"), - KEYWORD(FUN_WORD, "$$word"), - KEYWORD(FUN_BYTE, "$$byte"), - KEYWORD(FUN_LONG, "$$long"), - }; + KEYWORD(FUN_COUNTOF, "$$countof"), + KEYWORD(FUN_ARRAYINDEX, "$$arrayindex"), + KEYWORD(FUN_READ, "$$read"), + KEYWORD(FUN_BITFIELD, "$$bitfield"), + KEYWORD(FUN_WORD, "$$word"), + KEYWORD(FUN_BYTE, "$$byte"), + KEYWORD(FUN_LONG, "$$long"), + }; - std::string s = tok.get_value().c_str(); - if(s.size() >= 2 && s[0] == '$' && std::all_of(s.begin()+1, s.end(), [](char c) { return isxdigit(c); })) - return RezParser::make_INTLIT(readInt(s.c_str()+1, nullptr, 16), loc); + std::string s = tok.get_value().c_str(); + if(s.size() >= 2 && s[0] == '$' && std::all_of(s.begin()+1, s.end(), [](char c) { return isxdigit(c); })) + return RezParser::make_INTLIT(readInt(s.c_str()+1, nullptr, 16), loc); - std::string lower = s; - std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - auto p = keywords.find(lower); - if(p == keywords.end()) - { - //std::cout << "id: " << s << std::endl; - return RezParser::make_IDENTIFIER(lower, loc); - } - else - { - //std::cout << "key: " << s << std::endl; - return (*p->second)(loc); - } - } - else if(tok == T_INTLIT) - { - if(tok.get_value() == "0") - { - auto tok2 = peekWave(); - while(tok2 != T_EOI && tok2 != T_EOF && IS_CATEGORY(tok2, WhiteSpaceTokenType)) - nextWave(), tok2 = peekWave(); + std::string lower = s; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + auto p = keywords.find(lower); + if(p == keywords.end()) + { + //std::cout << "id: " << s << std::endl; + return RezParser::make_IDENTIFIER(lower, loc); + } + else + { + //std::cout << "key: " << s << std::endl; + return (*p->second)(loc); + } + } + else if(tok == T_INTLIT) + { + if(tok.get_value() == "0") + { + auto tok2 = peekWave(); + while(tok2 != T_EOI && tok2 != T_EOF && IS_CATEGORY(tok2, WhiteSpaceTokenType)) + nextWave(), tok2 = peekWave(); - //std::cout << "!" << std::hex << (token_id)tok2 << std::dec << "|" << tok2.get_value() << "!\n"; - static boost::regex binlit("[bB][01]+"); - if(tok2 == T_IDENTIFIER && boost::regex_match(tok2.get_value().c_str(), binlit)) - tok = nextWave(); - } - return RezParser::make_INTLIT(readInt(tok.get_value().c_str()), loc); - } - else - { -#define NOVAL_TOK(name) \ + //std::cout << "!" << std::hex << (token_id)tok2 << std::dec << "|" << tok2.get_value() << "!\n"; + static boost::regex binlit("[bB][01]+"); + if(tok2 == T_IDENTIFIER && boost::regex_match(tok2.get_value().c_str(), binlit)) + tok = nextWave(); + } + return RezParser::make_INTLIT(readInt(tok.get_value().c_str()), loc); + } + else + { +#define NOVAL_TOK(name) \ case T_ ## name: /*std::cout << #name << std::endl;*/ return RezParser::make_ ## name(loc) - switch(token_id(tok)) - { - case T_INTLIT: return RezParser::make_INTLIT(readInt(tok.get_value().c_str()), loc); + switch(token_id(tok)) + { + case T_INTLIT: return RezParser::make_INTLIT(readInt(tok.get_value().c_str()), loc); - case T_CHARLIT: return RezParser::make_CHARLIT(readCharLit(tok.get_value().c_str()), loc); - case T_STRINGLIT: return RezParser::make_STRINGLIT(readStringLit(tok.get_value().c_str()), loc); + case T_CHARLIT: return RezParser::make_CHARLIT(readCharLit(tok.get_value().c_str()), loc); + case T_STRINGLIT: return RezParser::make_STRINGLIT(readStringLit(tok.get_value().c_str()), loc); - NOVAL_TOK(LEFTBRACE); - NOVAL_TOK(RIGHTBRACE); - NOVAL_TOK(LEFTBRACKET); - NOVAL_TOK(RIGHTBRACKET); - NOVAL_TOK(LEFTPAREN); - NOVAL_TOK(RIGHTPAREN); - NOVAL_TOK(SEMICOLON); - NOVAL_TOK(COMMA); - NOVAL_TOK(PLUS); - NOVAL_TOK(MINUS); - NOVAL_TOK(DIVIDE); - NOVAL_TOK(STAR); - NOVAL_TOK(ASSIGN); - NOVAL_TOK(COLON); - NOVAL_TOK(SHIFTLEFT); - NOVAL_TOK(SHIFTRIGHT); - NOVAL_TOK(EQUAL); - NOVAL_TOK(NOTEQUAL); - NOVAL_TOK(AND); - NOVAL_TOK(OR); - NOVAL_TOK(XOR); - NOVAL_TOK(COMPL); + NOVAL_TOK(LEFTBRACE); + NOVAL_TOK(RIGHTBRACE); + NOVAL_TOK(LEFTBRACKET); + NOVAL_TOK(RIGHTBRACKET); + NOVAL_TOK(LEFTPAREN); + NOVAL_TOK(RIGHTPAREN); + NOVAL_TOK(SEMICOLON); + NOVAL_TOK(COMMA); + NOVAL_TOK(PLUS); + NOVAL_TOK(MINUS); + NOVAL_TOK(DIVIDE); + NOVAL_TOK(STAR); + NOVAL_TOK(ASSIGN); + NOVAL_TOK(COLON); + NOVAL_TOK(SHIFTLEFT); + NOVAL_TOK(SHIFTRIGHT); + NOVAL_TOK(EQUAL); + NOVAL_TOK(NOTEQUAL); + NOVAL_TOK(AND); + NOVAL_TOK(OR); + NOVAL_TOK(XOR); + NOVAL_TOK(COMPL); - default: + default: - return RezParser::make_BADTOKEN(tok.get_value().c_str(), loc); - } + return RezParser::make_BADTOKEN(tok.get_value().c_str(), loc); + } - } - } - } - return RezParser::symbol_type(RezParser::token_type(0), yy::location()); + } + } + } + return RezParser::symbol_type(RezParser::token_type(0), yy::location()); } diff --git a/Rez/RezLexerWaveToken.h b/Rez/RezLexerWaveToken.h index 3d11903b0b..b990bad4c3 100644 --- a/Rez/RezLexerWaveToken.h +++ b/Rez/RezLexerWaveToken.h @@ -8,8 +8,8 @@ class RezLexer::WaveToken : public boost::wave::cpplexer::lex_token<> { public: - WaveToken() = default; - WaveToken(const boost::wave::cpplexer::lex_token<> & o) : boost::wave::cpplexer::lex_token<>(o) {} + WaveToken() = default; + WaveToken(const boost::wave::cpplexer::lex_token<> & o) : boost::wave::cpplexer::lex_token<>(o) {} }; #endif // REZLEXERWAVETOKEN_H diff --git a/Rez/RezWorld.cc b/Rez/RezWorld.cc index e44b1f8d75..83bfcb16f1 100644 --- a/Rez/RezWorld.cc +++ b/Rez/RezWorld.cc @@ -7,52 +7,52 @@ #include "Diagnostic.h" RezWorld::RezWorld() - : verboseFlag(false), hadErrors(false) + : verboseFlag(false), hadErrors(false) { } void RezWorld::addTypeDefinition(TypeSpec spec, TypeDefinitionPtr type) { - if(!type) - return; - types[spec] = type; + if(!type) + return; + types[spec] = type; } TypeDefinitionPtr RezWorld::getTypeDefinition(ResType type, int id, yy::location loc) { - auto p = types.find(TypeSpec(type, id)); - if(p != types.end()) - return p->second; - p = types.find(TypeSpec(type)); - if(p != types.end()) - return p->second; - problem(Diagnostic(Diagnostic::Severity::error, "Can't find type definition for '" + std::string(type) + "'", loc)); + auto p = types.find(TypeSpec(type, id)); + if(p != types.end()) + return p->second; + p = types.find(TypeSpec(type)); + if(p != types.end()) + return p->second; + problem(Diagnostic(Diagnostic::Severity::error, "Can't find type definition for '" + std::string(type) + "'", loc)); - return nullptr; + return nullptr; } void RezWorld::addResource(ResSpec spec, CompoundExprPtr body, yy::location loc) { - if(verboseFlag) - std::cout << "RESOURCE " << spec.type() << "(" << spec.id() << ", " << "\"" << spec.name() << "\"" << spec.attr() << ")" << std::endl; - TypeDefinitionPtr def = getTypeDefinition(spec.type(), spec.id(), loc); - if(!def) - return; - ResourceCompiler compiler(*this, def, body, verboseFlag); - compiler.compile(); + if(verboseFlag) + std::cout << "RESOURCE " << spec.type() << "(" << spec.id() << ", " << "\"" << spec.name() << "\"" << spec.attr() << ")" << std::endl; + TypeDefinitionPtr def = getTypeDefinition(spec.type(), spec.id(), loc); + if(!def) + return; + ResourceCompiler compiler(*this, def, body, verboseFlag); + compiler.compile(); - resources.addResource(Resource(spec.type(), spec.id(), compiler.resourceData(), spec.name(), spec.attr())); + resources.addResource(Resource(spec.type(), spec.id(), compiler.resourceData(), spec.name(), spec.attr())); } void RezWorld::addData(ResSpec spec, const std::string &data, yy::location loc) { - if(verboseFlag) - std::cout << "DATA " << spec.type() << "(" << spec.id() << ", " << "\"" << spec.name() << "\"" << spec.attr() << ")" << std::endl; - resources.addResource(Resource(spec.type(), spec.id(), data, spec.name(), spec.attr())); + if(verboseFlag) + std::cout << "DATA " << spec.type() << "(" << spec.id() << ", " << "\"" << spec.name() << "\"" << spec.attr() << ")" << std::endl; + resources.addResource(Resource(spec.type(), spec.id(), data, spec.name(), spec.attr())); } void RezWorld::problem(Diagnostic d) { - hadErrors = true; - std::cerr << d << std::endl; + hadErrors = true; + std::cerr << d << std::endl; } diff --git a/Rez/RezWorld.h b/Rez/RezWorld.h index 48b9cf3c86..494f81bc60 100644 --- a/Rez/RezWorld.h +++ b/Rez/RezWorld.h @@ -13,30 +13,30 @@ class Diagnostic; class RezWorld { - friend class RezParser; + friend class RezParser; - std::map types; - std::stack fieldLists; - std::stack functionCalls; - std::stack switches; + std::map types; + std::stack fieldLists; + std::stack functionCalls; + std::stack switches; - Resources resources; + Resources resources; public: - RezWorld(); - void addTypeDefinition(TypeSpec spec, TypeDefinitionPtr type); + RezWorld(); + void addTypeDefinition(TypeSpec spec, TypeDefinitionPtr type); - TypeDefinitionPtr getTypeDefinition(ResType type, int id, yy::location loc); + TypeDefinitionPtr getTypeDefinition(ResType type, int id, yy::location loc); - void addResource(ResSpec spec, CompoundExprPtr body, yy::location loc); - void addData(ResSpec spec, const std::string& data, yy::location loc); + void addResource(ResSpec spec, CompoundExprPtr body, yy::location loc); + void addData(ResSpec spec, const std::string& data, yy::location loc); - Resources& getResources() { return resources; } + Resources& getResources() { return resources; } - bool verboseFlag; - bool hadErrors; + bool verboseFlag; + bool hadErrors; - void problem(Diagnostic d); + void problem(Diagnostic d); }; diff --git a/Rez/Test/UnitTests.cc b/Rez/Test/UnitTests.cc index fee01c864c..689c8728a4 100644 --- a/Rez/Test/UnitTests.cc +++ b/Rez/Test/UnitTests.cc @@ -12,89 +12,89 @@ BOOST_AUTO_TEST_SUITE(LexSuite) -#define CHECKSYM(TOKEN, TYPE, VAL) \ - do { \ - RezSymbol t = lex.nextToken(); \ - BOOST_CHECK_EQUAL(t.token(), TOKEN); \ - if(t.token() == TOKEN) \ - BOOST_CHECK_EQUAL(t.value.as(), VAL); \ - } while(0) -#define CHECKSYM_(TOKEN) \ - do { \ - RezSymbol t = lex.nextToken(); \ - BOOST_CHECK_EQUAL(t.token(), TOKEN); \ - } while(0) +#define CHECKSYM(TOKEN, TYPE, VAL) \ + do { \ + RezSymbol t = lex.nextToken(); \ + BOOST_CHECK_EQUAL(t.token(), TOKEN); \ + if(t.token() == TOKEN) \ + BOOST_CHECK_EQUAL(t.value.as(), VAL); \ + } while(0) +#define CHECKSYM_(TOKEN) \ + do { \ + RezSymbol t = lex.nextToken(); \ + BOOST_CHECK_EQUAL(t.token(), TOKEN); \ + } while(0) BOOST_AUTO_TEST_CASE(moveBisonSymbol) { - // Bison 3.2 contains a bug in the move constructor for its symbol type. - // It will crash when used. - // Unfortunately, there is no copy constructor any more, so it's hard to avoid. - std::string filename = "foo"; - yy::location loc(&filename, 0,0); - auto sym = RezParser::make_INTLIT(42, loc); - auto sym2 = std::move(sym); + // Bison 3.2 contains a bug in the move constructor for its symbol type. + // It will crash when used. + // Unfortunately, there is no copy constructor any more, so it's hard to avoid. + std::string filename = "foo"; + yy::location loc(&filename, 0,0); + auto sym = RezParser::make_INTLIT(42, loc); + auto sym2 = std::move(sym); } BOOST_AUTO_TEST_CASE(moveRezSymbol) { - // This tests my workaround for the bison bug; - // RezSymbol derives from bison's symbol type and reimplements all move constructors - std::string filename = "foo"; - yy::location loc(&filename, 0,0); - RezSymbol sym = RezParser::make_INTLIT(42, loc); - auto sym2 = std::move(sym); + // This tests my workaround for the bison bug; + // RezSymbol derives from bison's symbol type and reimplements all move constructors + std::string filename = "foo"; + yy::location loc(&filename, 0,0); + RezSymbol sym = RezParser::make_INTLIT(42, loc); + auto sym2 = std::move(sym); } BOOST_AUTO_TEST_CASE(basicInt) { - RezWorld world; - RezLexer lex(world, "test", "123 0x456 0xaBcd9\n"); + RezWorld world; + RezLexer lex(world, "test", "123 0x456 0xaBcd9\n"); - CHECKSYM(RezParser::token::INTLIT, int, 123); - CHECKSYM(RezParser::token::INTLIT, int, 0x456); - CHECKSYM(RezParser::token::INTLIT, int, 0xabcd9); - CHECKSYM_(0); + CHECKSYM(RezParser::token::INTLIT, int, 123); + CHECKSYM(RezParser::token::INTLIT, int, 0x456); + CHECKSYM(RezParser::token::INTLIT, int, 0xabcd9); + CHECKSYM_(0); } BOOST_AUTO_TEST_CASE(alternateHex) { - RezWorld world; - RezLexer lex(world, "test", "$456 $aBcd9\n"); + RezWorld world; + RezLexer lex(world, "test", "$456 $aBcd9\n"); - CHECKSYM(RezParser::token::INTLIT, int, 0x456); - CHECKSYM(RezParser::token::INTLIT, int, 0xabcd9); - CHECKSYM_(0); + CHECKSYM(RezParser::token::INTLIT, int, 0x456); + CHECKSYM(RezParser::token::INTLIT, int, 0xabcd9); + CHECKSYM_(0); } BOOST_AUTO_TEST_CASE(noNewlineAtEOF) { - RezWorld world; - RezLexer lex(world, "test", "123 456"); - CHECKSYM(RezParser::token::INTLIT, int, 123); - CHECKSYM(RezParser::token::INTLIT, int, 456); - CHECKSYM_(0); + RezWorld world; + RezLexer lex(world, "test", "123 456"); + CHECKSYM(RezParser::token::INTLIT, int, 123); + CHECKSYM(RezParser::token::INTLIT, int, 456); + CHECKSYM_(0); } BOOST_AUTO_TEST_CASE(strings) { - RezWorld world; - RezLexer lex(world, "test", R"rez( - "Hello, world." - "Foo \n" - "\r Quux" - "\001\002\003" - "\0x42\0x43" - "Blah \$5F" - )rez" "\n"); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "Hello, world."); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "Foo \n"); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "\r Quux"); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "\001\002\003"); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "\x42\x43"); - CHECKSYM(RezParser::token::STRINGLIT, std::string, "Blah \x5F"); - CHECKSYM_(0); + RezWorld world; + RezLexer lex(world, "test", R"rez( + "Hello, world." + "Foo \n" + "\r Quux" + "\001\002\003" + "\0x42\0x43" + "Blah \$5F" + )rez" "\n"); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "Hello, world."); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "Foo \n"); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "\r Quux"); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "\001\002\003"); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "\x42\x43"); + CHECKSYM(RezParser::token::STRINGLIT, std::string, "Blah \x5F"); + CHECKSYM_(0); } BOOST_AUTO_TEST_SUITE_END() @@ -103,59 +103,59 @@ BOOST_AUTO_TEST_SUITE(BinarySuite) BOOST_AUTO_TEST_CASE(bytes) { - BinaryOutput out; - out.write(8, 'a'); - out.write(8, 'b'); - out.write(8, 'c'); - BOOST_CHECK_EQUAL(out.resourceData(), "abc"); + BinaryOutput out; + out.write(8, 'a'); + out.write(8, 'b'); + out.write(8, 'c'); + BOOST_CHECK_EQUAL(out.resourceData(), "abc"); } BOOST_AUTO_TEST_CASE(multibyte) { - BinaryOutput out; - out.write(32, 'abcd'); - BOOST_CHECK_EQUAL(out.resourceData(), "abcd"); + BinaryOutput out; + out.write(32, 'abcd'); + BOOST_CHECK_EQUAL(out.resourceData(), "abcd"); } BOOST_AUTO_TEST_CASE(subbyte) { - BinaryOutput out; - out.write(4, 6); - out.write(4, 1); + BinaryOutput out; + out.write(4, 6); + out.write(4, 1); - out.write(2, 1); - out.write(2, 2); - out.write(4, 2); + out.write(2, 1); + out.write(2, 2); + out.write(4, 2); - out.write(3, 3); - out.write(2, 0); - out.write(3, 3); - BOOST_CHECK_EQUAL(out.resourceData(), "abc"); + out.write(3, 3); + out.write(2, 0); + out.write(3, 3); + BOOST_CHECK_EQUAL(out.resourceData(), "abc"); } BOOST_AUTO_TEST_CASE(peek) { - BinaryOutput out; - for(char c : "Hello, world.") - if(c != 0) - out.write(8, c); + BinaryOutput out; + for(char c : "Hello, world.") + if(c != 0) + out.write(8, c); - BOOST_CHECK_EQUAL(out.resourceData(), "Hello, world."); + BOOST_CHECK_EQUAL(out.resourceData(), "Hello, world."); - BOOST_CHECK_EQUAL(out.peek(0,8), 'H'); - BOOST_CHECK_EQUAL(out.peek(32,8), 'o'); + BOOST_CHECK_EQUAL(out.peek(0,8), 'H'); + BOOST_CHECK_EQUAL(out.peek(32,8), 'o'); - BOOST_CHECK_EQUAL(out.peek(0,32), 'Hell'); - BOOST_CHECK_EQUAL(out.peek(40,32), ', wo'); + BOOST_CHECK_EQUAL(out.peek(0,32), 'Hell'); + BOOST_CHECK_EQUAL(out.peek(40,32), ', wo'); - BOOST_CHECK_EQUAL(out.peek(1,8), 'H' * 2); - BOOST_CHECK_EQUAL(out.peek(2,8), 0x21); + BOOST_CHECK_EQUAL(out.peek(1,8), 'H' * 2); + BOOST_CHECK_EQUAL(out.peek(2,8), 0x21); - BOOST_CHECK_EQUAL(out.peek(2,30), 'Hell' & 0x3FFFFFFF); - BOOST_CHECK_EQUAL(out.peek(2,32), ('Hell' & 0x3FFFFFFF) << 2 | ('o' >> 6) ); + BOOST_CHECK_EQUAL(out.peek(2,30), 'Hell' & 0x3FFFFFFF); + BOOST_CHECK_EQUAL(out.peek(2,32), ('Hell' & 0x3FFFFFFF) << 2 | ('o' >> 6) ); - BOOST_CHECK_EQUAL(out.peek(4,3), 4); + BOOST_CHECK_EQUAL(out.peek(4,3), 4); } BOOST_AUTO_TEST_SUITE_END() diff --git a/Samples/Dialog/CMakeLists.txt b/Samples/Dialog/CMakeLists.txt index 8718e9381a..52e33860d9 100644 --- a/Samples/Dialog/CMakeLists.txt +++ b/Samples/Dialog/CMakeLists.txt @@ -1,19 +1,19 @@ -# Copyright 2015 Wolfgang Thaller. +# Copyright 2015 Wolfgang Thaller. # -# This file is part of Retro68. +# This file is part of Retro68. # -# Retro68 is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Retro68 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Retro68 is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Retro68 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with Retro68. If not, see . +# You should have received a copy of the GNU General Public License +# along with Retro68. If not, see . # To use this example as a standalone project using CMake: # mkdir build @@ -22,16 +22,16 @@ # make add_application(Dialog - dialog.c - dialog.r - ) + dialog.c + dialog.r + ) # Enable -ffunction-sections and -gc-sections to make the app as small as possible # On 68K, also enable --mac-single to build it as a single-segment app (so that this code path doesn't rot) set_target_properties(Dialog PROPERTIES COMPILE_OPTIONS -ffunction-sections) if(CMAKE_SYSTEM_NAME MATCHES Retro68) - set_target_properties(Dialog PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-single") + set_target_properties(Dialog PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-single") else() - set_target_properties(Dialog PROPERTIES LINK_FLAGS "-Wl,-gc-sections") + set_target_properties(Dialog PROPERTIES LINK_FLAGS "-Wl,-gc-sections") endif() diff --git a/Samples/Dialog/dialog.c b/Samples/Dialog/dialog.c index af8440fb78..9d586cd36b 100644 --- a/Samples/Dialog/dialog.c +++ b/Samples/Dialog/dialog.c @@ -22,10 +22,10 @@ #include #ifndef TARGET_API_MAC_CARBON - /* NOTE: this is checking whether the Dialogs.h we use *knows* about Carbon, - not whether we are actually compiling for Cabon. - If Dialogs.h is older, we add a define to be able to use the new name - for NewUserItemUPP, which used to be NewUserItemProc. */ + /* NOTE: this is checking whether the Dialogs.h we use *knows* about Carbon, + not whether we are actually compiling for Cabon. + If Dialogs.h is older, we add a define to be able to use the new name + for NewUserItemUPP, which used to be NewUserItemProc. */ #define NewUserItemUPP NewUserItemProc #endif @@ -33,7 +33,7 @@ pascal void ButtonFrameProc(DialogRef dlg, DialogItemIndex itemNo) { DialogItemType type; - Handle itemH; + Handle itemH; Rect box; GetDialogItem(dlg, 1, &type, &itemH, &box); @@ -49,8 +49,8 @@ int main() InitFonts(); InitWindows(); InitMenus(); - TEInit(); - InitDialogs(NULL); + TEInit(); + InitDialogs(NULL); #endif DialogPtr dlg = GetNewDialog(128,0,(WindowPtr)-1); InitCursor(); @@ -61,7 +61,7 @@ int main() Rect box; GetDialogItem(dlg, 2, &type, &itemH, &box); - SetDialogItem(dlg, 2, type, (Handle) NewUserItemUPP(&ButtonFrameProc), &box); + SetDialogItem(dlg, 2, type, (Handle) NewUserItemUPP(&ButtonFrameProc), &box); ControlHandle cb, radio1, radio2; GetDialogItem(dlg, 5, &type, &itemH, &box); @@ -89,5 +89,5 @@ int main() } while(item != 1); FlushEvents(everyEvent, -1); - return 0; + return 0; } diff --git a/Samples/HelloWorld/CMakeLists.txt b/Samples/HelloWorld/CMakeLists.txt index 65ad0a59a4..d31bf1e0bc 100644 --- a/Samples/HelloWorld/CMakeLists.txt +++ b/Samples/HelloWorld/CMakeLists.txt @@ -5,17 +5,17 @@ # make add_application(HelloWorld - hello.c - CONSOLE + hello.c + CONSOLE ) # make the result as small as possible - # by removing unused code (gc-sections) - # and by removing macsbug function names on 68K - # (don't do this when debugging...) + # by removing unused code (gc-sections) + # and by removing macsbug function names on 68K + # (don't do this when debugging...) set_target_properties(HelloWorld PROPERTIES COMPILE_OPTIONS -ffunction-sections) if(CMAKE_SYSTEM_NAME MATCHES Retro68) - set_target_properties(HelloWorld PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-strip-macsbug") + set_target_properties(HelloWorld PROPERTIES LINK_FLAGS "-Wl,-gc-sections -Wl,--mac-strip-macsbug") else() - set_target_properties(HelloWorld PROPERTIES LINK_FLAGS "-Wl,-gc-sections") + set_target_properties(HelloWorld PROPERTIES LINK_FLAGS "-Wl,-gc-sections") endif() diff --git a/Samples/HelloWorld/hello.c b/Samples/HelloWorld/hello.c index 1dbd3ac56d..8e3eef7e71 100644 --- a/Samples/HelloWorld/hello.c +++ b/Samples/HelloWorld/hello.c @@ -1,28 +1,28 @@ /* - Copyright 2014 Wolfgang Thaller. + Copyright 2014 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include int main(int argc, char** argv) { - printf("Hello, world.\n"); - printf("\n(Press Return)\n"); - getchar(); - return 0; + printf("Hello, world.\n"); + printf("\n(Press Return)\n"); + getchar(); + return 0; } diff --git a/Samples/Launcher/CMakeLists.txt b/Samples/Launcher/CMakeLists.txt index c1c41be524..3b86f2c1d6 100644 --- a/Samples/Launcher/CMakeLists.txt +++ b/Samples/Launcher/CMakeLists.txt @@ -2,4 +2,4 @@ set(CMAKE_C_FLAGS "-Wno-multichar") set(CMAKE_EXE_LINKER_FLAGS "-Wl,-gc-sections") add_application(Launcher - FILES Launcher.c CONSOLE) + FILES Launcher.c CONSOLE) diff --git a/Samples/Launcher/Launcher.c b/Samples/Launcher/Launcher.c index 3c9d18b044..86c127a8a4 100644 --- a/Samples/Launcher/Launcher.c +++ b/Samples/Launcher/Launcher.c @@ -1,20 +1,20 @@ /* - Copyright 2014 Wolfgang Thaller. + Copyright 2014 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include @@ -28,124 +28,124 @@ void Explain() { - printf("*********************************************************\n"); - printf("This program is intended to make developing software\n"); - printf("using Retro68K and Mini vMac a little more convenient.\n"); - printf("\n"); - printf("If you insert a disk that contains a single application\n"); - printf("(= drag a disk image created by Retro68K to this window),\n"); - printf("the application will be automatically launched and the\n"); - printf("disk image unmounted again afterwards.\n"); - printf("\n"); - printf("It just saves a few repetitive clicks.\n"); - printf("*********************************************************\n"); + printf("*********************************************************\n"); + printf("This program is intended to make developing software\n"); + printf("using Retro68K and Mini vMac a little more convenient.\n"); + printf("\n"); + printf("If you insert a disk that contains a single application\n"); + printf("(= drag a disk image created by Retro68K to this window),\n"); + printf("the application will be automatically launched and the\n"); + printf("disk image unmounted again afterwards.\n"); + printf("\n"); + printf("It just saves a few repetitive clicks.\n"); + printf("*********************************************************\n"); } void EjectOldDisk() { - Handle h = GetResource('LNCH', 128); - if(h) - { - short refNum = **(short**)h; - printf("Ejecting disk (refNum = %d)\n", (int)refNum); + Handle h = GetResource('LNCH', 128); + if(h) + { + short refNum = **(short**)h; + printf("Ejecting disk (refNum = %d)\n", (int)refNum); - Eject(NULL, refNum); - UnmountVol(NULL, refNum); - RemoveResource(h); - } + Eject(NULL, refNum); + UnmountVol(NULL, refNum); + RemoveResource(h); + } } int main() { - Explain(); - EjectOldDisk(); - printf("Insert a disk or hit any key to abort.\n"); + Explain(); + EjectOldDisk(); + printf("Insert a disk or hit any key to abort.\n"); - FlushEvents(everyEvent, 0); + FlushEvents(everyEvent, 0); - for(;;) - { - EventRecord e; - GetNextEvent(everyEvent, &e); + for(;;) + { + EventRecord e; + GetNextEvent(everyEvent, &e); - switch(e.what) - { - case keyDown: - return 0; - break; + switch(e.what) + { + case keyDown: + return 0; + break; - case diskEvt: - { - short refNum = LoWord(e.message); - short err = HiWord(e.message); - printf("Disk Inserted (refNum = %d, error = %d)\n", refNum, err); - if(err == 0) - { - { - Handle h = NewHandle(2); - **(short**)h = refNum; - AddResource(h, 'LNCH', 128, ""); - } - SetVol(NULL, refNum); + case diskEvt: + { + short refNum = LoWord(e.message); + short err = HiWord(e.message); + printf("Disk Inserted (refNum = %d, error = %d)\n", refNum, err); + if(err == 0) + { + { + Handle h = NewHandle(2); + **(short**)h = refNum; + AddResource(h, 'LNCH', 128, ""); + } + SetVol(NULL, refNum); - CInfoPBRec cpb; - unsigned char name[257]; - int i, nApps = 0; - unsigned char bestName[257]; - for(i = 1;; i++) - { - memset(&cpb, 0, sizeof(cpb)); - cpb.dirInfo.ioVRefNum = refNum; - cpb.dirInfo.ioFDirIndex = i; - cpb.dirInfo.ioNamePtr = name; - err = PBGetCatInfoSync(&cpb); + CInfoPBRec cpb; + unsigned char name[257]; + int i, nApps = 0; + unsigned char bestName[257]; + for(i = 1;; i++) + { + memset(&cpb, 0, sizeof(cpb)); + cpb.dirInfo.ioVRefNum = refNum; + cpb.dirInfo.ioFDirIndex = i; + cpb.dirInfo.ioNamePtr = name; + err = PBGetCatInfoSync(&cpb); - if(err != noErr) - break; + if(err != noErr) + break; - name[name[0]+1] = 0; - if(cpb.hFileInfo.ioFlFndrInfo.fdType == 'APPL') - { - printf("Application: %s\n", &name[1]); - memcpy(bestName, name, sizeof(bestName)); - ++nApps; - } - } + name[name[0]+1] = 0; + if(cpb.hFileInfo.ioFlFndrInfo.fdType == 'APPL') + { + printf("Application: %s\n", &name[1]); + memcpy(bestName, name, sizeof(bestName)); + ++nApps; + } + } - if(nApps == 0) - { - printf("No applications found on disk.\n"); - EjectOldDisk(); - } - else if(nApps > 1) - { - printf("Multiple applications found on disk.\n"); - EjectOldDisk(); - } - else - { - LaunchParamBlockRec lpb; - memset(&lpb, 0, sizeof(lpb)); + if(nApps == 0) + { + printf("No applications found on disk.\n"); + EjectOldDisk(); + } + else if(nApps > 1) + { + printf("Multiple applications found on disk.\n"); + EjectOldDisk(); + } + else + { + LaunchParamBlockRec lpb; + memset(&lpb, 0, sizeof(lpb)); - lpb.reserved1 = (unsigned long) bestName; - lpb.reserved2 = 0; - lpb.launchBlockID = extendedBlock; - lpb.launchEPBLength = 6; - lpb.launchFileFlags = 0; - lpb.launchControlFlags = 0xC000; + lpb.reserved1 = (unsigned long) bestName; + lpb.reserved2 = 0; + lpb.launchBlockID = extendedBlock; + lpb.launchEPBLength = 6; + lpb.launchFileFlags = 0; + lpb.launchControlFlags = 0xC000; - printf("Launching...\n"); - err = LaunchApplication(&lpb); - printf("Still here after launch (err = %d). Press Enter to exit.\n", (int)err); - getchar(); - return 0; - } - } - else - Eject(NULL, refNum); - } - break; - } - } - return 0; + printf("Launching...\n"); + err = LaunchApplication(&lpb); + printf("Still here after launch (err = %d). Press Enter to exit.\n", (int)err); + getchar(); + return 0; + } + } + else + Eject(NULL, refNum); + } + break; + } + } + return 0; } diff --git a/Samples/MPWTool/main.c b/Samples/MPWTool/main.c index d16007f329..ab92416742 100644 --- a/Samples/MPWTool/main.c +++ b/Samples/MPWTool/main.c @@ -1,20 +1,20 @@ /* - Copyright 2018 Wolfgang Thaller. + Copyright 2018 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ /* @@ -173,7 +173,7 @@ void *__dso_handle = &__dso_handle; void _start() { - RETRO68_RELOCATE(); + RETRO68_RELOCATE(); if(setjmp(exit_buf)) ; diff --git a/Samples/Raytracer/CMakeLists.txt b/Samples/Raytracer/CMakeLists.txt index 9c3002e7fd..e3671cd8b1 100644 --- a/Samples/Raytracer/CMakeLists.txt +++ b/Samples/Raytracer/CMakeLists.txt @@ -1,19 +1,19 @@ -# Copyright 2014 Wolfgang Thaller. +# Copyright 2014 Wolfgang Thaller. # -# This file is part of Retro68. +# This file is part of Retro68. # -# Retro68 is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Retro68 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Retro68 is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Retro68 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with Retro68. If not, see . +# You should have received a copy of the GNU General Public License +# along with Retro68. If not, see . # To use this example as a standalone project using CMake: # mkdir build @@ -22,27 +22,27 @@ # make if(APPLE) - add_executable(Raytracer MACOSX_BUNDLE - raytracer.c - ) - add_executable(Raytracer2 MACOSX_BUNDLE - raytracer2.cc - fixed.h - fixed.cc - ) + add_executable(Raytracer MACOSX_BUNDLE + raytracer.c + ) + add_executable(Raytracer2 MACOSX_BUNDLE + raytracer2.cc + fixed.h + fixed.cc + ) - target_link_libraries(Raytracer "-framework Carbon") - target_link_libraries(Raytracer2 "-framework Carbon") + target_link_libraries(Raytracer "-framework Carbon") + target_link_libraries(Raytracer2 "-framework Carbon") else() - add_application(Raytracer - raytracer.c - ) + add_application(Raytracer + raytracer.c + ) target_link_libraries(Raytracer "-lm") - add_application(Raytracer2 - raytracer2.cc - fixed.h - fixed.cc + add_application(Raytracer2 + raytracer2.cc + fixed.h + fixed.cc ) add_application(FixedBenchmark CONSOLE diff --git a/Samples/Raytracer/fixed.cc b/Samples/Raytracer/fixed.cc index 0f69ea3366..66cd282a7a 100644 --- a/Samples/Raytracer/fixed.cc +++ b/Samples/Raytracer/fixed.cc @@ -23,26 +23,26 @@ long fixed::nMul = 0, fixed::nIMul = 0, fixed::nDiv = 0, fixed::nSqrt = 0; fixed sqrt(fixed f) { - COUNT_OP(fixed::nSqrt); + COUNT_OP(fixed::nSqrt); - const int FRACBITS = 16; /* Must be even! */ - const int ITERS = 15 + (FRACBITS >> 1); - - unsigned long root, remHi, remLo, testDiv, count; - root = 0; /* Clear root */ - remHi = 0; /* Clear high part of partial remainder */ - remLo = f.val; /* Get argument into low part of partial remainder */ - count = ITERS; /* Load loop counter */ - - do { - remHi = (remHi << 2) | (remLo >> 30); remLo <<= 2; /* get 2 bits of arg */ - root <<= 1; /* Get ready for the next bit in the root */ - testDiv = (root << 1) + 1; /* Test radical */ - if (remHi >= testDiv) { - remHi -= testDiv; - root += 1; - } - } while (count-- != 0); + const int FRACBITS = 16; /* Must be even! */ + const int ITERS = 15 + (FRACBITS >> 1); + + unsigned long root, remHi, remLo, testDiv, count; + root = 0; /* Clear root */ + remHi = 0; /* Clear high part of partial remainder */ + remLo = f.val; /* Get argument into low part of partial remainder */ + count = ITERS; /* Load loop counter */ + + do { + remHi = (remHi << 2) | (remLo >> 30); remLo <<= 2; /* get 2 bits of arg */ + root <<= 1; /* Get ready for the next bit in the root */ + testDiv = (root << 1) + 1; /* Test radical */ + if (remHi >= testDiv) { + remHi -= testDiv; + root += 1; + } + } while (count-- != 0); - return fixed(root, fixed::raw()); + return fixed(root, fixed::raw()); } diff --git a/Samples/Raytracer/fixed.h b/Samples/Raytracer/fixed.h index 106835a485..5358636714 100644 --- a/Samples/Raytracer/fixed.h +++ b/Samples/Raytracer/fixed.h @@ -24,30 +24,30 @@ inline std::int32_t muls(std::int16_t x, std::int16_t y) { - return (std::int32_t)x*y; + return (std::int32_t)x*y; } inline std::uint32_t mulu(std::uint16_t x, std::uint16_t y) { #if TARGET_CPU_M68K - std::uint32_t res; - __asm("mulu %1, %0" : "=d"(res) : "d"(x), "0"(y)); - return res; + std::uint32_t res; + __asm("mulu %1, %0" : "=d"(res) : "d"(x), "0"(y)); + return res; #else - return (std::uint32_t)x * y; + return (std::uint32_t)x * y; #endif } inline std::int32_t mulsu(std::int16_t x, std::uint16_t y) { #if TARGET_CPU_M68K - std::int32_t res; - __asm("mulu %1, %0" : "=d"(res) : "d"(x), "0"(y)); - if(x < 0) - res -= ((std::uint32_t)y) << 16; - return res; + std::int32_t res; + __asm("mulu %1, %0" : "=d"(res) : "d"(x), "0"(y)); + if(x < 0) + res -= ((std::uint32_t)y) << 16; + return res; #else - return (std::int32_t)x * (std::uint32_t)y; + return (std::int32_t)x * (std::uint32_t)y; #endif } @@ -55,71 +55,71 @@ inline std::int32_t mulsu(std::int16_t x, std::uint16_t y) class fixed { - std::int32_t val; - + std::int32_t val; + public: - class raw {}; - fixed(std::int32_t val, raw r) : val(val) {} - - fixed() : val(0) {} - fixed(int x) : val((long)x << 16) {} - fixed(float f) : val(f * 65536) {} - - //operator int() { return val >> 16; } - - fixed operator+(fixed o) const { return fixed(val + o.val, raw()); } - fixed operator-(fixed o) const { return fixed(val - o.val, raw()); } - fixed operator*(fixed o) const { - COUNT_OP(nMul); - //return fixed((static_cast(val) * o.val) >> 16, raw()); - int16_t a = val >> 16; - int16_t c = o.val >> 16; + class raw {}; + fixed(std::int32_t val, raw r) : val(val) {} + + fixed() : val(0) {} + fixed(int x) : val((long)x << 16) {} + fixed(float f) : val(f * 65536) {} + + //operator int() { return val >> 16; } + + fixed operator+(fixed o) const { return fixed(val + o.val, raw()); } + fixed operator-(fixed o) const { return fixed(val - o.val, raw()); } + fixed operator*(fixed o) const { + COUNT_OP(nMul); + //return fixed((static_cast(val) * o.val) >> 16, raw()); + int16_t a = val >> 16; + int16_t c = o.val >> 16; - uint16_t b = val; - uint16_t d = o.val; + uint16_t b = val; + uint16_t d = o.val; - return fixed(((a*c) << 16) - + mulsu(a,d) + mulsu(c,b) - + (mulu(b,d) >> 16),raw()); - } - fixed operator/(fixed o) const { COUNT_OP(nDiv); return fixed((static_cast(val) << 16) / o.val, raw()); } - - fixed operator-() const { return fixed(-val, raw()); } - - fixed& operator+=(fixed o) { val += o.val; return *this; } - fixed& operator-=(fixed o) { val -= o.val; return *this; } - fixed& operator*=(fixed o) { return (*this = *this * o); } - - bool operator== (fixed o) const { return val == o.val; } - bool operator!= (fixed o) const { return val != o.val; } - bool operator> (fixed o) const { return val > o.val; } - bool operator< (fixed o) const { return val < o.val; } - bool operator>= (fixed o) const { return val >= o.val; } - bool operator<= (fixed o) const { return val <= o.val; } - - friend fixed sqrt(fixed f); - friend fixed floor(fixed f); - friend fixed operator*(fixed f, int x); - friend fixed operator*(int x, fixed f); - friend int floor_to_int(fixed f); - - static long nMul; - static long nIMul; - static long nDiv; - static long nSqrt; + return fixed(((a*c) << 16) + + mulsu(a,d) + mulsu(c,b) + + (mulu(b,d) >> 16),raw()); + } + fixed operator/(fixed o) const { COUNT_OP(nDiv); return fixed((static_cast(val) << 16) / o.val, raw()); } + + fixed operator-() const { return fixed(-val, raw()); } + + fixed& operator+=(fixed o) { val += o.val; return *this; } + fixed& operator-=(fixed o) { val -= o.val; return *this; } + fixed& operator*=(fixed o) { return (*this = *this * o); } + + bool operator== (fixed o) const { return val == o.val; } + bool operator!= (fixed o) const { return val != o.val; } + bool operator> (fixed o) const { return val > o.val; } + bool operator< (fixed o) const { return val < o.val; } + bool operator>= (fixed o) const { return val >= o.val; } + bool operator<= (fixed o) const { return val <= o.val; } + + friend fixed sqrt(fixed f); + friend fixed floor(fixed f); + friend fixed operator*(fixed f, int x); + friend fixed operator*(int x, fixed f); + friend int floor_to_int(fixed f); + + static long nMul; + static long nIMul; + static long nDiv; + static long nSqrt; }; /*fixed operator*(fixed f, int x) { return fixed(f.val * x, fixed::raw()); } fixed operator*(int x, fixed f) { return fixed(f.val * x, fixed::raw()); }*/ inline fixed operator*(fixed f, int c) { - std::int16_t a = f.val >> 16; + std::int16_t a = f.val >> 16; - std::uint16_t b = f.val; + std::uint16_t b = f.val; - COUNT_OP(fixed::nIMul); - return fixed(((a*c) << 16) - + mulsu(c,b),fixed::raw()); + COUNT_OP(fixed::nIMul); + return fixed(((a*c) << 16) + + mulsu(c,b),fixed::raw()); } inline fixed operator*(int x, fixed f) { return f*x; } @@ -132,12 +132,12 @@ fixed sqrt(fixed f); inline fixed floor(fixed f) { - return fixed(f.val & 0xFFFF0000L, fixed::raw()); + return fixed(f.val & 0xFFFF0000L, fixed::raw()); } inline int floor_to_int(fixed f) { - return f.val >> 16; + return f.val >> 16; } #endif // FIXED_H diff --git a/Samples/Raytracer/fixedbenchmark.cc b/Samples/Raytracer/fixedbenchmark.cc index 9e9723c15c..ff442fb8f2 100644 --- a/Samples/Raytracer/fixedbenchmark.cc +++ b/Samples/Raytracer/fixedbenchmark.cc @@ -1,20 +1,20 @@ /* - Copyright 2014 Wolfgang Thaller. + Copyright 2014 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include @@ -31,81 +31,81 @@ using std::sqrt; class timer { - long t; + long t; public: - timer() : t(TickCount()) {} - float elapsed() { return (TickCount() - t) / 60.15f; } + timer() : t(TickCount()) {} + float elapsed() { return (TickCount() - t) / 60.15f; } }; template void runTests(std::string type, std::vector& numbers) { - std::cout << "***********************************\n"; - std::cout << "Running tests on type " << type << ":\n"; - std::cout << "***********************************\n"; + std::cout << "***********************************\n"; + std::cout << "Running tests on type " << type << ":\n"; + std::cout << "***********************************\n"; - int n = numbers.size(); - std::vector outputs(n); + int n = numbers.size(); + std::vector outputs(n); - std::cout << "Testing Multiplication..." << std::flush; - { - timer t; - for(int i = 0; i < n; i++) - { - outputs[i] = numbers[i] * numbers[n - i - 1]; - } - std::cout << 1000 * t.elapsed() / n << "ms\n"; - } + std::cout << "Testing Multiplication..." << std::flush; + { + timer t; + for(int i = 0; i < n; i++) + { + outputs[i] = numbers[i] * numbers[n - i - 1]; + } + std::cout << 1000 * t.elapsed() / n << "ms\n"; + } - std::cout << "Testing Division..." << std::flush; - { - timer t; - for(int i = 0; i < n; i++) - { - outputs[i] = numbers[i] / numbers[n - i - 1]; - } - std::cout << 1000 * t.elapsed() / n << "ms\n"; - } + std::cout << "Testing Division..." << std::flush; + { + timer t; + for(int i = 0; i < n; i++) + { + outputs[i] = numbers[i] / numbers[n - i - 1]; + } + std::cout << 1000 * t.elapsed() / n << "ms\n"; + } - std::cout << "Testing Square Root..." << std::flush; - { - timer t; - for(int i = 0; i < n; i++) - { - outputs[i] = sqrt(numbers[i]); - } - std::cout << 1000 * t.elapsed() / n << "ms\n"; - } - std::cout << std::endl; + std::cout << "Testing Square Root..." << std::flush; + { + timer t; + for(int i = 0; i < n; i++) + { + outputs[i] = sqrt(numbers[i]); + } + std::cout << 1000 * t.elapsed() / n << "ms\n"; + } + std::cout << std::endl; } int main(int argc, char** argv) { - std::cout << "Hello, world.\n"; - - std::cout << "Generating numbers..." << std::flush; - - const size_t n = 1000; - std::vector numbers(n); - std::vector floats(n); - std::vector doubles(n); + std::cout << "Hello, world.\n"; + + std::cout << "Generating numbers..." << std::flush; + + const size_t n = 1000; + std::vector numbers(n); + std::vector floats(n); + std::vector doubles(n); - for(size_t i = 0; i < numbers.size(); i++) - { - numbers[i] = fixed(std::rand(), fixed::raw()); - floats[i] = float(std::rand()) / RAND_MAX; - doubles[i] = double(std::rand()) / RAND_MAX; - } - std::vector outputs(n); - std::cout << "done.\n\n"; - - runTests("float", floats); - runTests("double", doubles); - runTests("fixed", numbers); + for(size_t i = 0; i < numbers.size(); i++) + { + numbers[i] = fixed(std::rand(), fixed::raw()); + floats[i] = float(std::rand()) / RAND_MAX; + doubles[i] = double(std::rand()) / RAND_MAX; + } + std::vector outputs(n); + std::cout << "done.\n\n"; + + runTests("float", floats); + runTests("double", doubles); + runTests("fixed", numbers); - std::cout << "Press Enter to Exit ;-)\n"; - - std::cin.get(); - - return 0; + std::cout << "Press Enter to Exit ;-)\n"; + + std::cin.get(); + + return 0; } diff --git a/Samples/Raytracer/raytracer.c b/Samples/Raytracer/raytracer.c index 9b531f44e0..353ade55ab 100644 --- a/Samples/Raytracer/raytracer.c +++ b/Samples/Raytracer/raytracer.c @@ -1,5 +1,5 @@ /* - Copyright 2014 Wolfgang Thaller. + Copyright 2014 Wolfgang Thaller. This file is part of Retro68. @@ -44,30 +44,30 @@ pascal /* <- pascal calling convention, for no reason in particular except to test the comppiler */ bool hitSphere(float x0, float y0, float z0, float dx, float dy, float dz, float *t) { - const float xc = 0.0f, yc = 0.0f, zc = -6.0f, r = 1.0f; - float x0c = x0 - xc; - float y0c = y0 - yc; - float z0c = z0 - zc; - - /* - (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; - (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; - x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 - - (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 - */ - float a = dx*dx + dy*dy + dz*dz; - float b = 2*(x0c*dx + y0c*dy + z0c*dz); - float c = x0c*x0c + y0c*y0c + z0c*z0c -r*r; - - float D = b*b - 4 * a * c; - - if(D >= 0) - { - *t = (-b - sqrtf(D)) / (2*a); - return *t >= 0; - } - return false; + const float xc = 0.0f, yc = 0.0f, zc = -6.0f, r = 1.0f; + float x0c = x0 - xc; + float y0c = y0 - yc; + float z0c = z0 - zc; + + /* + (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; + (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; + x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 + + (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 + */ + float a = dx*dx + dy*dy + dz*dz; + float b = 2*(x0c*dx + y0c*dy + z0c*dz); + float c = x0c*x0c + y0c*y0c + z0c*z0c -r*r; + + float D = b*b - 4 * a * c; + + if(D >= 0) + { + *t = (-b - sqrtf(D)) / (2*a); + return *t >= 0; + } + return false; } const float lx = -2, ly = 4, lz = 3; float lenl; @@ -75,210 +75,210 @@ float lxn, lyn, lzn; float ray(int n, float x0, float y0, float z0, float dx, float dy, float dz) { - { - const float xc = 0.0f, yc = 0.0f, zc = -6.0f, r = 1.0f; - float x0c = x0 - xc; - float y0c = y0 - yc; - float z0c = z0 - zc; - - /* - (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; - (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; - x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 - - (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 - */ - float a = dx*dx + dy*dy + dz*dz; - float b = 2*(x0c*dx + y0c*dy + z0c*dz); - float c = x0c*x0c + y0c*y0c + z0c*z0c -r*r; - - float D = b*b - 4 * a * c; - - if(D >= 0) - { - float t = (-b - sqrtf(D)) / (2*a); - if(t > 0) - { - float x = x0 + dx * t; - float y = y0 + dy * t; - float z = z0 + dz * t; - - float dx2 = x - xc; - float dy2 = y - yc; - float dz2 = z - zc; - - - float l = dx2 * dx + dy2 * dy + dz2 * dz; - l *= 2; - - float reflected; - if(n) - reflected = ray(n-1, x,y,z, dx - l*dx2, dy - l*dy2, dz - l*dz2); - else - reflected = 0.0f; - - - float lambert = dx2 * lxn + dy2 * lyn + dz2 * lzn; - if(lambert < 0.0f) - lambert = 0.0f; - return 0.2f + 0.4f * lambert + 0.4f * reflected; - } - } - } + { + const float xc = 0.0f, yc = 0.0f, zc = -6.0f, r = 1.0f; + float x0c = x0 - xc; + float y0c = y0 - yc; + float z0c = z0 - zc; + + /* + (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; + (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; + x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 + + (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 + */ + float a = dx*dx + dy*dy + dz*dz; + float b = 2*(x0c*dx + y0c*dy + z0c*dz); + float c = x0c*x0c + y0c*y0c + z0c*z0c -r*r; + + float D = b*b - 4 * a * c; + + if(D >= 0) + { + float t = (-b - sqrtf(D)) / (2*a); + if(t > 0) + { + float x = x0 + dx * t; + float y = y0 + dy * t; + float z = z0 + dz * t; + + float dx2 = x - xc; + float dy2 = y - yc; + float dz2 = z - zc; + + + float l = dx2 * dx + dy2 * dy + dz2 * dz; + l *= 2; + + float reflected; + if(n) + reflected = ray(n-1, x,y,z, dx - l*dx2, dy - l*dy2, dz - l*dz2); + else + reflected = 0.0f; + + + float lambert = dx2 * lxn + dy2 * lyn + dz2 * lzn; + if(lambert < 0.0f) + lambert = 0.0f; + return 0.2f + 0.4f * lambert + 0.4f * reflected; + } + } + } - if(dy < 0) - { - float t = (-1.5f - y0) / dy; - float x = x0 + dx * t; - float z = z0 + dz * t; - - float color; - if( ((int)( floorf(x) ) - + (int)( floorf(z) )) % 2 ) - color = 0.8f; - else - color = 0.1f; - - float ts; - if(hitSphere(x,-1.5f,z, lxn, lyn, lzn, &ts)) - color *= 0.2f; - - float v = color + 0.5f * ray(n-1, x,-1.5f,z,dx,-dy,dz); - if(v > 1.0f) - return 1.0f; - else - return v; - } - - float v = dy * 0.3f; - if(v < 0.0f) - return 0.0f; - else - return v; + if(dy < 0) + { + float t = (-1.5f - y0) / dy; + float x = x0 + dx * t; + float z = z0 + dz * t; + + float color; + if( ((int)( floorf(x) ) + + (int)( floorf(z) )) % 2 ) + color = 0.8f; + else + color = 0.1f; + + float ts; + if(hitSphere(x,-1.5f,z, lxn, lyn, lzn, &ts)) + color *= 0.2f; + + float v = color + 0.5f * ray(n-1, x,-1.5f,z,dx,-dy,dz); + if(v > 1.0f) + return 1.0f; + else + return v; + } + + float v = dy * 0.3f; + if(v < 0.0f) + return 0.0f; + else + return v; } int main() { - WindowPtr win; - + WindowPtr win; + #if !TARGET_API_MAC_CARBON InitGraf(&qd.thePort); InitFonts(); InitWindows(); InitMenus(); - Rect r = qd.screenBits.bounds; + Rect r = qd.screenBits.bounds; #else - BitMap bm; - GetQDGlobalsScreenBits(&bm); - Rect r = bm.bounds; + BitMap bm; + GetQDGlobalsScreenBits(&bm); + Rect r = bm.bounds; #endif SetRect(&r, r.left + 5, r.top + 45, r.right - 5, r.bottom -5); - win = NewWindow(NULL, &r, "\pRaytracer (C Version)", true, 0, (WindowPtr)-1, false, 0); + win = NewWindow(NULL, &r, "\pRaytracer (C Version)", true, 0, (WindowPtr)-1, false, 0); -#if !TARGET_API_MAC_CARBON - SetPort(win); - r = win->portRect; +#if !TARGET_API_MAC_CARBON + SetPort(win); + r = win->portRect; #else - SetPortWindowPort(win); - GetPortBounds(GetWindowPort(win), &r); + SetPortWindowPort(win); + GetPortBounds(GetWindowPort(win), &r); #endif EraseRect(&r); - float accum = 0.0f; - short cx = r.right /2; - short cy = r.bottom / 2; - int x,y; + float accum = 0.0f; + short cx = r.right /2; + short cy = r.bottom / 2; + int x,y; - lenl = 1.0f / sqrtf(lx*lx + ly*ly + lz*lz); - lxn = lx*lenl, lyn = ly*lenl, lzn = lz*lenl; + lenl = 1.0f / sqrtf(lx*lx + ly*ly + lz*lz); + lxn = lx*lenl, lyn = ly*lenl, lzn = lz*lenl; - long startTime = TickCount(); - float *accumV = (float*)NewPtrClear(sizeof(float) * r.right); - for(y = 0; y < r.bottom; y++) - { - for(x = 0; x < r.right; x++) - { - float pixel; - - // cam = (0,0,0) - // ray = t * (x-r.right/2, - (y-r.bottom/2), -1) - // plane: y = -2 - - float dx = x - cx; - float dy = - (y - cy); - float dz = -cx; - float n1 = 1.0f / sqrtf(dx*dx + dy*dy + dz*dz); - - pixel = ray(1,0,0,0,n1*dx,n1*dy,n1*dz); - + long startTime = TickCount(); + float *accumV = (float*)NewPtrClear(sizeof(float) * r.right); + for(y = 0; y < r.bottom; y++) + { + for(x = 0; x < r.right; x++) + { + float pixel; + + // cam = (0,0,0) + // ray = t * (x-r.right/2, - (y-r.bottom/2), -1) + // plane: y = -2 + + float dx = x - cx; + float dy = - (y - cy); + float dz = -cx; + float n1 = 1.0f / sqrtf(dx*dx + dy*dy + dz*dz); + + pixel = ray(1,0,0,0,n1*dx,n1*dy,n1*dz); + #if 0 - accum += pixel; - if(accum >= 0.5f) - accum -= 1.0f; - else - { - MoveTo(x,y); - Line(0,0); - } + accum += pixel; + if(accum >= 0.5f) + accum -= 1.0f; + else + { + MoveTo(x,y); + Line(0,0); + } #elif 0 - accum += pixel; - accum += accumV[x]; - if(accum >= 0.5f) - accum -= 1.0f; - else - { - MoveTo(x,y); - Line(0,0); - } - accumV[x] = accum = accum / 2; -#elif 0 - //if(pixel < Random() / 32767.0) - if(pixel < (float)std::rand() / (32767.0f * 65536.0f)) - { - MoveTo(x,y); - Line(0,0); - } + accum += pixel; + accum += accumV[x]; + if(accum >= 0.5f) + accum -= 1.0f; + else + { + MoveTo(x,y); + Line(0,0); + } + accumV[x] = accum = accum / 2; +#elif 0 + //if(pixel < Random() / 32767.0) + if(pixel < (float)std::rand() / (32767.0f * 65536.0f)) + { + MoveTo(x,y); + Line(0,0); + } #else - float thresh = (float)rand() / (32767.0f * 65536.0f); - thresh = 0.5f + 0.4f * (thresh - 0.5f); - accum += pixel; - accum += accumV[x]; - if(accum >= thresh) - accum -= 1.0f; - else - { - MoveTo(x,y); - Line(0,0); - } - accumV[x] = accum = accum / 2; + float thresh = (float)rand() / (32767.0f * 65536.0f); + thresh = 0.5f + 0.4f * (thresh - 0.5f); + accum += pixel; + accum += accumV[x]; + if(accum >= thresh) + accum -= 1.0f; + else + { + MoveTo(x,y); + Line(0,0); + } + accumV[x] = accum = accum / 2; #endif - } - if(Button()) - return 0; + } + if(Button()) + return 0; #if TARGET_API_MAC_CARBON - QDFlushPortBuffer(GetWindowPort(win),NULL); + QDFlushPortBuffer(GetWindowPort(win),NULL); #endif - } - long endTime = TickCount(); - - Str255 pstr; - NumToString( (long)( (float)r.right * r.bottom / (endTime - startTime) * 60.0f ), - pstr ); - - SetRect(&r, 10, 10, 10 + StringWidth("\ppps = ") + StringWidth(pstr) + 10, 30); - PaintRect(&r); - PenMode(patXor); - FrameRect(&r); - MoveTo(15,25); - TextMode(srcBic); - DrawString("\ppps = "); - DrawString(pstr); + } + long endTime = TickCount(); + + Str255 pstr; + NumToString( (long)( (float)r.right * r.bottom / (endTime - startTime) * 60.0f ), + pstr ); + + SetRect(&r, 10, 10, 10 + StringWidth("\ppps = ") + StringWidth(pstr) + 10, 30); + PaintRect(&r); + PenMode(patXor); + FrameRect(&r); + MoveTo(15,25); + TextMode(srcBic); + DrawString("\ppps = "); + DrawString(pstr); #if TARGET_API_MAC_CARBON - QDFlushPortBuffer(GetWindowPort(win),NULL); + QDFlushPortBuffer(GetWindowPort(win),NULL); #endif - - while(!Button()) - ; - FlushEvents(everyEvent, -1); - return 0; + + while(!Button()) + ; + FlushEvents(everyEvent, -1); + return 0; } diff --git a/Samples/Raytracer/raytracer2.cc b/Samples/Raytracer/raytracer2.cc index 7922ba90bf..2cfe2b15b7 100644 --- a/Samples/Raytracer/raytracer2.cc +++ b/Samples/Raytracer/raytracer2.cc @@ -52,69 +52,69 @@ using std::floor; inline int floor_to_int(float f) { - return static_cast(std::floor(f)); + return static_cast(std::floor(f)); } template class vec3 { public: - T x,y,z; - vec3(T x, T y, T z) : x(x), y(y), z(z) {} - vec3() : x(0), y(0), z(0) {} - - vec3 operator+(const vec3& other) const { return vec3(x + other.x, y + other.y, z + other.z); } - vec3 operator-(const vec3& other) const { return vec3(x - other.x, y - other.y, z - other.z); } - vec3 operator*(T a) const { return vec3(x*a, y*a, z*a); } - - T length() const { return sqrt(x*x + y*y + z*z); } - T operator*(const vec3& other) const { return x*other.x + y*other.y + z*other.z; } - + T x,y,z; + vec3(T x, T y, T z) : x(x), y(y), z(z) {} + vec3() : x(0), y(0), z(0) {} + + vec3 operator+(const vec3& other) const { return vec3(x + other.x, y + other.y, z + other.z); } + vec3 operator-(const vec3& other) const { return vec3(x - other.x, y - other.y, z - other.z); } + vec3 operator*(T a) const { return vec3(x*a, y*a, z*a); } + + T length() const { return sqrt(x*x + y*y + z*z); } + T operator*(const vec3& other) const { return x*other.x + y*other.y + z*other.z; } + #if 1 - vec3 normalize() const { - T l = length(); - //if(l == 0) - // return *this; - //else - return (*this) * (T(1) / l); - } + vec3 normalize() const { + T l = length(); + //if(l == 0) + // return *this; + //else + return (*this) * (T(1) / l); + } #else - vec3 normalize() const { - T l = length(); - if(l == 0) - return *this; - else - return vec3(x/l, y/l, z/l); - } + vec3 normalize() const { + T l = length(); + if(l == 0) + return *this; + else + return vec3(x/l, y/l, z/l); + } #endif }; template bool hitSphere(vec3 p0, vec3 dir, T& t) { - const vec3 center(0.0f, 1.0f, -6.0f); - const T r = 2.0f; - vec3 p0c(p0 - center); - - /* - (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; - (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; - x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 - - (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 - */ - T a = dir*dir; - T b = 2*(p0c*dir); - T c = p0c*p0c - r*r; - - T D = b*b - 4 * a * c; - - if(D >= 0) - { - t = (-b - sqrt(D)) / (2*a); - return t >= 0; - } - return false; + const vec3 center(0.0f, 1.0f, -6.0f); + const T r = 2.0f; + vec3 p0c(p0 - center); + + /* + (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; + (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; + x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 + + (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 + */ + T a = dir*dir; + T b = 2*(p0c*dir); + T c = p0c*p0c - r*r; + + T D = b*b - 4 * a * c; + + if(D >= 0) + { + t = (-b - sqrt(D)) / (2*a); + return t >= 0; + } + return false; } @@ -122,71 +122,71 @@ template T ray(int n, vec3 p0, vec3 dir) { #if 1 - static const vec3 light = vec3(-2,4,3).normalize(); - - if(1){ - const vec3 center(0.0f, 1.0f, -6.0f); - const T r = 2.0f; - vec3 p0c(p0 - center); - - /* - (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; - (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; - x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 - - (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 - */ - T a = dir*dir; - T b = 2*(p0c*dir); - T c = p0c*p0c - r*r; - - T D = b*b - 4 * a * c; - - if(D >= 0) - { - T t = (-b - sqrt(D)) / (2*a); - if(t > 0) - { - vec3 p = p0 + dir * t; - - vec3 dir2 = (p - center) * (T(1)/r); - - T l = dir2*dir; - - T reflected; - if(n) - reflected = ray(n-1, p, dir - dir2*(l*2)); - else - reflected = 0.0f; - - - T lambert = dir2 * light; - - return T(0.2f) + T(0.4f) * std::max(T(0),lambert) + T(0.4f) * reflected; - } - } - } + static const vec3 light = vec3(-2,4,3).normalize(); + + if(1){ + const vec3 center(0.0f, 1.0f, -6.0f); + const T r = 2.0f; + vec3 p0c(p0 - center); + + /* + (x-xc)^2 + (y-yc)^2 + (z-zc)^2 = r^2; + (x0c + dx * t)^2 + (y0c + dy * t)^2 + (z0c + dz * t)^2 = r^2; + x0c^2 + 2*x0c*dx*t + dx^2*t^2 + y0c^2 + 2*y0c*dy*t + dy^2*t^2 + z0c^2 + 2 * z0c*dz*t + dz^2*t^2 = r^2 + + (dx^2 + dy^2 + dz^2)*t^2 + (2*x0c*dx + 2*y0c&dy + 2*z0c*dz) * t + x0c^2+y0c^2+z0c^2-r^2 + */ + T a = dir*dir; + T b = 2*(p0c*dir); + T c = p0c*p0c - r*r; + + T D = b*b - 4 * a * c; + + if(D >= 0) + { + T t = (-b - sqrt(D)) / (2*a); + if(t > 0) + { + vec3 p = p0 + dir * t; + + vec3 dir2 = (p - center) * (T(1)/r); + + T l = dir2*dir; + + T reflected; + if(n) + reflected = ray(n-1, p, dir - dir2*(l*2)); + else + reflected = 0.0f; + + + T lambert = dir2 * light; + + return T(0.2f) + T(0.4f) * std::max(T(0),lambert) + T(0.4f) * reflected; + } + } + } - if(dir.y < 0) - { - T t = (T(-1.5f) - p0.y) / dir.y; - vec3 p = p0 + dir*t; - - T color; - if( (floor_to_int(p.x) - + floor_to_int(p.z)) % 2 ) - color = 0.8f; - else - color = 0.1f; - - T ts; - if(hitSphere(p, light, ts)) - color *= T(0.2f); - - return std::min(T(1), color + T(0.5f) * ray(n-1, p,vec3(dir.x, -dir.y, dir.z))); - } + if(dir.y < 0) + { + T t = (T(-1.5f) - p0.y) / dir.y; + vec3 p = p0 + dir*t; + + T color; + if( (floor_to_int(p.x) + + floor_to_int(p.z)) % 2 ) + color = 0.8f; + else + color = 0.1f; + + T ts; + if(hitSphere(p, light, ts)) + color *= T(0.2f); + + return std::min(T(1), color + T(0.5f) * ray(n-1, p,vec3(dir.x, -dir.y, dir.z))); + } #endif - return std::max(T(0), dir.y * T(0.3f)); + return std::max(T(0), dir.y * T(0.3f)); } typedef fixed numtype; @@ -195,130 +195,130 @@ typedef fixed numtype; template struct rand1 { - static T get() - { - return T(std::rand()) / T(32767.0f * 65536.0f); - } + static T get() + { + return T(std::rand()) / T(32767.0f * 65536.0f); + } }; template<> struct rand1 { - static fixed get() - { - return fixed(std::rand() >> 15, fixed::raw()); - } + static fixed get() + { + return fixed(std::rand() >> 15, fixed::raw()); + } }; int main() { - WindowPtr win; + WindowPtr win; #if !TARGET_API_MAC_CARBON InitGraf(&qd.thePort); InitFonts(); InitWindows(); InitMenus(); - Rect r = qd.screenBits.bounds; + Rect r = qd.screenBits.bounds; #else - BitMap bm; - GetQDGlobalsScreenBits(&bm); - Rect r = bm.bounds; + BitMap bm; + GetQDGlobalsScreenBits(&bm); + Rect r = bm.bounds; #endif SetRect(&r, r.left + 5, r.top + 45, r.right - 5, r.bottom -5); - win = NewWindow(NULL, &r, "\pRaytracer (C++ Version)", true, 0, (WindowPtr)-1, false, 0); + win = NewWindow(NULL, &r, "\pRaytracer (C++ Version)", true, 0, (WindowPtr)-1, false, 0); -#if !TARGET_API_MAC_CARBON - SetPort(win); - r = win->portRect; +#if !TARGET_API_MAC_CARBON + SetPort(win); + r = win->portRect; #else - SetPortWindowPort(win); - GetPortBounds(GetWindowPort(win), &r); + SetPortWindowPort(win); + GetPortBounds(GetWindowPort(win), &r); #endif EraseRect(&r); - numtype accum = 0.0f; - short cx = r.right /2; - short cy = r.bottom / 2; - - long startTime = TickCount(); - std::vector accumV(r.right); - BitMap line; - std::vector bits(((r.right + 31) / 8) & ~0x3); - SetRect(&line.bounds, 0,0,r.right,1); - line.rowBytes = bits.size(); - line.baseAddr = (char*)(&bits[0]); - - numtype preRandoms[29*31]; - for(int i = 0; i < 29*31; i++) - { - numtype thresh = rand1::get(); - thresh = numtype(0.5f) + numtype(0.4f) * (thresh - numtype(0.5f)); - preRandoms[i] = thresh; - } - int randIdx = 0; + numtype accum = 0.0f; + short cx = r.right /2; + short cy = r.bottom / 2; + + long startTime = TickCount(); + std::vector accumV(r.right); + BitMap line; + std::vector bits(((r.right + 31) / 8) & ~0x3); + SetRect(&line.bounds, 0,0,r.right,1); + line.rowBytes = bits.size(); + line.baseAddr = (char*)(&bits[0]); + + numtype preRandoms[29*31]; + for(int i = 0; i < 29*31; i++) + { + numtype thresh = rand1::get(); + thresh = numtype(0.5f) + numtype(0.4f) * (thresh - numtype(0.5f)); + preRandoms[i] = thresh; + } + int randIdx = 0; - for(int y = 0; y < r.bottom; y++) - { - std::fill(bits.begin(),bits.end(), 0); - for(int x = 0; x < r.right; x++) - { - numtype pixel; - - // cam = (0,0,0) - // ray = t * (x-r.right/2, - (y-r.bottom/2), -1) - // plane: y = -2 - pixel = ray(1,vec3(),vec3(numtype(x-cx)/numtype(cx),-numtype(y-cy)/numtype(cx),-1).normalize()); + for(int y = 0; y < r.bottom; y++) + { + std::fill(bits.begin(),bits.end(), 0); + for(int x = 0; x < r.right; x++) + { + numtype pixel; + + // cam = (0,0,0) + // ray = t * (x-r.right/2, - (y-r.bottom/2), -1) + // plane: y = -2 + pixel = ray(1,vec3(),vec3(numtype(x-cx)/numtype(cx),-numtype(y-cy)/numtype(cx),-1).normalize()); - numtype thresh = preRandoms[randIdx++]; - if(randIdx == 29*31) - randIdx = 0; - - accum += pixel; - accum += accumV[x]; - if(accum >= thresh) - accum -= 1; - else - { - //MoveTo(x,y); - //Line(0,0); - bits[x / 8] |= (0x80 >> (x%8)); - } - accumV[x] = accum = accum / numtype(2); - } - Rect r2; - SetRect(&r2,0,y,r.right,y+1); + numtype thresh = preRandoms[randIdx++]; + if(randIdx == 29*31) + randIdx = 0; + + accum += pixel; + accum += accumV[x]; + if(accum >= thresh) + accum -= 1; + else + { + //MoveTo(x,y); + //Line(0,0); + bits[x / 8] |= (0x80 >> (x%8)); + } + accumV[x] = accum = accum / numtype(2); + } + Rect r2; + SetRect(&r2,0,y,r.right,y+1); #if TARGET_API_MAC_CARBON - CopyBits(&line, GetPortBitMapForCopyBits(GetWindowPort(win)), &line.bounds, &r2, srcCopy, NULL); + CopyBits(&line, GetPortBitMapForCopyBits(GetWindowPort(win)), &line.bounds, &r2, srcCopy, NULL); #else - CopyBits(&line, &win->portBits, &line.bounds, &r2, srcCopy, NULL); + CopyBits(&line, &win->portBits, &line.bounds, &r2, srcCopy, NULL); #endif - if(Button()) - return 0; + if(Button()) + return 0; #if TARGET_API_MAC_CARBON - QDFlushPortBuffer(GetWindowPort(win),NULL); + QDFlushPortBuffer(GetWindowPort(win),NULL); #endif - } - long endTime = TickCount(); - - char buf[256]; - unsigned char* pstr = (unsigned char*)buf; - std::sprintf(buf+1, "pps = %d %ld %ld %ld %ld", (int)( (long)r.right * r.bottom * 60 / (endTime - startTime) ), - fixed::nMul, fixed::nIMul, fixed::nDiv, fixed::nSqrt); - buf[0] = std::strlen(buf+1); - - SetRect(&r, 10, 10, 10 + StringWidth(pstr) + 10, 30); - PaintRect(&r); - PenMode(patXor); - FrameRect(&r); - MoveTo(15,25); - TextMode(srcBic); - DrawString(pstr); + } + long endTime = TickCount(); + + char buf[256]; + unsigned char* pstr = (unsigned char*)buf; + std::sprintf(buf+1, "pps = %d %ld %ld %ld %ld", (int)( (long)r.right * r.bottom * 60 / (endTime - startTime) ), + fixed::nMul, fixed::nIMul, fixed::nDiv, fixed::nSqrt); + buf[0] = std::strlen(buf+1); + + SetRect(&r, 10, 10, 10 + StringWidth(pstr) + 10, 30); + PaintRect(&r); + PenMode(patXor); + FrameRect(&r); + MoveTo(15,25); + TextMode(srcBic); + DrawString(pstr); #if TARGET_API_MAC_CARBON - QDFlushPortBuffer(GetWindowPort(win),NULL); + QDFlushPortBuffer(GetWindowPort(win),NULL); #endif - - while(!Button()) - ; - FlushEvents(everyEvent, -1); - return 0; + + while(!Button()) + ; + FlushEvents(everyEvent, -1); + return 0; } diff --git a/Samples/SystemExtension/CMakeLists.txt b/Samples/SystemExtension/CMakeLists.txt index 4ef8b3c696..d3593c8984 100644 --- a/Samples/SystemExtension/CMakeLists.txt +++ b/Samples/SystemExtension/CMakeLists.txt @@ -25,10 +25,10 @@ # Build the code resource as a regular executable # (not using the add_application macro) add_executable(SystemExtension - SystemExtension.c - ShowInitIcon.c - SystemExtension.r - ShowInitIcon.h) + SystemExtension.c + ShowInitIcon.c + SystemExtension.r + ShowInitIcon.h) if(TARGET retrocrt) # Hack: if we are building as part of the Retro68 source tree, @@ -40,23 +40,23 @@ endif(TARGET retrocrt) set_target_properties(SystemExtension PROPERTIES - OUTPUT_NAME SystemExtension.flt - - # set a linker flag that says we want a flat piece - # of code in a data file - LINK_FLAGS -Wl,--mac-flat) + OUTPUT_NAME SystemExtension.flt + + # set a linker flag that says we want a flat piece + # of code in a data file + LINK_FLAGS -Wl,--mac-flat) - # Use Rez to put it together + # Use Rez to put it together add_custom_command( - OUTPUT SystemExtension.bin SystemExtension.dsk - COMMAND ${REZ} -I ${REZ_INCLUDE_PATH} - ${CMAKE_CURRENT_SOURCE_DIR}/SystemExtension.r - --copy ${CMAKE_CURRENT_SOURCE_DIR}/Icons.rsrc.bin - -o SystemExtension.bin - --cc SystemExtension.dsk - --cc SystemExtension - -t INIT - DEPENDS SystemExtension SystemExtension.r Icons.rsrc.bin) + OUTPUT SystemExtension.bin SystemExtension.dsk + COMMAND ${REZ} -I ${REZ_INCLUDE_PATH} + ${CMAKE_CURRENT_SOURCE_DIR}/SystemExtension.r + --copy ${CMAKE_CURRENT_SOURCE_DIR}/Icons.rsrc.bin + -o SystemExtension.bin + --cc SystemExtension.dsk + --cc SystemExtension + -t INIT + DEPENDS SystemExtension SystemExtension.r Icons.rsrc.bin) add_custom_target(SystemExtension_INIT ALL DEPENDS SystemExtension.dsk) diff --git a/Samples/SystemExtension/ShowInitIcon.c b/Samples/SystemExtension/ShowInitIcon.c index 336130a9e3..c7bbffb7dd 100644 --- a/Samples/SystemExtension/ShowInitIcon.c +++ b/Samples/SystemExtension/ShowInitIcon.c @@ -33,10 +33,10 @@ // The MPW C compiler doesn't accept variables declared at an absolute address, so I use these macros instead. // Only one macro is defined per variable; there is no need to define a Set and a Get accessor like in . -#define LMVCheckSum (* (unsigned short*) 0x928) -#define LMVCoord (* ( short*) 0x92A) -#define LMHCoord (* ( short*) 0x92C) -#define LMHCheckSum (* (unsigned short*) 0x92E) +#define LMVCheckSum (* (unsigned short*) 0x928) +#define LMVCoord (* ( short*) 0x92A) +#define LMHCoord (* ( short*) 0x92C) +#define LMHCheckSum (* (unsigned short*) 0x92E) // --------------------------------------------------------------------------------------------------------------------- // Prototypes for the subroutines. The main routine comes first; this is necessary to make THINK C's "Custom Header" option work. @@ -50,41 +50,41 @@ static void DrawBWIcon (short iconID, Rect *iconRect); // Main routine. typedef struct { - QDGlobals qd; // Storage for the QuickDraw globals - long qdGlobalsPtr; // A5 points to this place; it will contain a pointer to qd + QDGlobals qd; // Storage for the QuickDraw globals + long qdGlobalsPtr; // A5 points to this place; it will contain a pointer to qd } QDStorage; pascal void ShowInitIcon (short iconFamilyID, Boolean advance) { - long oldA5; // Original value of register A5 - QDStorage qds; // Fake QD globals - CGrafPort colorPort; - GrafPort bwPort; - Rect destRect; - SysEnvRec environment; // Machine configuration. - - oldA5 = SetA5((long) &qds.qdGlobalsPtr); // Tell A5 to point to the end of the fake QD Globals - InitGraf(&qds.qd.thePort); // Initialize the fake QD Globals - - SysEnvirons(curSysEnvVers, &environment); // Find out what kind of machine this is + long oldA5; // Original value of register A5 + QDStorage qds; // Fake QD globals + CGrafPort colorPort; + GrafPort bwPort; + Rect destRect; + SysEnvRec environment; // Machine configuration. + + oldA5 = SetA5((long) &qds.qdGlobalsPtr); // Tell A5 to point to the end of the fake QD Globals + InitGraf(&qds.qd.thePort); // Initialize the fake QD Globals + + SysEnvirons(curSysEnvVers, &environment); // Find out what kind of machine this is - ComputeIconRect(&destRect, &qds.qd.screenBits.bounds); // Compute where the icon should be drawn + ComputeIconRect(&destRect, &qds.qd.screenBits.bounds); // Compute where the icon should be drawn - if (environment.systemVersion >= 0x0700 && environment.hasColorQD) { - OpenCPort(&colorPort); - PlotIconID(&destRect, atNone, ttNone, iconFamilyID); - CloseCPort(&colorPort); - } - else { - OpenPort(&bwPort); - DrawBWIcon(iconFamilyID, &destRect); - ClosePort(&bwPort); - } - - if (advance) - AdvanceIconPosition (&destRect); - - SetA5(oldA5); // Restore A5 to its previous value + if (environment.systemVersion >= 0x0700 && environment.hasColorQD) { + OpenCPort(&colorPort); + PlotIconID(&destRect, atNone, ttNone, iconFamilyID); + CloseCPort(&colorPort); + } + else { + OpenPort(&bwPort); + DrawBWIcon(iconFamilyID, &destRect); + ClosePort(&bwPort); + } + + if (advance) + AdvanceIconPosition (&destRect); + + SetA5(oldA5); // Restore A5 to its previous value } // --------------------------------------------------------------------------------------------------------------------- @@ -92,7 +92,7 @@ pascal void ShowInitIcon (short iconFamilyID, Boolean advance) static unsigned short CheckSum (short x) { - return (unsigned short)(((x << 1) | (x >> 15)) ^ 0x1021); + return (unsigned short)(((x << 1) | (x >> 15)) ^ 0x1021); } // --------------------------------------------------------------------------------------------------------------------- @@ -100,56 +100,56 @@ static unsigned short CheckSum (short x) static void ComputeIconRect (Rect* iconRect, Rect* screenBounds) { - if (CheckSum(LMHCoord) != LMHCheckSum) // If we are first, we need to initialize the shared data. - LMHCoord = 8; - if (CheckSum(LMVCoord) != LMVCheckSum) - LMVCoord = (short)(screenBounds->bottom - 40); - - if (LMHCoord + 34 > screenBounds->right) { // Check whether we must wrap - iconRect->left = 8; - iconRect->top = (short)(LMVCoord - 40); - } - else { - iconRect->left = LMHCoord; - iconRect->top = LMVCoord; - } - iconRect->right = (short)(iconRect->left + 32); - iconRect->bottom = (short)(iconRect->top + 32); + if (CheckSum(LMHCoord) != LMHCheckSum) // If we are first, we need to initialize the shared data. + LMHCoord = 8; + if (CheckSum(LMVCoord) != LMVCheckSum) + LMVCoord = (short)(screenBounds->bottom - 40); + + if (LMHCoord + 34 > screenBounds->right) { // Check whether we must wrap + iconRect->left = 8; + iconRect->top = (short)(LMVCoord - 40); + } + else { + iconRect->left = LMHCoord; + iconRect->top = LMVCoord; + } + iconRect->right = (short)(iconRect->left + 32); + iconRect->bottom = (short)(iconRect->top + 32); } // AdvanceIconPosition updates the shared global variables so that the next extension will draw its icon beside ours. static void AdvanceIconPosition (Rect* iconRect) { - LMHCoord = (short)(iconRect->left + 40); // Update the shared data - LMVCoord = iconRect->top; - LMHCheckSum = CheckSum(LMHCoord); - LMVCheckSum = CheckSum(LMVCoord); + LMHCoord = (short)(iconRect->left + 40); // Update the shared data + LMVCoord = iconRect->top; + LMHCheckSum = CheckSum(LMHCoord); + LMVCheckSum = CheckSum(LMVCoord); } // DrawBWIcon draws the 'ICN#' member of the icon family. It works under System 6. static void DrawBWIcon (short iconID, Rect *iconRect) { - Handle icon; - BitMap source, destination; - GrafPtr port; - - icon = Get1Resource('ICN#', iconID); - if (icon != NULL) { - HLock(icon); - // Prepare the source and destination bitmaps. - source.baseAddr = *icon + 128; // Mask address. - source.rowBytes = 4; - SetRect(&source.bounds, 0, 0, 32, 32); - GetPort(&port); - destination = port->portBits; - // Transfer the mask. - CopyBits(&source, &destination, &source.bounds, iconRect, srcBic, nil); - // Then the icon. - source.baseAddr = *icon; - CopyBits(&source, &destination, &source.bounds, iconRect, srcOr, nil); - } + Handle icon; + BitMap source, destination; + GrafPtr port; + + icon = Get1Resource('ICN#', iconID); + if (icon != NULL) { + HLock(icon); + // Prepare the source and destination bitmaps. + source.baseAddr = *icon + 128; // Mask address. + source.rowBytes = 4; + SetRect(&source.bounds, 0, 0, 32, 32); + GetPort(&port); + destination = port->portBits; + // Transfer the mask. + CopyBits(&source, &destination, &source.bounds, iconRect, srcBic, nil); + // Then the icon. + source.baseAddr = *icon; + CopyBits(&source, &destination, &source.bounds, iconRect, srcOr, nil); + } } // --------------------------------------------------------------------------------------------------------------------- diff --git a/Samples/SystemExtension/SystemExtension.c b/Samples/SystemExtension/SystemExtension.c index 2b0f81caa9..d32bd580d4 100644 --- a/Samples/SystemExtension/SystemExtension.c +++ b/Samples/SystemExtension/SystemExtension.c @@ -4,13 +4,13 @@ void _start() { - RETRO68_RELOCATE(); - Retro68CallConstructors(); + RETRO68_RELOCATE(); + Retro68CallConstructors(); - ShowInitIcon(130, false); - Delay(20, NULL); - ShowInitIcon(128, true); - Delay(40, NULL); + ShowInitIcon(130, false); + Delay(20, NULL); + ShowInitIcon(128, true); + Delay(40, NULL); - Retro68FreeGlobals(); + Retro68FreeGlobals(); } diff --git a/Samples/WDEF/CMakeLists.txt b/Samples/WDEF/CMakeLists.txt index 74b177d5ea..1397e640cb 100644 --- a/Samples/WDEF/CMakeLists.txt +++ b/Samples/WDEF/CMakeLists.txt @@ -1,19 +1,19 @@ -# Copyright 2015 Wolfgang Thaller. +# Copyright 2015 Wolfgang Thaller. # -# This file is part of Retro68. +# This file is part of Retro68. # -# Retro68 is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Retro68 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Retro68 is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Retro68 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# You should have received a copy of the GNU General Public License -# along with Retro68. If not, see . +# You should have received a copy of the GNU General Public License +# along with Retro68. If not, see . # To use this example as a standalone project using CMake: # mkdir build @@ -78,14 +78,14 @@ add_custom_command( # Now build the application add_application(WDEFShell - wdefshell.c + wdefshell.c wdefshell.r wdef.c # the WDEF as a plain source file in the application # the separately compiled WDEF resource ${CMAKE_CURRENT_BINARY_DIR}/WDEF.rsrc.bin - ) + ) # Again, add some options to make things smaller. set_target_properties(WDEFShell PROPERTIES COMPILE_OPTIONS -ffunction-sections) diff --git a/Samples/WDEF/wdefshell.c b/Samples/WDEF/wdefshell.c index 492b04602c..612565fc5f 100644 --- a/Samples/WDEF/wdefshell.c +++ b/Samples/WDEF/wdefshell.c @@ -300,5 +300,5 @@ int main() } } } - return 0; + return 0; } diff --git a/TestApps/EmptyTest.c b/TestApps/EmptyTest.c index a46866d92e..905869dfa3 100644 --- a/TestApps/EmptyTest.c +++ b/TestApps/EmptyTest.c @@ -1,4 +1,4 @@ int main() { - return 0; + return 0; } diff --git a/TestApps/ExceptionTest.cc b/TestApps/ExceptionTest.cc index 50e0809706..590e299eda 100644 --- a/TestApps/ExceptionTest.cc +++ b/TestApps/ExceptionTest.cc @@ -1,20 +1,20 @@ /* - Copyright 2012 Wolfgang Thaller. + Copyright 2012 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include @@ -29,51 +29,51 @@ class Foo void foobar() { - throw Foo(); + throw Foo(); } void UnexpectedExceptionOccurred() { - printf("std::unexpected called.\n"); - printf("Press Enter...\n"); - getchar(); - exit(1); + printf("std::unexpected called.\n"); + printf("Press Enter...\n"); + getchar(); + exit(1); } void UncaughtExceptionOccurred() { - printf("std::terminate called.\n"); - printf("Press Enter...\n"); - getchar(); - exit(1); + printf("std::terminate called.\n"); + printf("Press Enter...\n"); + getchar(); + exit(1); } int main(int argc, char** argv) { - std::set_unexpected(&UnexpectedExceptionOccurred); - std::set_terminate(&UncaughtExceptionOccurred); - bool throwFail = false; - bool catchFail = true; - for(int i = 0; i < 5; i++) - { - int n = i == 0 ? 1 : 100; - printf("Exception speed test (%3d iterations): ", n); fflush(stdout); - long start = TickCount(); - for(int j = 0; j < n; j++) - { - try { foobar(); throwFail = true; } catch(...) { catchFail = false; } - } - long end = TickCount(); + std::set_unexpected(&UnexpectedExceptionOccurred); + std::set_terminate(&UncaughtExceptionOccurred); + bool throwFail = false; + bool catchFail = true; + for(int i = 0; i < 5; i++) + { + int n = i == 0 ? 1 : 100; + printf("Exception speed test (%3d iterations): ", n); fflush(stdout); + long start = TickCount(); + for(int j = 0; j < n; j++) + { + try { foobar(); throwFail = true; } catch(...) { catchFail = false; } + } + long end = TickCount(); - printf("%g ms per throw/catch\n",(end-start)*1000 / 60.0 / n); - } + printf("%g ms per throw/catch\n",(end-start)*1000 / 60.0 / n); + } - if(throwFail) - printf("******** FAILURE: throw didn't really throw\n"); - if(catchFail) - printf("******** FAILURE: catch block never entered\n"); + if(throwFail) + printf("******** FAILURE: throw didn't really throw\n"); + if(catchFail) + printf("******** FAILURE: catch block never entered\n"); - printf("Press Enter...\n"); - getchar(); - return 0; + printf("Press Enter...\n"); + getchar(); + return 0; } diff --git a/TestApps/InitTest.cc b/TestApps/InitTest.cc index d4ed4cc664..57e29abed7 100644 --- a/TestApps/InitTest.cc +++ b/TestApps/InitTest.cc @@ -1,20 +1,20 @@ /* - Copyright 2012 Wolfgang Thaller. + Copyright 2012 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with Retro68. If not, see . + You should have received a copy of the GNU General Public License + along with Retro68. If not, see . */ #include @@ -24,18 +24,18 @@ class Foo { public: - Foo() - { - printf("Foo::Foo() was called.\n"); - } - ~Foo() - { - printf("Foo::~Foo() was called. (delaying 1 sec)\n"); + Foo() + { + printf("Foo::Foo() was called.\n"); + } + ~Foo() + { + printf("Foo::~Foo() was called. (delaying 1 sec)\n"); - unsigned long start = TickCount(); - while(TickCount() < start + 60) - ; - } + unsigned long start = TickCount(); + while(TickCount() < start + 60) + ; + } }; @@ -44,20 +44,20 @@ Foo foo; __attribute__((constructor)) void con() { - printf("con() called.\n"); + printf("con() called.\n"); } __attribute__((destructor)) void des() { - printf("des() called. (delaying 1 sec)\n"); - unsigned long start = TickCount(); - while(TickCount() < start + 60) - ; + printf("des() called. (delaying 1 sec)\n"); + unsigned long start = TickCount(); + while(TickCount() < start + 60) + ; } int main(int argc, char** argv) { - printf("Entering main. Press Enter.\n"); - getchar(); - return 0; + printf("Entering main. Press Enter.\n"); + getchar(); + return 0; } diff --git a/cmake/add_application.cmake b/cmake/add_application.cmake index ab647adc5c..c899af741e 100644 --- a/cmake/add_application.cmake +++ b/cmake/add_application.cmake @@ -5,59 +5,59 @@ cmake_policy(SET CMP0012 NEW) function(add_application name) - set(options DEBUGBREAK CONSOLE) - set(oneValueArgs TYPE CREATOR) - set(multiValueArgs FILES MAKEAPPL_ARGS) + set(options DEBUGBREAK CONSOLE) + set(oneValueArgs TYPE CREATOR) + set(multiValueArgs FILES MAKEAPPL_ARGS) - cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - list(APPEND ARGS_FILES ${ARGS_UNPARSED_ARGUMENTS}) + list(APPEND ARGS_FILES ${ARGS_UNPARSED_ARGUMENTS}) - set(REZ_FLAGS) - if(CMAKE_SYSTEM_NAME MATCHES RetroPPC OR CMAKE_SYSTEM_NAME MATCHES RetroCarbon) - if(CMAKE_SYSTEM_NAME MATCHES RetroCarbon) - set(REZ_FLAGS -DTARGET_API_MAC_CARBON=1) - endif() - endif() - - set(files) - set(rsrc_files) - set(rez_files) - foreach(f ${ARGS_FILES}) - if(${f} MATCHES "\\.r$") - add_custom_command( - OUTPUT ${f}.rsrc.bin - COMMAND ${REZ} ${REZ_FLAGS} ${CMAKE_CURRENT_SOURCE_DIR}/${f} -I ${REZ_INCLUDE_PATH} -o ${f}.rsrc.bin + set(REZ_FLAGS) + if(CMAKE_SYSTEM_NAME MATCHES RetroPPC OR CMAKE_SYSTEM_NAME MATCHES RetroCarbon) + if(CMAKE_SYSTEM_NAME MATCHES RetroCarbon) + set(REZ_FLAGS -DTARGET_API_MAC_CARBON=1) + endif() + endif() + + set(files) + set(rsrc_files) + set(rez_files) + foreach(f ${ARGS_FILES}) + if(${f} MATCHES "\\.r$") + add_custom_command( + OUTPUT ${f}.rsrc.bin + COMMAND ${REZ} ${REZ_FLAGS} ${CMAKE_CURRENT_SOURCE_DIR}/${f} -I ${REZ_INCLUDE_PATH} -o ${f}.rsrc.bin DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${f}) list(APPEND rsrc_files "${CMAKE_CURRENT_BINARY_DIR}/${f}.rsrc.bin") - list(APPEND rez_files "${f}") - elseif(${f} MATCHES "\\.rsrc$") + list(APPEND rez_files "${f}") + elseif(${f} MATCHES "\\.rsrc$") get_filename_component(abspath "${f}" ABSOLUTE) list(APPEND rsrc_files "${abspath}") - elseif(${f} MATCHES "\\.rsrc.bin$") + elseif(${f} MATCHES "\\.rsrc.bin$") get_filename_component(abspath "${f}" ABSOLUTE) list(APPEND rsrc_files "${abspath}") else() get_filename_component(abspath "${f}" ABSOLUTE) list(APPEND files "${abspath}") - endif() - endforeach() + endif() + endforeach() - add_executable(${name} ${files} ${rez_files}) + add_executable(${name} ${files} ${rez_files}) - if(${ARGS_DEBUGBREAK}) - target_link_options(${name} PRIVATE "LINKER:--defsym=__break_on_entry=1") - endif() - if(${ARGS_CONSOLE}) + if(${ARGS_DEBUGBREAK}) + target_link_options(${name} PRIVATE "LINKER:--defsym=__break_on_entry=1") + endif() + if(${ARGS_CONSOLE}) if(TARGET RetroConsole OR NOT (CMAKE_SYSTEM_NAME MATCHES RetroCarbon)) target_link_libraries(${name} RetroConsole) else() target_link_libraries(${name} RetroConsoleCarbon) endif() - # RetroConsole library uses C++: - set_target_properties(${name} PROPERTIES LINKER_LANGUAGE CXX) - endif() + # RetroConsole library uses C++: + set_target_properties(${name} PROPERTIES LINKER_LANGUAGE CXX) + endif() foreach(f ${rsrc_files}) # DO NOT add --copy here. @@ -66,66 +66,66 @@ function(add_application name) # Currently, the --copy flag has the side effect that Rez processes all --copy inputs # before other inputs, so this messes up the overriding mechanics, leading to the wrong SIZE resource # being included. (duplicate resources shouldn't be replaced silently, and overriding should be explicit...) - list(APPEND ARGS_MAKEAPPL_ARGS "${f}") - endforeach() + list(APPEND ARGS_MAKEAPPL_ARGS "${f}") + endforeach() - if(NOT ARGS_TYPE) - set(ARGS_TYPE "APPL") - endif() - if(NOT ARGS_CREATOR) - set(ARGS_CREATOR "????") - endif() + if(NOT ARGS_TYPE) + set(ARGS_TYPE "APPL") + endif() + if(NOT ARGS_CREATOR) + set(ARGS_CREATOR "????") + endif() - if(TARGET retrocrt) + if(TARGET retrocrt) add_dependencies(${name} retrocrt) - endif(TARGET retrocrt) + endif(TARGET retrocrt) - if(CMAKE_SYSTEM_NAME MATCHES Retro68) + if(CMAKE_SYSTEM_NAME MATCHES Retro68) - set_target_properties(${name} PROPERTIES OUTPUT_NAME ${name}.code.bin) + set_target_properties(${name} PROPERTIES OUTPUT_NAME ${name}.code.bin) - add_custom_command( - OUTPUT ${name}.bin ${name}.APPL ${name}.dsk ${name}.ad "%${name}.ad" - COMMAND ${REZ} ${REZ_FLAGS} - ${REZ_TEMPLATES_PATH}/Retro68APPL.r - -I${REZ_INCLUDE_PATH} - --copy "${name}.code.bin" - -o "${name}.bin" - -t "${ARGS_TYPE}" -c "${ARGS_CREATOR}" - --cc "${name}.dsk" --cc "${name}.APPL" --cc "%${name}.ad" - ${ARGS_MAKEAPPL_ARGS} - DEPENDS ${name} ${rsrc_files}) - add_custom_target(${name}_APPL ALL DEPENDS ${name}.bin) + add_custom_command( + OUTPUT ${name}.bin ${name}.APPL ${name}.dsk ${name}.ad "%${name}.ad" + COMMAND ${REZ} ${REZ_FLAGS} + ${REZ_TEMPLATES_PATH}/Retro68APPL.r + -I${REZ_INCLUDE_PATH} + --copy "${name}.code.bin" + -o "${name}.bin" + -t "${ARGS_TYPE}" -c "${ARGS_CREATOR}" + --cc "${name}.dsk" --cc "${name}.APPL" --cc "%${name}.ad" + ${ARGS_MAKEAPPL_ARGS} + DEPENDS ${name} ${rsrc_files}) + add_custom_target(${name}_APPL ALL DEPENDS ${name}.bin) - elseif(CMAKE_SYSTEM_NAME MATCHES RetroPPC OR CMAKE_SYSTEM_NAME MATCHES RetroCarbon) - if(CMAKE_SYSTEM_NAME MATCHES RetroCarbon) - set(REZ_TEMPLATE "${REZ_TEMPLATES_PATH}/RetroCarbonAPPL.r") - else() - set(REZ_TEMPLATE "${REZ_TEMPLATES_PATH}/RetroPPCAPPL.r") - endif() - - set_target_properties(${name} PROPERTIES OUTPUT_NAME ${name}.xcoff) - add_custom_command( - OUTPUT ${name}.pef - COMMAND ${MAKE_PEF} "${name}.xcoff" -o "${name}.pef" - DEPENDS ${name}) + elseif(CMAKE_SYSTEM_NAME MATCHES RetroPPC OR CMAKE_SYSTEM_NAME MATCHES RetroCarbon) + if(CMAKE_SYSTEM_NAME MATCHES RetroCarbon) + set(REZ_TEMPLATE "${REZ_TEMPLATES_PATH}/RetroCarbonAPPL.r") + else() + set(REZ_TEMPLATE "${REZ_TEMPLATES_PATH}/RetroPPCAPPL.r") + endif() + + set_target_properties(${name} PROPERTIES OUTPUT_NAME ${name}.xcoff) + add_custom_command( + OUTPUT ${name}.pef + COMMAND ${MAKE_PEF} "${name}.xcoff" -o "${name}.pef" + DEPENDS ${name}) - add_custom_command( - OUTPUT ${name}.bin ${name}.APPL ${name}.dsk ${name}.ad "%${name}.ad" - COMMAND ${REZ} - ${REZ_FLAGS} - ${REZ_TEMPLATE} - -I${REZ_INCLUDE_PATH} - -DCFRAG_NAME="\\"${name}\\"" - -o "${name}.bin" --cc "${name}.dsk" --cc "${name}.APPL" - --cc "%${name}.ad" - -t "${ARGS_TYPE}" -c "${ARGS_CREATOR}" - --data ${name}.pef - ${ARGS_MAKEAPPL_ARGS} - DEPENDS ${name}.pef ${rsrc_files}) - add_custom_target(${name}_APPL ALL DEPENDS ${name}.bin) - endif() + add_custom_command( + OUTPUT ${name}.bin ${name}.APPL ${name}.dsk ${name}.ad "%${name}.ad" + COMMAND ${REZ} + ${REZ_FLAGS} + ${REZ_TEMPLATE} + -I${REZ_INCLUDE_PATH} + -DCFRAG_NAME="\\"${name}\\"" + -o "${name}.bin" --cc "${name}.dsk" --cc "${name}.APPL" + --cc "%${name}.ad" + -t "${ARGS_TYPE}" -c "${ARGS_CREATOR}" + --data ${name}.pef + ${ARGS_MAKEAPPL_ARGS} + DEPENDS ${name}.pef ${rsrc_files}) + add_custom_target(${name}_APPL ALL DEPENDS ${name}.bin) + endif() endfunction() diff --git a/interfaces-and-libraries.sh b/interfaces-and-libraries.sh index afe1dd29f1..208df2acf5 100755 --- a/interfaces-and-libraries.sh +++ b/interfaces-and-libraries.sh @@ -18,272 +18,272 @@ function locateInterfaceThing() { - local varname=$1 - local name=$2 - printf "Searching for %-25s" "$name..." - local found=`find "$INTERFACES_DIR" -name ".*" -prune -o -name $name -print` - if [ -n "$found" ]; then - eval "$varname=\$found" - echo ${found#$INTERFACES_DIR/} - return 0 # success - else - echo "NOT FOUND" - return 1 # failure - fi + local varname=$1 + local name=$2 + printf "Searching for %-25s" "$name..." + local found=`find "$INTERFACES_DIR" -name ".*" -prune -o -name $name -print` + if [ -n "$found" ]; then + eval "$varname=\$found" + echo ${found#$INTERFACES_DIR/} + return 0 # success + else + echo "NOT FOUND" + return 1 # failure + fi } function explainInterfaces() { - echo "Please get a copy of Apple's Universal Interfaces & Libraries, " - echo "version 3.x, and place it in the InterfacesAndLibraries directory inside" - echo "the Retro68 source directory." - echo - echo "The exact directory layout does not matter, but there has to be" - echo " - a directory with C header files (usually \"CIncludes\")" - echo " - a directory with Rez header files (usually \"RIncludes\")" - echo " - (for 68K) a directory containing Interface.o (usually \"Libraries\")" - echo " - (for PPC) a directory containing InterfaceLib (usually \"SharedLibraries\")" - echo " - (for Carbon) Carbon.h and CarbonLib, in the same directories" - echo - echo "The Interfaces&Libraries folder from Apple's last MPW release (MPW 3.5 " - echo "aka MPW GM 'Golden Master') is known to work." - exit 1 + echo "Please get a copy of Apple's Universal Interfaces & Libraries, " + echo "version 3.x, and place it in the InterfacesAndLibraries directory inside" + echo "the Retro68 source directory." + echo + echo "The exact directory layout does not matter, but there has to be" + echo " - a directory with C header files (usually \"CIncludes\")" + echo " - a directory with Rez header files (usually \"RIncludes\")" + echo " - (for 68K) a directory containing Interface.o (usually \"Libraries\")" + echo " - (for PPC) a directory containing InterfaceLib (usually \"SharedLibraries\")" + echo " - (for Carbon) Carbon.h and CarbonLib, in the same directories" + echo + echo "The Interfaces&Libraries folder from Apple's last MPW release (MPW 3.5 " + echo "aka MPW GM 'Golden Master') is known to work." + exit 1 } function locateAndCheckInterfacesAndLibraries() { - echo "Looking for various files in $INTERFACES_DIR/..." + echo "Looking for various files in $INTERFACES_DIR/..." - if locateInterfaceThing CONDITIONALMACROS_H ConditionalMacros.h; then - CINCLUDES=`dirname "$CONDITIONALMACROS_H"` - else - echo "Could not find ConditionalMacros.h anywhere inside InterfaceAndLibraries/" - echo - explainInterfaces - fi + if locateInterfaceThing CONDITIONALMACROS_H ConditionalMacros.h; then + CINCLUDES=`dirname "$CONDITIONALMACROS_H"` + else + echo "Could not find ConditionalMacros.h anywhere inside InterfaceAndLibraries/" + echo + explainInterfaces + fi - if locateInterfaceThing CONDITIONALMACROS_R ConditionalMacros.r; then - RINCLUDES=`dirname "$CONDITIONALMACROS_R"` - else - echo "Could not find ConditionalMacros.r anywhere inside InterfaceAndLibraries/" - echo - explainInterfaces - fi + if locateInterfaceThing CONDITIONALMACROS_R ConditionalMacros.r; then + RINCLUDES=`dirname "$CONDITIONALMACROS_R"` + else + echo "Could not find ConditionalMacros.r anywhere inside InterfaceAndLibraries/" + echo + explainInterfaces + fi - if [ $BUILD_68K != false ]; then + if [ $BUILD_68K != false ]; then - if locateInterfaceThing INTERFACE_O Interface.o; then - M68KLIBRARIES=`dirname "$INTERFACE_O"` - else - echo "Could not find Interface.o anywhere inside InterfaceAndLibraries/" - echo "(This file is required for 68K support only)" - echo - explainInterfaces - fi + if locateInterfaceThing INTERFACE_O Interface.o; then + M68KLIBRARIES=`dirname "$INTERFACE_O"` + else + echo "Could not find Interface.o anywhere inside InterfaceAndLibraries/" + echo "(This file is required for 68K support only)" + echo + explainInterfaces + fi - fi + fi - if [ $BUILD_PPC != false ]; then + if [ $BUILD_PPC != false ]; then - if locateInterfaceThing INTERFACELIB InterfaceLib; then - SHAREDLIBRARIES=`dirname "$INTERFACELIB"` - else - echo "Could not find InterfaceLib anywhere inside InterfaceAndLibraries/" - echo "(This file is required for PowerPC support only)" - echo - explainInterfaces - fi + if locateInterfaceThing INTERFACELIB InterfaceLib; then + SHAREDLIBRARIES=`dirname "$INTERFACELIB"` + else + echo "Could not find InterfaceLib anywhere inside InterfaceAndLibraries/" + echo "(This file is required for PowerPC support only)" + echo + explainInterfaces + fi - if locateInterfaceThing OPENTRANSPORTAPPPPC OpenTransportAppPPC.o; then - PPCLIBRARIES=`dirname "$OPENTRANSPORTAPPPPC"` - else - echo "Could not find OpenTransportAppPPC.o anywhere inside InterfaceAndLibraries/" - echo "(This file is required for OpenTransport on PPC only)" - fi + if locateInterfaceThing OPENTRANSPORTAPPPPC OpenTransportAppPPC.o; then + PPCLIBRARIES=`dirname "$OPENTRANSPORTAPPPPC"` + else + echo "Could not find OpenTransportAppPPC.o anywhere inside InterfaceAndLibraries/" + echo "(This file is required for OpenTransport on PPC only)" + fi - fi + fi - if [ $BUILD_CARBON != false ]; then - if locateInterfaceThing CARBON_H Carbon.h; then - carbondir=`dirname "$CARBON_H"` - if [ "$carbondir" != "$CINCLUDES" ]; then - echo "Carbon.h found, but not in the same directory as ConditionalMacros.h." - echo "This is confusing." - echo - explainInterfaces - fi - else - echo "Could not find Carbon.h anywhere inside InterfaceAndLibraries/" - echo "(This file is required for Carbon support only)" - echo - explainInterfaces - fi - if locateInterfaceThing CARBONLIB CarbonLib; then - carbondir=`dirname "$CARBONLIB"` - if [ "$carbondir" != "$SHAREDLIBRARIES" ]; then - echo "CarbonLib found, but not in the same directory as InterfaceLib." - echo "This is confusing." - echo - explainInterfaces - fi - else - echo "Could not find CarbonLib anywhere inside InterfaceAndLibraries/" - echo "(This file is required for Carbon support only)" - echo - explainInterfaces - fi - fi + if [ $BUILD_CARBON != false ]; then + if locateInterfaceThing CARBON_H Carbon.h; then + carbondir=`dirname "$CARBON_H"` + if [ "$carbondir" != "$CINCLUDES" ]; then + echo "Carbon.h found, but not in the same directory as ConditionalMacros.h." + echo "This is confusing." + echo + explainInterfaces + fi + else + echo "Could not find Carbon.h anywhere inside InterfaceAndLibraries/" + echo "(This file is required for Carbon support only)" + echo + explainInterfaces + fi + if locateInterfaceThing CARBONLIB CarbonLib; then + carbondir=`dirname "$CARBONLIB"` + if [ "$carbondir" != "$SHAREDLIBRARIES" ]; then + echo "CarbonLib found, but not in the same directory as InterfaceLib." + echo "This is confusing." + echo + explainInterfaces + fi + else + echo "Could not find CarbonLib anywhere inside InterfaceAndLibraries/" + echo "(This file is required for Carbon support only)" + echo + explainInterfaces + fi + fi } # remove old symlinks in $PREFIX/*-apple-macos/include/ # and link files from $PREFIX/CIncludes function linkheaders() { - # incompatible with Universal Interfaces on case-insensitive file systems - # (and does not currently work anyways) - rm -f "$1"/threads.h + # incompatible with Universal Interfaces on case-insensitive file systems + # (and does not currently work anyways) + rm -f "$1"/threads.h - # the following command doesn't work on older Mac OS X versions. - # allow it to fail quietly, at worst we leave some dangling symlinks around - # in the rare situation that headers are removed from the input directory - find "$1" -lname "../../CIncludes/*" -delete || true - (cd "$1" && find "../../CIncludes/" -name '*.h' -exec ln -s {} . \;) + # the following command doesn't work on older Mac OS X versions. + # allow it to fail quietly, at worst we leave some dangling symlinks around + # in the rare situation that headers are removed from the input directory + find "$1" -lname "../../CIncludes/*" -delete || true + (cd "$1" && find "../../CIncludes/" -name '*.h' -exec ln -s {} . \;) } function setupPEFBinaryFormat() { - (export LC_ALL=C; sed 's/\r$//' < "$CINCLUDES/PEFBinaryFormat.h" | tr '\r' '\n' > "$PREFIX/include/PEFBinaryFormat.h") + (export LC_ALL=C; sed 's/\r$//' < "$CINCLUDES/PEFBinaryFormat.h" | tr '\r' '\n' > "$PREFIX/include/PEFBinaryFormat.h") } function setUpInterfacesAndLibraries() { - echo "Preparing CIncludes..." - rm -rf "$PREFIX/CIncludes" - mkdir "$PREFIX/CIncludes" - sh "$SRC/prepare-headers.sh" "$CINCLUDES" "$PREFIX/CIncludes" + echo "Preparing CIncludes..." + rm -rf "$PREFIX/CIncludes" + mkdir "$PREFIX/CIncludes" + sh "$SRC/prepare-headers.sh" "$CINCLUDES" "$PREFIX/CIncludes" - echo "Preparing RIncludes..." - rm -rf "$PREFIX/RIncludes" - mkdir "$PREFIX/RIncludes" - sh "$SRC/prepare-rincludes.sh" "$RINCLUDES" "$PREFIX/RIncludes" + echo "Preparing RIncludes..." + rm -rf "$PREFIX/RIncludes" + mkdir "$PREFIX/RIncludes" + sh "$SRC/prepare-rincludes.sh" "$RINCLUDES" "$PREFIX/RIncludes" - echo "Creating Symlinks for CIncludes and RIncludes..." + echo "Creating Symlinks for CIncludes and RIncludes..." - if [ $BUILD_68K != false ]; then - ln -sf ../RIncludes $PREFIX/m68k-apple-macos/RIncludes - linkheaders $PREFIX/m68k-apple-macos/include - fi + if [ $BUILD_68K != false ]; then + ln -sf ../RIncludes $PREFIX/m68k-apple-macos/RIncludes + linkheaders $PREFIX/m68k-apple-macos/include + fi - if [ $BUILD_PPC != false ]; then - ln -sf ../RIncludes $PREFIX/powerpc-apple-macos/RIncludes - linkheaders $PREFIX/powerpc-apple-macos/include - fi + if [ $BUILD_PPC != false ]; then + ln -sf ../RIncludes $PREFIX/powerpc-apple-macos/RIncludes + linkheaders $PREFIX/powerpc-apple-macos/include + fi - FILE_LIST="$PREFIX/apple-libraries.txt" - rm -f "$FILE_LIST" - touch "$FILE_LIST" + FILE_LIST="$PREFIX/apple-libraries.txt" + rm -f "$FILE_LIST" + touch "$FILE_LIST" - if [ $BUILD_68K != false ]; then - echo "Converting 68K static libraries..." - for macobj in "${M68KLIBRARIES}/"*.o; do - if [ -r "$macobj" ]; then - libname=`basename "$macobj"` - libname=${libname%.o} - printf " %30s => %-30s\n" ${libname}.o lib${libname}.a - obj="$PREFIX/m68k-apple-macos/lib/$libname.o" - lib="$PREFIX/m68k-apple-macos/lib/lib${libname}.a" - rm -f $lib + if [ $BUILD_68K != false ]; then + echo "Converting 68K static libraries..." + for macobj in "${M68KLIBRARIES}/"*.o; do + if [ -r "$macobj" ]; then + libname=`basename "$macobj"` + libname=${libname%.o} + printf " %30s => %-30s\n" ${libname}.o lib${libname}.a + obj="$PREFIX/m68k-apple-macos/lib/$libname.o" + lib="$PREFIX/m68k-apple-macos/lib/lib${libname}.a" + rm -f $lib - set -o pipefail - ((ConvertObj "$macobj" | m68k-apple-macos-as - -o "$obj") || (rm "$obj" && false) ) \ - && m68k-apple-macos-ar cqs "$lib" "$obj" \ - && echo "m68k-apple-macos/lib/$libname.o" >> "$FILE_LIST" \ - && echo "m68k-apple-macos/lib/lib${libname}.a" >> "$FILE_LIST" - fi - done - fi + set -o pipefail + ((ConvertObj "$macobj" | m68k-apple-macos-as - -o "$obj") || (rm "$obj" && false) ) \ + && m68k-apple-macos-ar cqs "$lib" "$obj" \ + && echo "m68k-apple-macos/lib/$libname.o" >> "$FILE_LIST" \ + && echo "m68k-apple-macos/lib/lib${libname}.a" >> "$FILE_LIST" + fi + done + fi - if [ $BUILD_PPC != false ]; then - case `ResInfo -n "$INTERFACELIB" || echo 0` in - 0) - echo "WARNING: Couldn't read resource fork for \"$INTERFACELIB\"." - echo " Falling back to included import libraries." - echo "Copying readymade PowerPC import libraries..." - cp $SRC/ImportLibraries/*.a $PREFIX/powerpc-apple-macos/lib/ - ;; - *) - echo "Building PowerPC import libraries..." - for shlib in "${SHAREDLIBRARIES}/"*; do - libname=`basename "$shlib"` - implib=lib${libname}.a - printf " %30s => %-30s\n" ${libname} ${implib} - MakeImport "$shlib" "$PREFIX/powerpc-apple-macos/lib/$implib" \ - && echo "powerpc-apple-macos/lib/$implib" >> "$FILE_LIST" - done - ;; - esac + if [ $BUILD_PPC != false ]; then + case `ResInfo -n "$INTERFACELIB" || echo 0` in + 0) + echo "WARNING: Couldn't read resource fork for \"$INTERFACELIB\"." + echo " Falling back to included import libraries." + echo "Copying readymade PowerPC import libraries..." + cp $SRC/ImportLibraries/*.a $PREFIX/powerpc-apple-macos/lib/ + ;; + *) + echo "Building PowerPC import libraries..." + for shlib in "${SHAREDLIBRARIES}/"*; do + libname=`basename "$shlib"` + implib=lib${libname}.a + printf " %30s => %-30s\n" ${libname} ${implib} + MakeImport "$shlib" "$PREFIX/powerpc-apple-macos/lib/$implib" \ + && echo "powerpc-apple-macos/lib/$implib" >> "$FILE_LIST" + done + ;; + esac - if [ -d "${PPCLIBRARIES}" ]; then - echo "Copying static PPC libraries" - for obj in "${PPCLIBRARIES}/OpenT*.o" "${PPCLIBRARIES}/CarbonAccessors.o" "${PPCLIBRARIES}/CursorDevicesGlue.o"; do - if [ -r "$obj" ]; then - # copy the library: - cp "$obj" "$PREFIX/powerpc-apple-macos/lib/" - basename=`basename "${obj%.o}"` - # and wrap it in a .a archive for convenience - lib="$PREFIX"/powerpc-apple-macos/lib/lib$basename.a - rm -f "$lib" - powerpc-apple-macos-ar cqs "$lib" "$obj" - echo "powerpc-apple-macos/lib/$basename.o" >> "$FILE_LIST" - echo "powerpc-apple-macos/lib/lib$basename.a" >> "$FILE_LIST" - fi - done - fi - fi + if [ -d "${PPCLIBRARIES}" ]; then + echo "Copying static PPC libraries" + for obj in "${PPCLIBRARIES}/OpenT*.o" "${PPCLIBRARIES}/CarbonAccessors.o" "${PPCLIBRARIES}/CursorDevicesGlue.o"; do + if [ -r "$obj" ]; then + # copy the library: + cp "$obj" "$PREFIX/powerpc-apple-macos/lib/" + basename=`basename "${obj%.o}"` + # and wrap it in a .a archive for convenience + lib="$PREFIX"/powerpc-apple-macos/lib/lib$basename.a + rm -f "$lib" + powerpc-apple-macos-ar cqs "$lib" "$obj" + echo "powerpc-apple-macos/lib/$basename.o" >> "$FILE_LIST" + echo "powerpc-apple-macos/lib/lib$basename.a" >> "$FILE_LIST" + fi + done + fi + fi } function removeInterfacesAndLibraries() { - FILE_LIST="$PREFIX/apple-libraries.txt" - if [ -r "$FILE_LIST" ]; then - echo "Removing currently installed Apple Interfaces and Libraries..." - for file in `cat "$FILE_LIST"`; do - rm "$PREFIX/$file" - done - find "$PREFIX/m68k-apple-macos/include" -lname "../../CIncludes/*" -delete || true - find "$PREFIX/powerpc-apple-macos/include" -lname "../../CIncludes/*" -delete || true - rm "$PREFIX/m68k-apple-macos/RIncludes" - rm "$PREFIX/powerpc-apple-macos/RIncludes" - rm -rf "$PREFIX/CIncludes" - rm -rf "$PREFIX/RIncludes" - rm "$FILE_LIST" - rm "$PREFIX/include/PEFBinaryFormat.h" - fi + FILE_LIST="$PREFIX/apple-libraries.txt" + if [ -r "$FILE_LIST" ]; then + echo "Removing currently installed Apple Interfaces and Libraries..." + for file in `cat "$FILE_LIST"`; do + rm "$PREFIX/$file" + done + find "$PREFIX/m68k-apple-macos/include" -lname "../../CIncludes/*" -delete || true + find "$PREFIX/powerpc-apple-macos/include" -lname "../../CIncludes/*" -delete || true + rm "$PREFIX/m68k-apple-macos/RIncludes" + rm "$PREFIX/powerpc-apple-macos/RIncludes" + rm -rf "$PREFIX/CIncludes" + rm -rf "$PREFIX/RIncludes" + rm "$FILE_LIST" + rm "$PREFIX/include/PEFBinaryFormat.h" + fi } if [ "$0" = "$BASH_SOURCE" ]; then - # We are being run directly + # We are being run directly - if [ $# -lt 2 ]; then - echo "Usage: $0 /install/path /path/to/InterfacesAndLibraries" - echo " $0 /install/path --remove" - exit 1 - fi + if [ $# -lt 2 ]; then + echo "Usage: $0 /install/path /path/to/InterfacesAndLibraries" + echo " $0 /install/path --remove" + exit 1 + fi - PREFIX="$1" - INTERFACES_DIR="$2" - BUILD_68K=${3:-true} - BUILD_PPC=${4:-true} - BUILD_CARBON=${5:-true} - SRC=$(cd `dirname $0` && pwd -P) - export PATH="$PREFIX/bin:$PATH" + PREFIX="$1" + INTERFACES_DIR="$2" + BUILD_68K=${3:-true} + BUILD_PPC=${4:-true} + BUILD_CARBON=${5:-true} + SRC=$(cd `dirname $0` && pwd -P) + export PATH="$PREFIX/bin:$PATH" - if [ "${INTERFACES_DIR}" = "--remove" ]; then - removeInterfacesAndLibraries - else - locateAndCheckInterfacesAndLibraries - removeInterfacesAndLibraries + if [ "${INTERFACES_DIR}" = "--remove" ]; then + removeInterfacesAndLibraries + else + locateAndCheckInterfacesAndLibraries + removeInterfacesAndLibraries setupPEFBinaryFormat - setUpInterfacesAndLibraries - fi + setUpInterfacesAndLibraries + fi fi diff --git a/libretro/CMakeLists.txt b/libretro/CMakeLists.txt index 0a8a4bf2a0..5490e3aee6 100644 --- a/libretro/CMakeLists.txt +++ b/libretro/CMakeLists.txt @@ -1,70 +1,70 @@ -# Copyright 2015 Wolfgang Thaller. +# Copyright 2015 Wolfgang Thaller. # -# This file is part of Retro68. +# This file is part of Retro68. # -# Retro68 is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# Retro68 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# Retro68 is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# Retro68 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. # -# Under Section 7 of GPL version 3, you are granted additional -# permissions described in the GCC Runtime Library Exception, version -# 3.1, as published by the Free Software Foundation. +# Under Section 7 of GPL version 3, you are granted additional +# permissions described in the GCC Runtime Library Exception, version +# 3.1, as published by the Free Software Foundation. # -# You should have received a copy of the GNU General Public License and -# a copy of the GCC Runtime Library Exception along with this program; -# see the files COPYING and COPYING.RUNTIME respectively. If not, see -# . +# You should have received a copy of the GNU General Public License and +# a copy of the GCC Runtime Library Exception along with this program; +# see the files COPYING and COPYING.RUNTIME respectively. If not, see +# . if(CMAKE_SYSTEM_NAME MATCHES Retro68) enable_language(ASM) set(ARCH_FILES - Retro68Runtime.h - start.c - relocate.c - PoorMansDebugging.h - MultiSegApp.c - LoadSeg.s - # glue.c - qdglobals.c - Retro68.r - Retro68APPL.r - ) + Retro68Runtime.h + start.c + relocate.c + PoorMansDebugging.h + MultiSegApp.c + LoadSeg.s + # glue.c + qdglobals.c + Retro68.r + Retro68APPL.r + ) - install(FILES Retro68Runtime.h DESTINATION include) - install(FILES Retro68.r Retro68APPL.r DESTINATION RIncludes) - + install(FILES Retro68Runtime.h DESTINATION include) + install(FILES Retro68.r Retro68APPL.r DESTINATION RIncludes) + elseif(CMAKE_SYSTEM_NAME MATCHES RetroPPC) - enable_language(ASM) - set(ARCH_FILES - ppcstart.c - ppcfpsave.s - qdglobals.c - RetroPPCAPPL.r) - install(FILES RetroPPCAPPL.r DESTINATION RIncludes) + enable_language(ASM) + set(ARCH_FILES + ppcstart.c + ppcfpsave.s + qdglobals.c + RetroPPCAPPL.r) + install(FILES RetroPPCAPPL.r DESTINATION RIncludes) elseif(CMAKE_SYSTEM_NAME MATCHES RetroCarbon) - enable_language(ASM) - set(ARCH_FILES - ppcstart.c - ppcfpsave.s - RetroCarbonAPPL.r) - install(FILES RetroCarbonAPPL.r DESTINATION RIncludes) + enable_language(ASM) + set(ARCH_FILES + ppcstart.c + ppcfpsave.s + RetroCarbonAPPL.r) + install(FILES RetroCarbonAPPL.r DESTINATION RIncludes) endif() add_library(retrocrt - malloc.c - syscalls.c - consolehooks.c - ${ARCH_FILES} + malloc.c + syscalls.c + consolehooks.c + ${ARCH_FILES} ) set_target_properties(retrocrt - PROPERTIES - COMPILE_OPTIONS -ffunction-sections) + PROPERTIES + COMPILE_OPTIONS -ffunction-sections) install(TARGETS retrocrt DESTINATION lib) diff --git a/libretro/MultiSegApp.c b/libretro/MultiSegApp.c index cb5f92abfb..020efbfae1 100644 --- a/libretro/MultiSegApp.c +++ b/libretro/MultiSegApp.c @@ -61,12 +61,12 @@ pascal void* Retro68LoadSegment(uint8_t *p) short id = jtEntry->far.id; uint32_t offset = jtEntry->far.offset; - /*{ - char buf[256]; - sprintf(buf+1, "Loading seg %d.;g", id); - buf[0] = strlen(buf+1); - DebugStr((unsigned char*) buf); - }*/ + /*{ + char buf[256]; + sprintf(buf+1, "Loading seg %d.;g", id); + buf[0] = strlen(buf+1); + DebugStr((unsigned char*) buf); + }*/ // TODO: UseResFile? Handle CODE = GetResource('CODE', id); @@ -82,20 +82,20 @@ pascal void* Retro68LoadSegment(uint8_t *p) if(header->loadAddress != base || header->currentA5 != a5) { long displacements[4] = { - base - header->loadAddress, // code - a5 - header->currentA5, - a5 - header->currentA5, - a5 - header->currentA5 - }; - + base - header->loadAddress, // code + a5 - header->currentA5, + a5 - header->currentA5, + a5 - header->currentA5 + }; + header->loadAddress = base; header->currentA5 = a5; - Handle RELA = NULL; - RELA = GetResource('RELA', id); - assert(RELA); - Retro68ApplyRelocations(base + 40, codeSize - 40, *RELA, displacements); - HPurge(RELA); + Handle RELA = NULL; + RELA = GetResource('RELA', id); + assert(RELA); + Retro68ApplyRelocations(base + 40, codeSize - 40, *RELA, displacements); + HPurge(RELA); } /* Update JT Entries */ @@ -127,48 +127,48 @@ pascal void* Retro68LoadSegment(uint8_t *p) static pascal void PatchedUnloadSeg(Ptr ptr) { - union JTEntry *jtEntry = (JTEntry*) (ptr - 2); - if(jtEntry->jmp.jmp != 0x4EF9) - return; // not loaded or invalid pointer. + union JTEntry *jtEntry = (JTEntry*) (ptr - 2); + if(jtEntry->jmp.jmp != 0x4EF9) + return; // not loaded or invalid pointer. - int id = jtEntry->jmp.id; - Handle CODE = GetResource('CODE', id); - uint8_t *base = StripAddressCompat((uint8_t *)*CODE); - CODEHeader *header = (CODEHeader*) base; - uint32_t codeSize = GetHandleSize(CODE); + int id = jtEntry->jmp.id; + Handle CODE = GetResource('CODE', id); + uint8_t *base = StripAddressCompat((uint8_t *)*CODE); + CODEHeader *header = (CODEHeader*) base; + uint32_t codeSize = GetHandleSize(CODE); - // TODO: check header->magic, pass on to original UnloadSeg? + // TODO: check header->magic, pass on to original UnloadSeg? - /* Load Exception Information */ - if (__register_frame_info) - { - int32_t offset = ((int32_t*) (base + codeSize))[-1]; - void *eh_frame_info = base + codeSize - 4 + offset; - __deregister_frame_info(eh_frame_info); - } + /* Load Exception Information */ + if (__register_frame_info) + { + int32_t offset = ((int32_t*) (base + codeSize))[-1]; + void *eh_frame_info = base + codeSize - 4 + offset; + __deregister_frame_info(eh_frame_info); + } - uint8_t * a5 = (uint8_t*) StripAddressCompat((void*)SetCurrentA5()); + uint8_t * a5 = (uint8_t*) StripAddressCompat((void*)SetCurrentA5()); - // FIXME: hardcoded JT offset, there is a LM global for this somewhere: - jtEntry = (JTEntry*) (a5 + 32 + header->farEntryOffset); - int n = header->nFarEntries; - while(n--) - { - if(jtEntry->jmp.jmp == 0x4EF9 && jtEntry->jmp.id == id) - { - uint32_t offset = (uint8_t*) jtEntry->jmp.addr - base; - jtEntry->far.loadseg = _LoadSeg; - jtEntry->far.offset = offset; - } - ++jtEntry; - } - if(relocState.hasFlushCodeCache) - FlushCodeCache(); + // FIXME: hardcoded JT offset, there is a LM global for this somewhere: + jtEntry = (JTEntry*) (a5 + 32 + header->farEntryOffset); + int n = header->nFarEntries; + while(n--) + { + if(jtEntry->jmp.jmp == 0x4EF9 && jtEntry->jmp.id == id) + { + uint32_t offset = (uint8_t*) jtEntry->jmp.addr - base; + jtEntry->far.loadseg = _LoadSeg; + jtEntry->far.offset = offset; + } + ++jtEntry; + } + if(relocState.hasFlushCodeCache) + FlushCodeCache(); - HUnlock(CODE); - HPurge(CODE); + HUnlock(CODE); + HPurge(CODE); } static void InstallPatches(); @@ -247,11 +247,11 @@ void Retro68InitMultisegApp() // Zero-initialize bss for(uint32_t *p = (uint32_t*) &_sbss; p < (uint32_t*) &_ebss; ++p) - *p = 0; + *p = 0; // Set up patched LoadSeg - // NOTE: OriginalLoadSeg is the first global variable we can use + // NOTE: OriginalLoadSeg is the first global variable we can use OriginalLoadSeg = GetToolTrapAddress(_LoadSeg); OriginalUnloadSeg = GetToolTrapAddress(_UnLoadSeg); OriginalExitToShell = GetToolTrapAddress(_ExitToShell); @@ -275,5 +275,5 @@ void Retro68InitMultisegApp() RELA = GetResource('RELA', 0); assert(RELA); Retro68ApplyRelocations(&_sdata, &_edata - &_sdata, *RELA, displacements); - ReleaseResource(RELA); + ReleaseResource(RELA); } diff --git a/libretro/PoorMansDebugging.h b/libretro/PoorMansDebugging.h index bfa50ee364..7badb4a104 100644 --- a/libretro/PoorMansDebugging.h +++ b/libretro/PoorMansDebugging.h @@ -1,26 +1,26 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #define ENABLE_ASSERT 1 @@ -38,46 +38,46 @@ #define assert(x) do { } while(0) #else #define assert(x) do { \ - if(!(x)) {\ - unsigned char str[6]; \ - int i; \ - int l = __LINE__; \ - for(i = 1; i < 6; i++) \ - str[i] = ' '; \ - str[0] = 5; \ - str[5] = '0'; \ - for(i = 5; l && i > 0; i--) \ - { \ - str[i] = '0' + (l % 10); \ - l /= 10; \ - } \ - DebugStr(str); \ - } \ - } while(0) + if(!(x)) {\ + unsigned char str[6]; \ + int i; \ + int l = __LINE__; \ + for(i = 1; i < 6; i++) \ + str[i] = ' '; \ + str[0] = 5; \ + str[5] = '0'; \ + for(i = 5; l && i > 0; i--) \ + { \ + str[i] = '0' + (l % 10); \ + l /= 10; \ + } \ + DebugStr(str); \ + } \ + } while(0) #endif #if !ENABLE_LOG #define log(x) do { } while(0) #else #define log(x) do { \ - {\ - unsigned char str[10]; \ - int ___i; \ - unsigned l = (x); \ - for(___i = 2; ___i < 10; ___i++) \ - str[___i] = ' '; \ - str[0] = 9; \ - str[1] = 'L'; \ - str[9] = '0'; \ - for(___i = 8; l && ___i > 1; ___i--) \ - { \ - str[___i] = '0' + (l & 0xF); \ - if((l & 0xF) >= 0xA) \ - str[___i] = 'A' - 10 + (l&0xF); \ - l >>= 4; \ - } \ - DebugStr(str); \ - } \ - } while(0) + {\ + unsigned char str[10]; \ + int ___i; \ + unsigned l = (x); \ + for(___i = 2; ___i < 10; ___i++) \ + str[___i] = ' '; \ + str[0] = 9; \ + str[1] = 'L'; \ + str[9] = '0'; \ + for(___i = 8; l && ___i > 1; ___i--) \ + { \ + str[___i] = '0' + (l & 0xF); \ + if((l & 0xF) >= 0xA) \ + str[___i] = 'A' - 10 + (l&0xF); \ + l >>= 4; \ + } \ + DebugStr(str); \ + } \ + } while(0) #endif diff --git a/libretro/Retro68Runtime.h b/libretro/Retro68Runtime.h index 7c6ed6fac7..627a0fd45b 100644 --- a/libretro/Retro68Runtime.h +++ b/libretro/Retro68Runtime.h @@ -1,43 +1,43 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include #include #define _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, STRIP) \ - do { \ - char *virtualstart, *realstart; \ - __asm__( "1:\n" \ - "\tmove.l #1b, %0\n" \ - "\tlea (1b:w,%%pc), %1" \ - : "=r"(virtualstart) , "=a"(realstart) ); \ - DISPLACEMENT = STRIP(realstart) - virtualstart; \ - } while(0) + do { \ + char *virtualstart, *realstart; \ + __asm__( "1:\n" \ + "\tmove.l #1b, %0\n" \ + "\tlea (1b:w,%%pc), %1" \ + : "=r"(virtualstart) , "=a"(realstart) ); \ + DISPLACEMENT = STRIP(realstart) - virtualstart; \ + } while(0) #define RETRO68_GET_DISPLACEMENT(DISPLACEMENT) \ - _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, ) + _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, ) // Calls to the StripAddress() trap are supposed to make sure addresses are 32-bit clean. // But this trap doesn’t exist on old ROMs and old system versions, @@ -49,18 +49,18 @@ #define StripAddress24(x) ((char*) ((unsigned long)(x) & 0x00FFFFFF)) #define RETRO68_GET_DISPLACEMENT_STRIP24(DISPLACEMENT) \ - _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, StripAddress24) + _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, StripAddress24) // original StripAddress #define RETRO68_GET_DISPLACEMENT_STRIP(DISPLACEMENT) \ - _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, StripAddress) + _RETRO68_GET_DISPLACEMENT(DISPLACEMENT, StripAddress) #define RETRO68_CALL_UNRELOCATED(FUN,ARGS) \ - do { \ - long displacement; \ - RETRO68_GET_DISPLACEMENT(displacement); \ - (*(typeof(&FUN)) ((char*)(&FUN) + displacement)) ARGS; \ - } while(0) + do { \ + long displacement; \ + RETRO68_GET_DISPLACEMENT(displacement); \ + (*(typeof(&FUN)) ((char*)(&FUN) + displacement)) ARGS; \ + } while(0) void Retro68Relocate(); void Retro68CallConstructors(); @@ -81,16 +81,16 @@ void Retro68ApplyRelocations(uint8_t *base, uint32_t size, void *relocations, ui struct object { long space[8]; }; extern void __register_frame_info (const void *, struct object *) - __attribute__ ((weak)); + __attribute__ ((weak)); extern void *__deregister_frame_info (const void *) - __attribute__ ((weak)); + __attribute__ ((weak)); typedef struct Retro68RelocState { - Ptr bssPtr; - Handle codeHandle; - char hasStripAddr; - char hasFlushCodeCache; + Ptr bssPtr; + Handle codeHandle; + char hasStripAddr; + char hasFlushCodeCache; } Retro68RelocState; extern Retro68RelocState relocState; diff --git a/libretro/consolehooks.c b/libretro/consolehooks.c index 3dc60558cc..2dda657b03 100644 --- a/libretro/consolehooks.c +++ b/libretro/consolehooks.c @@ -1,36 +1,36 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include ssize_t _consolewrite(int fd, const void *buf, size_t count) { - return -1; + return -1; } ssize_t _consoleread(int fd, void *buf, size_t count) { - return -1; + return -1; } diff --git a/libretro/glue.c b/libretro/glue.c index fe56277f86..7636b91f30 100644 --- a/libretro/glue.c +++ b/libretro/glue.c @@ -1,26 +1,26 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -37,11 +37,11 @@ pascal long _GetPtrSize(Ptr ptr) = { 0xA021 }; pascal Size GetPtrSize(Ptr ptr) { - long tmp = _GetPtrSize(ptr); - if(tmp > 0) - return (Size) tmp; - else - return 0; + long tmp = _GetPtrSize(ptr); + if(tmp > 0) + return (Size) tmp; + else + return 0; } #pragma parameter __D0 _GetHandleSize(__A0) @@ -49,11 +49,11 @@ pascal long _GetHandleSize(Handle h) = { 0xA025 }; pascal Size GetHandleSize(Handle h) { - long tmp = _GetHandleSize(h); - if(tmp > 0) - return (Size) tmp; - else - return 0; + long tmp = _GetHandleSize(h); + if(tmp > 0) + return (Size) tmp; + else + return 0; } #pragma parameter __A0 _PtrToHand(__A0, __D0) @@ -65,9 +65,9 @@ PtrToHand( Handle * dstHndl, long size) { - *dstHndl = _PtrToHand(srcPtr, size); + *dstHndl = _PtrToHand(srcPtr, size); - return MemError(); + return MemError(); } #pragma parameter __A0 _HandToHand(__A0) @@ -76,9 +76,9 @@ pascal Handle _HandToHand(Handle h) = { 0xA9E1 }; EXTERN_API( OSErr ) HandToHand(Handle * theHndl) { - *theHndl = _HandToHand(*theHndl); + *theHndl = _HandToHand(*theHndl); - return MemError(); + return MemError(); } #pragma parameter __D0 _StringToNum(__A0) @@ -89,7 +89,7 @@ StringToNum( ConstStr255Param theString, long * theNum) { - *theNum = _StringToNum(theString); + *theNum = _StringToNum(theString); } #pragma parameter _NumToString(__D0, __A0) @@ -100,7 +100,7 @@ NumToString( long theNum, Str255 theString) { - _NumToString(theNum, theString); + _NumToString(theNum, theString); } #pragma parameter __D0 _CmpString(__A0, __A1, __D0) @@ -119,36 +119,36 @@ EqualString( Boolean caseSensitive, Boolean diacSensitive) { - long lens = (str1[0] << 16) | str2[0]; - long result; - if(caseSensitive) - { - if(diacSensitive) - result = _CmpStringCase(str1+1, str2+1, lens); - else - result = _CmpStringCaseMarks(str1+1, str2+1, lens); - } - else - { - if(diacSensitive) - result = _CmpString(str1+1, str2+1, lens); - else - result = _CmpStringMarks(str1+1, str2+1, lens); - } - return result == 0; + long lens = (str1[0] << 16) | str2[0]; + long result; + if(caseSensitive) + { + if(diacSensitive) + result = _CmpStringCase(str1+1, str2+1, lens); + else + result = _CmpStringCaseMarks(str1+1, str2+1, lens); + } + else + { + if(diacSensitive) + result = _CmpString(str1+1, str2+1, lens); + else + result = _CmpStringMarks(str1+1, str2+1, lens); + } + return result == 0; } pascal void GetIndString(Str255 theString, short strListID, short index) { - Handle h = GetResource('STR#', strListID); - theString[0] = 0; - if(index > *(short*)*h) - return; - unsigned char *p = ((unsigned char*) *h) + 2; - while(--index > 0) - p += *p + 1; - if(index == 0) - memcpy(theString, p, p[0]+1); + Handle h = GetResource('STR#', strListID); + theString[0] = 0; + if(index > *(short*)*h) + return; + unsigned char *p = ((unsigned char*) *h) + 2; + while(--index > 0) + p += *p + 1; + if(index == 0) + memcpy(theString, p, p[0]+1); } EXTERN_API( UniversalProcPtr ) @@ -156,10 +156,10 @@ NGetTrapAddress( UInt16 trapNum, TrapType tTyp) { - if(tTyp == kOSTrapType) - return GetOSTrapAddress(trapNum); - else - return GetToolTrapAddress(trapNum); + if(tTyp == kOSTrapType) + return GetOSTrapAddress(trapNum); + else + return GetToolTrapAddress(trapNum); } EXTERN_API( void ) @@ -167,30 +167,30 @@ CountAppFiles( short * message, short * count) { - Handle h = LMGetAppParmHandle(); - if(!GetHandleSize(h)) - return; - *message = ((short*)*h)[0]; - *count = ((short*)*h)[1]; + Handle h = LMGetAppParmHandle(); + if(!GetHandleSize(h)) + return; + *message = ((short*)*h)[0]; + *count = ((short*)*h)[1]; } static AppFile* AppFilePtr(short index) { - Handle h = LMGetAppParmHandle(); - if(!GetHandleSize(h)) - return NULL; - short count = ((short*)*h)[1]; - if(index < 1 || index > count) - return NULL; - index--; + Handle h = LMGetAppParmHandle(); + if(!GetHandleSize(h)) + return NULL; + short count = ((short*)*h)[1]; + if(index < 1 || index > count) + return NULL; + index--; - Ptr p = *h + 4; - while(index) - { - AppFile *f = (AppFile*) p; - p += (8 + 1 + f->fName[0] + 1) & ~1; - } - return (AppFile*) p; + Ptr p = *h + 4; + while(index) + { + AppFile *f = (AppFile*) p; + p += (8 + 1 + f->fName[0] + 1) & ~1; + } + return (AppFile*) p; } EXTERN_API( void ) @@ -198,27 +198,27 @@ GetAppFiles( short index, AppFile * theFile) { - AppFile *ptr = AppFilePtr(index); - if(ptr) - memcpy(theFile, ptr, 8 + 1 + ptr->fName[0]); + AppFile *ptr = AppFilePtr(index); + if(ptr) + memcpy(theFile, ptr, 8 + 1 + ptr->fName[0]); } EXTERN_API( void ) ClrAppFiles(short index) { - AppFile *ptr = AppFilePtr(index); - if(ptr) - ptr->fType = 0; + AppFile *ptr = AppFilePtr(index); + if(ptr) + ptr->fType = 0; } pascal OSErr SetVol (ConstStr63Param volName, short vRefNum) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.volumeParam.ioNamePtr = (StringPtr)volName; - pb.volumeParam.ioVRefNum = vRefNum; - return PBSetVolSync(&pb); + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.volumeParam.ioNamePtr = (StringPtr)volName; + pb.volumeParam.ioVRefNum = vRefNum; + return PBSetVolSync(&pb); } EXTERN_API( OSErr ) @@ -226,169 +226,169 @@ GetVol( StringPtr volName, short * vRefNum) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.volumeParam.ioNamePtr = volName; - OSErr err = PBGetVolSync(&pb); - *vRefNum = pb.volumeParam.ioVRefNum; - return err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.volumeParam.ioNamePtr = volName; + OSErr err = PBGetVolSync(&pb); + *vRefNum = pb.volumeParam.ioVRefNum; + return err; } pascal OSErr UnmountVol (ConstStr63Param volName, short vRefNum) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.volumeParam.ioNamePtr = (StringPtr)volName; - pb.volumeParam.ioVRefNum = vRefNum; - return PBUnmountVolImmed(&pb); + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.volumeParam.ioNamePtr = (StringPtr)volName; + pb.volumeParam.ioVRefNum = vRefNum; + return PBUnmountVolImmed(&pb); } pascal OSErr Eject (ConstStr63Param volName, short vRefNum) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.volumeParam.ioNamePtr = (StringPtr)volName; - pb.volumeParam.ioVRefNum = vRefNum; - return PBEject(&pb); + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.volumeParam.ioNamePtr = (StringPtr)volName; + pb.volumeParam.ioVRefNum = vRefNum; + return PBEject(&pb); } pascal OSErr FSOpen (ConstStr255Param fileName, short vRefNum, short *refNum) { - OSErr err; - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioNamePtr = (StringPtr)fileName; - pb.ioParam.ioVRefNum = vRefNum; + OSErr err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioNamePtr = (StringPtr)fileName; + pb.ioParam.ioVRefNum = vRefNum; - // Try newer OpenDF first, because it does not open drivers - err = PBOpenDFSync(&pb); - if (err == paramErr) { - // OpenDF not implemented, so use regular Open. - err = PBOpenSync(&pb); - } + // Try newer OpenDF first, because it does not open drivers + err = PBOpenDFSync(&pb); + if (err == paramErr) { + // OpenDF not implemented, so use regular Open. + err = PBOpenSync(&pb); + } - *refNum = pb.ioParam.ioRefNum; - return err; + *refNum = pb.ioParam.ioRefNum; + return err; } pascal OSErr OpenDF (ConstStr255Param fileName, short vRefNum, short *refNum) { - return FSOpen(fileName, vRefNum, refNum); + return FSOpen(fileName, vRefNum, refNum); } pascal OSErr FSClose (short refNum) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - return PBCloseSync(&pb); + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + return PBCloseSync(&pb); } pascal OSErr FSRead (short refNum, long *count, void *buffPtr) { - OSErr err; - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - pb.ioParam.ioBuffer = buffPtr; - pb.ioParam.ioReqCount = *count; + OSErr err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + pb.ioParam.ioBuffer = buffPtr; + pb.ioParam.ioReqCount = *count; - err = PBReadSync(&pb); - *count = pb.ioParam.ioActCount; - return err; + err = PBReadSync(&pb); + *count = pb.ioParam.ioActCount; + return err; } pascal OSErr FSWrite (short refNum, long *count, const void *buffPtr) { - OSErr err; - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - pb.ioParam.ioBuffer = (void *)buffPtr; - pb.ioParam.ioReqCount = *count; + OSErr err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + pb.ioParam.ioBuffer = (void *)buffPtr; + pb.ioParam.ioReqCount = *count; - err = PBWriteSync(&pb); - *count = pb.ioParam.ioActCount; - return err; + err = PBWriteSync(&pb); + *count = pb.ioParam.ioActCount; + return err; } pascal OSErr GetEOF (short refNum, long *logEOF) { - OSErr err; - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - err = PBGetEOFSync(&pb); - *logEOF = (long)pb.ioParam.ioMisc; - return err; + OSErr err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + err = PBGetEOFSync(&pb); + *logEOF = (long)pb.ioParam.ioMisc; + return err; } pascal OSErr SetEOF (short refNum, long logEOF) { - OSErr err; - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - pb.ioParam.ioMisc = (Ptr)logEOF; - return PBGetEOFSync(&pb); + OSErr err; + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + pb.ioParam.ioMisc = (Ptr)logEOF; + return PBGetEOFSync(&pb); } pascal OSErr GetFPos (short refNum, long *filePos) { - OSErr err; - ParamBlockRec pb; - pb.ioParam.ioRefNum = refNum; - err = PBGetFPosSync(&pb); - *filePos = pb.ioParam.ioPosOffset; - return err; + OSErr err; + ParamBlockRec pb; + pb.ioParam.ioRefNum = refNum; + err = PBGetFPosSync(&pb); + *filePos = pb.ioParam.ioPosOffset; + return err; } pascal OSErr SetFPos (short refNum, short posMode, long posOff) { - ParamBlockRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioRefNum = refNum; - pb.ioParam.ioPosMode = posMode; - pb.ioParam.ioPosOffset = posOff; - return PBSetFPosSync(&pb); + ParamBlockRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioParam.ioRefNum = refNum; + pb.ioParam.ioPosMode = posMode; + pb.ioParam.ioPosOffset = posOff; + return PBSetFPosSync(&pb); } pascal OSErr Create (ConstStr255Param fileName, short vRefNum, OSType creator, - OSType fileType) + OSType fileType) { - ParamBlockRec pb; - OSErr err; - memset(&pb, 0, sizeof(pb)); - pb.fileParam.ioVRefNum = vRefNum; - pb.fileParam.ioNamePtr = (StringPtr)fileName; - // create the file - err = PBCreateSync(&pb); - if (err != noErr) return err; - // get previous finder info - err = PBGetFInfoSync(&pb); - if (err != noErr) return err; - // clear directory index - pb.fileParam.ioFDirIndex = 0; - // copy finder info words - pb.fileParam.ioFlFndrInfo.fdType = fileType; - pb.fileParam.ioFlFndrInfo.fdCreator = creator; - // save finder info - return PBSetFInfoSync(&pb); + ParamBlockRec pb; + OSErr err; + memset(&pb, 0, sizeof(pb)); + pb.fileParam.ioVRefNum = vRefNum; + pb.fileParam.ioNamePtr = (StringPtr)fileName; + // create the file + err = PBCreateSync(&pb); + if (err != noErr) return err; + // get previous finder info + err = PBGetFInfoSync(&pb); + if (err != noErr) return err; + // clear directory index + pb.fileParam.ioFDirIndex = 0; + // copy finder info words + pb.fileParam.ioFlFndrInfo.fdType = fileType; + pb.fileParam.ioFlFndrInfo.fdCreator = creator; + // save finder info + return PBSetFInfoSync(&pb); } pascal OSErr GetWDInfo(short wdRefNum, short *vRefNum, long *dirID, - long *procID) + long *procID) { - OSErr err; - WDPBRec pb; - memset(&pb, 0, sizeof(pb)); - pb.ioVRefNum = wdRefNum; - err = PBGetWDInfo(&pb, false); - *vRefNum = pb.ioWDVRefNum; - *dirID = pb.ioWDDirID; - *procID = pb.ioWDProcID; - return err; + OSErr err; + WDPBRec pb; + memset(&pb, 0, sizeof(pb)); + pb.ioVRefNum = wdRefNum; + err = PBGetWDInfo(&pb, false); + *vRefNum = pb.ioWDVRefNum; + *dirID = pb.ioWDDirID; + *procID = pb.ioWDProcID; + return err; } EXTERN_API( OSErr ) @@ -397,14 +397,14 @@ GetFInfo( short vRefNum, FInfo * fndrInfo) { - ParamBlockRec pb; - OSErr err; - memset(&pb, 0, sizeof(pb)); - pb.fileParam.ioVRefNum = vRefNum; - pb.fileParam.ioNamePtr = (StringPtr)fileName; - err = PBGetFInfoSync(&pb); - *fndrInfo = pb.fileParam.ioFlFndrInfo; - return err; + ParamBlockRec pb; + OSErr err; + memset(&pb, 0, sizeof(pb)); + pb.fileParam.ioVRefNum = vRefNum; + pb.fileParam.ioNamePtr = (StringPtr)fileName; + err = PBGetFInfoSync(&pb); + *fndrInfo = pb.fileParam.ioFlFndrInfo; + return err; } EXTERN_API( OSErr ) @@ -413,12 +413,12 @@ HDelete( long dirID, ConstStr255Param fileName) { - HParamBlockRec pb; - pb.fileParam.ioVRefNum = vRefNum; - pb.fileParam.ioNamePtr = (StringPtr)fileName; - pb.fileParam.ioDirID = dirID; - pb.fileParam.ioFVersNum = 0; // ??? - return PBHDeleteSync(&pb); + HParamBlockRec pb; + pb.fileParam.ioVRefNum = vRefNum; + pb.fileParam.ioNamePtr = (StringPtr)fileName; + pb.fileParam.ioDirID = dirID; + pb.fileParam.ioFVersNum = 0; // ??? + return PBHDeleteSync(&pb); } EXTERN_API( OSErr ) @@ -428,16 +428,16 @@ HGetFInfo( ConstStr255Param fileName, FInfo * fndrInfo) { - HParamBlockRec pb; - OSErr err; - pb.fileParam.ioVRefNum = vRefNum; - pb.fileParam.ioNamePtr = (StringPtr)fileName; - pb.fileParam.ioFVersNum = 0; // ??? - pb.fileParam.ioFDirIndex = 0; - pb.fileParam.ioDirID = dirID; - err = PBHGetFInfoSync(&pb); - *fndrInfo = pb.fileParam.ioFlFndrInfo; - return err; + HParamBlockRec pb; + OSErr err; + pb.fileParam.ioVRefNum = vRefNum; + pb.fileParam.ioNamePtr = (StringPtr)fileName; + pb.fileParam.ioFVersNum = 0; // ??? + pb.fileParam.ioFDirIndex = 0; + pb.fileParam.ioDirID = dirID; + err = PBHGetFInfoSync(&pb); + *fndrInfo = pb.fileParam.ioFlFndrInfo; + return err; } EXTERN_API( OSErr ) @@ -447,31 +447,31 @@ HSetFInfo( ConstStr255Param fileName, const FInfo * fndrInfo) { - HParamBlockRec pb; - OSErr err; - pb.fileParam.ioVRefNum = vRefNum; - pb.fileParam.ioNamePtr = (StringPtr)fileName; - pb.fileParam.ioFVersNum = 0; // ??? - pb.fileParam.ioFDirIndex = 0; - pb.fileParam.ioDirID = dirID; - pb.fileParam.ioFlFndrInfo = *fndrInfo; - return PBHSetFInfoSync(&pb); + HParamBlockRec pb; + OSErr err; + pb.fileParam.ioVRefNum = vRefNum; + pb.fileParam.ioNamePtr = (StringPtr)fileName; + pb.fileParam.ioFVersNum = 0; // ??? + pb.fileParam.ioFDirIndex = 0; + pb.fileParam.ioDirID = dirID; + pb.fileParam.ioFlFndrInfo = *fndrInfo; + return PBHSetFInfoSync(&pb); } pascal OSErr OpenDriver(ConstStr255Param name, short *drvrRefNum) { - ParamBlockRec pb; - OSErr err; - memset(&pb, 0, sizeof(pb)); + ParamBlockRec pb; + OSErr err; + memset(&pb, 0, sizeof(pb)); - pb.ioParam.ioNamePtr = (StringPtr)name; + pb.ioParam.ioNamePtr = (StringPtr)name; - err = PBOpenSync(&pb); - *drvrRefNum = pb.ioParam.ioRefNum; - return err; + err = PBOpenSync(&pb); + *drvrRefNum = pb.ioParam.ioRefNum; + return err; } pascal OSErr CloseDriver(short refNum) { - return FSClose(refNum); + return FSClose(refNum); } diff --git a/libretro/malloc.c b/libretro/malloc.c index e49141b294..f44da9886c 100644 --- a/libretro/malloc.c +++ b/libretro/malloc.c @@ -1,26 +1,26 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -33,104 +33,104 @@ void referenceMyMalloc() {} void *_malloc_r(struct _reent *reent_ptr, size_t sz) { - Ptr p = NewPtr(sz); + Ptr p = NewPtr(sz); - if(!p) - reent_ptr->_errno = ENOMEM; + if(!p) + reent_ptr->_errno = ENOMEM; - return p; + return p; } void *_calloc_r(struct _reent *reent_ptr, size_t sz, size_t sz2) { - Ptr p = NewPtrClear(sz*sz2); + Ptr p = NewPtrClear(sz*sz2); - if(!p) - reent_ptr->_errno = ENOMEM; + if(!p) + reent_ptr->_errno = ENOMEM; - return p; + return p; } void _free_r(struct _reent *reent_ptr, void *ptr) { - if(ptr != NULL) - DisposePtr(ptr); + if(ptr != NULL) + DisposePtr(ptr); } void *_realloc_r(struct _reent *reent_ptr, void *ptr, size_t sz) { - if(ptr == NULL) - { - Ptr p = NewPtr(sz); + if(ptr == NULL) + { + Ptr p = NewPtr(sz); - if(!p) - reent_ptr->_errno = ENOMEM; + if(!p) + reent_ptr->_errno = ENOMEM; - return p; - } - else - { - MemError(); - SetPtrSize(ptr, sz); - if(MemError()) - { - size_t oldSz = GetPtrSize(ptr); - if(sz > oldSz) - { - void *newPtr = NewPtr(sz); - if(!newPtr) - { - reent_ptr->_errno = ENOMEM; - return NULL; - } - memcpy(newPtr, ptr, oldSz); - return newPtr; - } - else - { - reent_ptr->_errno = ENOMEM; - return NULL; - } - } - else - return ptr; - } + return p; + } + else + { + MemError(); + SetPtrSize(ptr, sz); + if(MemError()) + { + size_t oldSz = GetPtrSize(ptr); + if(sz > oldSz) + { + void *newPtr = NewPtr(sz); + if(!newPtr) + { + reent_ptr->_errno = ENOMEM; + return NULL; + } + memcpy(newPtr, ptr, oldSz); + return newPtr; + } + else + { + reent_ptr->_errno = ENOMEM; + return NULL; + } + } + else + return ptr; + } } void *malloc(size_t sz) { - return _malloc_r(_REENT, sz); + return _malloc_r(_REENT, sz); } void free(void *p) { - _free_r(_REENT, p); + _free_r(_REENT, p); } void *realloc(void *ptr, size_t sz) { - return _realloc_r(_REENT, ptr, sz); + return _realloc_r(_REENT, ptr, sz); } void *calloc(size_t sz1, size_t sz2) { - return _calloc_r(_REENT, sz1, sz2); + return _calloc_r(_REENT, sz1, sz2); } void *memalign(size_t alignment, size_t sz) { - Ptr p = NewPtr(sz); + Ptr p = NewPtr(sz); - if(!p) - errno = ENOMEM; + if(!p) + errno = ENOMEM; - // FIXME: - // NewPtr aligns to 4 bytes on 68020 and 68030, - // and to 16 bytes on 68040 and PowerPC. + // FIXME: + // NewPtr aligns to 4 bytes on 68020 and 68030, + // and to 16 bytes on 68040 and PowerPC. - // Do something else when more alignment is required. - // This might be hard, as adding extra overhead to all normal allocations - // just so that we can distinguish things in free() doesn't sound like it's worth it. + // Do something else when more alignment is required. + // This might be hard, as adding extra overhead to all normal allocations + // just so that we can distinguish things in free() doesn't sound like it's worth it. - return p; + return p; } diff --git a/libretro/ppcstart.c b/libretro/ppcstart.c index 132e20f7d9..cc72fda7cd 100644 --- a/libretro/ppcstart.c +++ b/libretro/ppcstart.c @@ -1,26 +1,26 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -32,14 +32,14 @@ void __do_global_dtors(); void __start() { - int result; + int result; - atexit(&__do_global_dtors); - { - char *argv[2] = { "./a.out", NULL }; - result = main(1, argv); - } - exit(result); + atexit(&__do_global_dtors); + { + char *argv[2] = { "./a.out", NULL }; + result = main(1, argv); + } + exit(result); } void *__dso_handle = &__dso_handle; diff --git a/libretro/relocate.c b/libretro/relocate.c index c2b6dc0689..6ec38c9e5e 100644 --- a/libretro/relocate.c +++ b/libretro/relocate.c @@ -1,26 +1,26 @@ /* - Copyright 2017 Wolfgang Thaller. + Copyright 2017 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -42,8 +42,8 @@ typedef void (*voidFunction)(void); Linker-defined addresses in the binary; */ - // absolute address 0x1 for multiseg applications, - // absolute address NULL (or undefined) for code resources + // absolute address 0x1 for multiseg applications, + // absolute address NULL (or undefined) for code resources extern uint8_t _MULTISEG_APP __attribute__ ((weak)); // section boundaries @@ -61,177 +61,177 @@ extern uint8_t __EH_FRAME_BEGIN__; Retro68RelocState relocState __attribute__ ((section(".relocvars"))) = { - NULL, NULL, false, false + NULL, NULL, false, false }; #define GET_VIRTUAL_ADDRESS(NAME, SYM) \ - do { \ - __asm__( "\tlea " #SYM ", %0\n" \ - : "=a"(NAME) ); \ - if(hasStripAddr) \ - NAME = StripAddress(NAME); \ - else \ - NAME = StripAddress24(NAME); \ - } while(0) + do { \ + __asm__( "\tlea " #SYM ", %0\n" \ + : "=a"(NAME) ); \ + if(hasStripAddr) \ + NAME = StripAddress(NAME); \ + else \ + NAME = StripAddress24(NAME); \ + } while(0) -#define READ_UNALIGNED_LONGWORD(ptr) \ - (((((((ptr)[0] << 8) | (ptr)[1]) << 8) | (ptr)[2]) << 8) | (ptr)[3]) -#define WRITE_UNALIGNED_LONGWORD(ptr, val) \ - do { \ - uint32_t _a = (val); \ - uint8_t *_ptr = (ptr); \ - _ptr[3] = _a; \ - _ptr[2] = (_a >>= 8); \ - _ptr[1] = (_a >>= 8); \ - _ptr[0] = (_a >>= 8); \ - } while(0) +#define READ_UNALIGNED_LONGWORD(ptr) \ + (((((((ptr)[0] << 8) | (ptr)[1]) << 8) | (ptr)[2]) << 8) | (ptr)[3]) +#define WRITE_UNALIGNED_LONGWORD(ptr, val) \ + do { \ + uint32_t _a = (val); \ + uint8_t *_ptr = (ptr); \ + _ptr[3] = _a; \ + _ptr[2] = (_a >>= 8); \ + _ptr[1] = (_a >>= 8); \ + _ptr[0] = (_a >>= 8); \ + } while(0) #if 0 void Retro68ApplyRelocations(uint8_t *base, uint32_t size, void *relocations, uint32_t displacements[]) { - uint32_t *reloc = (uint32_t*) relocations; - // Process relocation records - for(;*reloc != -1;++reloc) - { - uint32_t r = *reloc; - uint8_t *addrPtr = base + (r & 0xFFFFFF); - uint8_t *addr; - uint8_t kind = r >> 24; + uint32_t *reloc = (uint32_t*) relocations; + // Process relocation records + for(;*reloc != -1;++reloc) + { + uint32_t r = *reloc; + uint8_t *addrPtr = base + (r & 0xFFFFFF); + uint8_t *addr; + uint8_t kind = r >> 24; - assert(addrPtr >= base); - assert(addrPtr < base + size); + assert(addrPtr >= base); + assert(addrPtr < base + size); - addr = (uint8_t*) READ_UNALIGNED_LONGWORD(addrPtr); - addr += displacements[kind]; - WRITE_UNALIGNED_LONGWORD(addrPtr, (uint32_t) addr); - } + addr = (uint8_t*) READ_UNALIGNED_LONGWORD(addrPtr); + addr += displacements[kind]; + WRITE_UNALIGNED_LONGWORD(addrPtr, (uint32_t) addr); + } } #else void Retro68ApplyRelocations(uint8_t *base, uint32_t size, void *relocations, uint32_t displacements[]) { - uint8_t *reloc = (uint8_t*) relocations; - uint8_t *addrPtr = base - 1; - while(*reloc) - { - // read an uleb128 value - uint32_t val = 0; - uint8_t b; - int i = 0; - do - { - b = *reloc++; - val |= (b & 0x7F) << i; - i += 7; - } while(b & 0x80); + uint8_t *reloc = (uint8_t*) relocations; + uint8_t *addrPtr = base - 1; + while(*reloc) + { + // read an uleb128 value + uint32_t val = 0; + uint8_t b; + int i = 0; + do + { + b = *reloc++; + val |= (b & 0x7F) << i; + i += 7; + } while(b & 0x80); - // ... which consists of an offset and the displacement base index - // the offset is relative to the previous relocation, or to base-1 - addrPtr += val >> 2; - uint8_t kind = val & 0x3; + // ... which consists of an offset and the displacement base index + // the offset is relative to the previous relocation, or to base-1 + addrPtr += val >> 2; + uint8_t kind = val & 0x3; - assert(addrPtr >= base); - assert(addrPtr <= base + size - 4); + assert(addrPtr >= base); + assert(addrPtr <= base + size - 4); - uint8_t *addr = (uint8_t*) READ_UNALIGNED_LONGWORD(addrPtr); - addr += displacements[kind]; - WRITE_UNALIGNED_LONGWORD(addrPtr, (uint32_t) addr); - } + uint8_t *addr = (uint8_t*) READ_UNALIGNED_LONGWORD(addrPtr); + addr += displacements[kind]; + WRITE_UNALIGNED_LONGWORD(addrPtr, (uint32_t) addr); + } } #endif void Retro68Relocate() { - // memory address to retrieve the ROM type (64K or a later ROM) - // see for details http://www.mac.linux-m68k.org/devel/macalmanac.php - short* ROM85 = (short*) 0x028E; - - // figure out which trap is supported - Boolean is128KROM = ((*ROM85) > 0); - Boolean hasSysEnvirons = false; - Boolean hasStripAddr = false; - Boolean hasFlushCodeCache = false; - if (is128KROM) - { - UniversalProcPtr trapSysEnv = GetOSTrapAddress(_SysEnvirons); - UniversalProcPtr trapStripAddr = GetOSTrapAddress(_StripAddress); - UniversalProcPtr trapFlushCodeCache = GetOSTrapAddress(0xA0BD); - UniversalProcPtr trapUnimpl = GetOSTrapAddress(_Unimplemented); + // memory address to retrieve the ROM type (64K or a later ROM) + // see for details http://www.mac.linux-m68k.org/devel/macalmanac.php + short* ROM85 = (short*) 0x028E; + + // figure out which trap is supported + Boolean is128KROM = ((*ROM85) > 0); + Boolean hasSysEnvirons = false; + Boolean hasStripAddr = false; + Boolean hasFlushCodeCache = false; + if (is128KROM) + { + UniversalProcPtr trapSysEnv = GetOSTrapAddress(_SysEnvirons); + UniversalProcPtr trapStripAddr = GetOSTrapAddress(_StripAddress); + UniversalProcPtr trapFlushCodeCache = GetOSTrapAddress(0xA0BD); + UniversalProcPtr trapUnimpl = GetOSTrapAddress(_Unimplemented); - hasSysEnvirons = (trapSysEnv != trapUnimpl); - hasStripAddr = (trapStripAddr != trapUnimpl); - hasFlushCodeCache = (trapFlushCodeCache != trapUnimpl); - } - - // Figure out the displacement - // what is the difference between the addresses in our program code - // and an address calculated by PC-relative access? - long displacement; - - if (hasStripAddr) - { - RETRO68_GET_DISPLACEMENT_STRIP(displacement); - } - else - { - RETRO68_GET_DISPLACEMENT_STRIP24(displacement); - } + hasSysEnvirons = (trapSysEnv != trapUnimpl); + hasStripAddr = (trapStripAddr != trapUnimpl); + hasFlushCodeCache = (trapFlushCodeCache != trapUnimpl); + } + + // Figure out the displacement + // what is the difference between the addresses in our program code + // and an address calculated by PC-relative access? + long displacement; + + if (hasStripAddr) + { + RETRO68_GET_DISPLACEMENT_STRIP(displacement); + } + else + { + RETRO68_GET_DISPLACEMENT_STRIP24(displacement); + } - struct Retro68RelocState *rState = (Retro68RelocState*) - ((char*)&relocState + displacement); - // rState now points to the global relocState variable - // - if(displacement == 0) - { - if(rState->bssPtr) - { - // this is not the first time, no relocations needed. - // should only happen for code resources - // that are invoked more than once. + struct Retro68RelocState *rState = (Retro68RelocState*) + ((char*)&relocState + displacement); + // rState now points to the global relocState variable + // + if(displacement == 0) + { + if(rState->bssPtr) + { + // this is not the first time, no relocations needed. + // should only happen for code resources + // that are invoked more than once. - // Lock the code to be sure. - if(rState->codeHandle) - HLock(rState->codeHandle); - return; - } - } + // Lock the code to be sure. + if(rState->codeHandle) + HLock(rState->codeHandle); + return; + } + } - rState->hasStripAddr = hasStripAddr; - rState->hasFlushCodeCache = hasFlushCodeCache; + rState->hasStripAddr = hasStripAddr; + rState->hasFlushCodeCache = hasFlushCodeCache; - // Locate the start of the FLT file header inside the code resource - uint8_t *orig_stext, *orig_etext, *orig_sdata, *orig_edata, *orig_sbss, *orig_ebss; - - GET_VIRTUAL_ADDRESS(orig_stext, _stext); - GET_VIRTUAL_ADDRESS(orig_etext, _etext); - GET_VIRTUAL_ADDRESS(orig_sdata, _sdata); - GET_VIRTUAL_ADDRESS(orig_edata, _edata); - GET_VIRTUAL_ADDRESS(orig_sbss, _sbss); - GET_VIRTUAL_ADDRESS(orig_ebss, _ebss); - - log(orig_stext); - log(orig_etext); - log(orig_sdata); - log(orig_edata); - log(orig_sbss); - log(orig_ebss); - - uint8_t *base = orig_stext + displacement; + // Locate the start of the FLT file header inside the code resource + uint8_t *orig_stext, *orig_etext, *orig_sdata, *orig_edata, *orig_sbss, *orig_ebss; + + GET_VIRTUAL_ADDRESS(orig_stext, _stext); + GET_VIRTUAL_ADDRESS(orig_etext, _etext); + GET_VIRTUAL_ADDRESS(orig_sdata, _sdata); + GET_VIRTUAL_ADDRESS(orig_edata, _edata); + GET_VIRTUAL_ADDRESS(orig_sbss, _sbss); + GET_VIRTUAL_ADDRESS(orig_ebss, _ebss); + + log(orig_stext); + log(orig_etext); + log(orig_sdata); + log(orig_edata); + log(orig_sbss); + log(orig_ebss); + + uint8_t *base = orig_stext + displacement; - long bss_displacement = 0; - long data_displacement = 0; - long jt_displacement = 0; - - if(&_MULTISEG_APP) - { - uint8_t * a5 = (uint8_t*) SetCurrentA5(); - bss_displacement = a5 - orig_ebss; - data_displacement = a5 - orig_ebss; - jt_displacement = a5 - (uint8_t*)NULL; - } - else - { - data_displacement = displacement; + long bss_displacement = 0; + long data_displacement = 0; + long jt_displacement = 0; + + if(&_MULTISEG_APP) + { + uint8_t * a5 = (uint8_t*) SetCurrentA5(); + bss_displacement = a5 - orig_ebss; + data_displacement = a5 - orig_ebss; + jt_displacement = a5 - (uint8_t*)NULL; + } + else + { + data_displacement = displacement; #if 0 // find the beginning of the current code resource and lock it. // this crashes with some implementations of the memory manager @@ -242,149 +242,149 @@ void Retro68Relocate() // TODO: figure out a way to reliably determine the offset from the // start of the resource (to pass it from Elf2Mac, probably). - { - uint8_t *orig_rsrc_start; - GET_VIRTUAL_ADDRESS(orig_rsrc_start, _rsrc_start); - uint8_t *rsrc_start = orig_rsrc_start + displacement; - - Handle h = RecoverHandle((Ptr) rsrc_start); - if(MemError() == noErr && h) - { - // Make sure the code is locked. Only relevant for some code resources. - HLock(h); - rState->codeHandle = h; - } - } -#endif - // Allocate BSS section (uninitialized/zero-initialized global data) - if(!rState->bssPtr) - { - uint32_t bss_size = orig_ebss - orig_sbss; - THz zone = ApplicationZone(); - if(!zone || base < (uint8_t*)zone) - rState->bssPtr = NewPtrSysClear(bss_size); - else - rState->bssPtr = NewPtrClear(bss_size); - bss_displacement = (uint8_t*)rState->bssPtr - orig_sbss; - } - } - - /* - Relocation records consist of 4 bytes each. - The lower three bytes are the offset of the longword being relocated. - the first byte of each longword specifies which segment - the relocation leads to; the corresponding displacements are taken - from the following table: - */ - long displacements[4] = { - displacement, // code - data_displacement, - bss_displacement, - jt_displacement - }; - - void *reloc; - Handle RELA = NULL; - uint32_t relocatableSize; - if(&_MULTISEG_APP == (uint8_t*)1) - { - RELA = Get1Resource('RELA', 1); - assert(RELA); - reloc = *RELA; - uint32_t text_size = orig_etext - orig_stext; - relocatableSize = text_size; - } - else - { - uint32_t text_and_data_size = orig_edata - orig_stext; - reloc = base + text_and_data_size; - relocatableSize = text_and_data_size; - } - - typedef typeof(&Retro68ApplyRelocations) ApplyRelocationsPtr; - ApplyRelocationsPtr RealApplyRelocations; - RealApplyRelocations = (ApplyRelocationsPtr) ((uint8_t*)&Retro68ApplyRelocations + displacement); - RealApplyRelocations(base, relocatableSize, reloc, displacements); + { + uint8_t *orig_rsrc_start; + GET_VIRTUAL_ADDRESS(orig_rsrc_start, _rsrc_start); + uint8_t *rsrc_start = orig_rsrc_start + displacement; + + Handle h = RecoverHandle((Ptr) rsrc_start); + if(MemError() == noErr && h) + { + // Make sure the code is locked. Only relevant for some code resources. + HLock(h); + rState->codeHandle = h; + } + } +#endif + // Allocate BSS section (uninitialized/zero-initialized global data) + if(!rState->bssPtr) + { + uint32_t bss_size = orig_ebss - orig_sbss; + THz zone = ApplicationZone(); + if(!zone || base < (uint8_t*)zone) + rState->bssPtr = NewPtrSysClear(bss_size); + else + rState->bssPtr = NewPtrClear(bss_size); + bss_displacement = (uint8_t*)rState->bssPtr - orig_sbss; + } + } + + /* + Relocation records consist of 4 bytes each. + The lower three bytes are the offset of the longword being relocated. + the first byte of each longword specifies which segment + the relocation leads to; the corresponding displacements are taken + from the following table: + */ + long displacements[4] = { + displacement, // code + data_displacement, + bss_displacement, + jt_displacement + }; + + void *reloc; + Handle RELA = NULL; + uint32_t relocatableSize; + if(&_MULTISEG_APP == (uint8_t*)1) + { + RELA = Get1Resource('RELA', 1); + assert(RELA); + reloc = *RELA; + uint32_t text_size = orig_etext - orig_stext; + relocatableSize = text_size; + } + else + { + uint32_t text_and_data_size = orig_edata - orig_stext; + reloc = base + text_and_data_size; + relocatableSize = text_and_data_size; + } + + typedef typeof(&Retro68ApplyRelocations) ApplyRelocationsPtr; + ApplyRelocationsPtr RealApplyRelocations; + RealApplyRelocations = (ApplyRelocationsPtr) ((uint8_t*)&Retro68ApplyRelocations + displacement); + RealApplyRelocations(base, relocatableSize, reloc, displacements); - // We're basically done. - /*// Now check whether we're on 68040 or later and need to flush the cache. - // only do this if SysEnvirons is available. - // if SysEnvirons is not available, that means we're on an old System or ROM - // and likely not using a 68040, so we won't do this - if (hasSysEnvirons) - { - SysEnvRec env; + // We're basically done. + /*// Now check whether we're on 68040 or later and need to flush the cache. + // only do this if SysEnvirons is available. + // if SysEnvirons is not available, that means we're on an old System or ROM + // and likely not using a 68040, so we won't do this + if (hasSysEnvirons) + { + SysEnvRec env; - env.processor = 0; - SysEnvirons(0, &env); - if(env.processor >= env68040) - { + env.processor = 0; + SysEnvirons(0, &env); + if(env.processor >= env68040) + { rState->needFlushCache = true; - FlushCodeCache(); - } - }*/ - if(hasFlushCodeCache) - FlushCodeCache(); + FlushCodeCache(); + } + }*/ + if(hasFlushCodeCache) + FlushCodeCache(); - // accessing globals and calling functions is OK below here. - // ... as long as it is in the current segment. + // accessing globals and calling functions is OK below here. + // ... as long as it is in the current segment. - Retro68InitMultisegApp(); - - // Now we're set. - // Someone still needs to invoke Retro68CallConstructors - // ... but that's the job of _start(). + Retro68InitMultisegApp(); + + // Now we're set. + // Someone still needs to invoke Retro68CallConstructors + // ... but that's the job of _start(). } void Retro68CallConstructors() { - static struct object object; - if (__register_frame_info) - __register_frame_info(&__EH_FRAME_BEGIN__, &object); - { - uint8_t *p = &__init_section; - uint8_t *e = &__init_section_end; - p += 2; - while( p < e ) - { - (*(voidFunction)(*(long*)p))(); - p += 6; - } - } - { - voidFunction *p, f; - for(p = &__CTOR_LIST__; (f = *p); p++) - f(); - } + static struct object object; + if (__register_frame_info) + __register_frame_info(&__EH_FRAME_BEGIN__, &object); + { + uint8_t *p = &__init_section; + uint8_t *e = &__init_section_end; + p += 2; + while( p < e ) + { + (*(voidFunction)(*(long*)p))(); + p += 6; + } + } + { + voidFunction *p, f; + for(p = &__CTOR_LIST__; (f = *p); p++) + f(); + } } void Retro68CallDestructors() { - { - voidFunction *p, f; - for(p = &__DTOR_LIST__; (f = *p); p++) - f(); - } - { - uint8_t *p = &__fini_section; - uint8_t *e = &__fini_section_end; - p += 2; - while( p < e ) - { - (*(voidFunction)(*(long*)p))(); - p += 6; - } - } - if (__deregister_frame_info) - __deregister_frame_info(&__EH_FRAME_BEGIN__); + { + voidFunction *p, f; + for(p = &__DTOR_LIST__; (f = *p); p++) + f(); + } + { + uint8_t *p = &__fini_section; + uint8_t *e = &__fini_section_end; + p += 2; + while( p < e ) + { + (*(voidFunction)(*(long*)p))(); + p += 6; + } + } + if (__deregister_frame_info) + __deregister_frame_info(&__EH_FRAME_BEGIN__); } void Retro68FreeGlobals() { - if(relocState.bssPtr != (Ptr) -1) - { - DisposePtr(relocState.bssPtr); - relocState.bssPtr = (Ptr) -1; - } + if(relocState.bssPtr != (Ptr) -1) + { + DisposePtr(relocState.bssPtr); + relocState.bssPtr = (Ptr) -1; + } } diff --git a/libretro/start.c b/libretro/start.c index 0162009cdc..68e75663dd 100644 --- a/libretro/start.c +++ b/libretro/start.c @@ -1,26 +1,26 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -30,14 +30,14 @@ int main(int argc, char* argv[]); void _start() { - RETRO68_RELOCATE(); - atexit(&Retro68CallDestructors); - Retro68CallConstructors(); + RETRO68_RELOCATE(); + atexit(&Retro68CallDestructors); + Retro68CallConstructors(); - int result; - { - char *argv[2] = { "./a.out", NULL }; - result = main(1, argv); - } - exit(result); + int result; + { + char *argv[2] = { "./a.out", NULL }; + result = main(1, argv); + } + exit(result); } diff --git a/libretro/syscalls.c b/libretro/syscalls.c index 0435ff6db4..96958559e1 100644 --- a/libretro/syscalls.c +++ b/libretro/syscalls.c @@ -1,26 +1,26 @@ /* - Copyright 2015 Wolfgang Thaller. + Copyright 2015 Wolfgang Thaller. - This file is part of Retro68. + This file is part of Retro68. - Retro68 is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. + Retro68 is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. - Retro68 is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + Retro68 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - Under Section 7 of GPL version 3, you are granted additional - permissions described in the GCC Runtime Library Exception, version - 3.1, as published by the Free Software Foundation. + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. - You should have received a copy of the GNU General Public License and - a copy of the GCC Runtime Library Exception along with this program; - see the files COPYING and COPYING.RUNTIME respectively. If not, see - . + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING and COPYING.RUNTIME respectively. If not, see + . */ #include @@ -41,17 +41,17 @@ void *_sbrk_r(struct _reent *reent, ptrdiff_t increment) { - Debugger(); - return NewPtrClear(increment); + Debugger(); + return NewPtrClear(increment); } void _exit(int status) { - //if(status != 0) - // Debugger(); - ExitToShell(); - for(;;) - ; + //if(status != 0) + // Debugger(); + ExitToShell(); + for(;;) + ; } ssize_t _consolewrite(int fd, const void *buf, size_t count); @@ -61,224 +61,224 @@ const int kMacRefNumOffset = 10; ssize_t _write_r(struct _reent *reent, int fd, const void *buf, size_t count) { - long cnt = count; - if(fd >= kMacRefNumOffset) - { - FSWrite(fd - kMacRefNumOffset, &cnt, buf); - return cnt; - } - else - return _consolewrite(fd,buf,count); + long cnt = count; + if(fd >= kMacRefNumOffset) + { + FSWrite(fd - kMacRefNumOffset, &cnt, buf); + return cnt; + } + else + return _consolewrite(fd,buf,count); } ssize_t _read_r(struct _reent *reent, int fd, void *buf, size_t count) { - long cnt = count; - if(fd >= kMacRefNumOffset) - { - FSRead(fd - kMacRefNumOffset, &cnt, buf); - return cnt; - } - else - return _consoleread(fd,buf,count); + long cnt = count; + if(fd >= kMacRefNumOffset) + { + FSRead(fd - kMacRefNumOffset, &cnt, buf); + return cnt; + } + else + return _consoleread(fd,buf,count); } int _open_r(struct _reent *reent, const char* name, int flags, int mode) { - Str255 pname; + Str255 pname; #if TARGET_API_MAC_CARBON - // Carbon has the new, sane version. - c2pstrcpy(pname,name); + // Carbon has the new, sane version. + c2pstrcpy(pname,name); #else - // It is also availble in various glue code libraries and - // in some versions of InterfaceLib, but it's confusing. - // Using the inplace variant, c2pstr, isn't much better than - // doing things by hand: - strncpy(&pname[1],name,255); - pname[0] = strlen(name); + // It is also availble in various glue code libraries and + // in some versions of InterfaceLib, but it's confusing. + // Using the inplace variant, c2pstr, isn't much better than + // doing things by hand: + strncpy(&pname[1],name,255); + pname[0] = strlen(name); #endif - short ref; + short ref; - SInt8 permission; - switch(flags & O_ACCMODE) - { - case O_RDONLY: - permission = fsRdPerm; - break; - case O_WRONLY: - permission = fsWrPerm; - break; - case O_RDWR: - permission = fsRdWrPerm; - break; - } + SInt8 permission; + switch(flags & O_ACCMODE) + { + case O_RDONLY: + permission = fsRdPerm; + break; + case O_WRONLY: + permission = fsWrPerm; + break; + case O_RDWR: + permission = fsRdWrPerm; + break; + } - if(flags & O_CREAT) - { - HCreate(0,0,pname,'????','TEXT'); - } + if(flags & O_CREAT) + { + HCreate(0,0,pname,'????','TEXT'); + } - OSErr err = HOpenDF(0,0,pname,fsRdWrPerm,&ref); + OSErr err = HOpenDF(0,0,pname,fsRdWrPerm,&ref); if(err == paramErr) err = HOpen(0,0,pname,fsRdWrPerm,&ref); - if(err) - return -1; // TODO: errno + if(err) + return -1; // TODO: errno - if(flags & O_TRUNC) - { - SetEOF(ref, 0); - } + if(flags & O_TRUNC) + { + SetEOF(ref, 0); + } - return ref + kMacRefNumOffset; + return ref + kMacRefNumOffset; } int _close_r(struct _reent *reent, int fd) { - if(fd >= kMacRefNumOffset) - FSClose(fd - kMacRefNumOffset); - return 0; + if(fd >= kMacRefNumOffset) + FSClose(fd - kMacRefNumOffset); + return 0; } int _fstat_r(struct _reent *reent, int fd, struct stat *buf) { - return -1; + return -1; } extern int _stat_r(struct _reent * reent, const char *fn, struct stat *buf) { - return -1; + return -1; } off_t _lseek_r(struct _reent *reent, int fd, off_t offset, int whence) { - if(fd >= kMacRefNumOffset) - { - short posMode; - switch(whence) - { - case SEEK_SET: - posMode = fsFromStart; - break; - case SEEK_CUR: - posMode = fsFromMark; - break; - case SEEK_END: - posMode = fsFromLEOF; - break; - } + if(fd >= kMacRefNumOffset) + { + short posMode; + switch(whence) + { + case SEEK_SET: + posMode = fsFromStart; + break; + case SEEK_CUR: + posMode = fsFromMark; + break; + case SEEK_END: + posMode = fsFromLEOF; + break; + } - short ref = fd - kMacRefNumOffset; - SetFPos(ref, posMode, offset); - long finalPos; - GetFPos(ref, &finalPos); - return finalPos; - } - return (off_t) -1; + short ref = fd - kMacRefNumOffset; + SetFPos(ref, posMode, offset); + long finalPos; + GetFPos(ref, &finalPos); + return finalPos; + } + return (off_t) -1; } int _kill_r(struct _reent *reent, pid_t pid, int sig) { - if(pid == 42) - _exit(42); - else - return -1; + if(pid == 42) + _exit(42); + else + return -1; } pid_t _getpid_r(struct _reent *reent) { - return 42; + return 42; } int _fork_r(struct _reent *reent) { - return -1; + return -1; } int _execve_r(struct _reent *reent, const char *fn, char *const * argv, char *const *envp) { - return -1; + return -1; } int _fcntl_r(struct _reent *reent, int fd, int cmd, int arg) { - return -1; + return -1; } int _isatty_r(struct _reent *reent, int fd) { - return fd < kMacRefNumOffset; + return fd < kMacRefNumOffset; } int _link_r(struct _reent *reent, const char *from, const char *to) { - reent->_errno = EPERM; - return -1; + reent->_errno = EPERM; + return -1; } int _mkdir_r(struct _reent *reent, const char *fn, int mode) { - return -1; + return -1; } int _rename_r(struct _reent *reent, const char *from, const char *to) { - return -1; + return -1; } int _unlink_r(struct _reent *reent, const char *fn) { - return -1; + return -1; } _CLOCK_T_ _times_r(struct _reent *reent, struct tms *buf) { - reent->_errno = EACCES; - return -1; + reent->_errno = EACCES; + return -1; } int _wait_r(struct _reent *reent, int *wstatus) { - reent->_errno = ECHILD; - return -1; /* Always fails */ + reent->_errno = ECHILD; + return -1; /* Always fails */ } int _gettimeofday_r(struct _reent *reent, struct timeval *tp, void *__tz) { - /* Classic MacOS's GetDateTime function returns an integer. - * TickCount() has a slightly higher resolution, but is independend of the real-time clock. - */ - unsigned long secs; - GetDateTime(&secs); - unsigned long ticks = TickCount(); + /* Classic MacOS's GetDateTime function returns an integer. + * TickCount() has a slightly higher resolution, but is independend of the real-time clock. + */ + unsigned long secs; + GetDateTime(&secs); + unsigned long ticks = TickCount(); - static unsigned long savedTicks = 0, savedSecs = 0; - - if(!savedSecs) - { - savedTicks = ticks; - savedSecs = secs; - } - else - { - unsigned long elapsedTicks = ticks - savedTicks; - unsigned long elapsedSecs = secs - savedSecs; - unsigned long expectedTicks = elapsedSecs * 60 + elapsedSecs * 3 / 20; - - if(expectedTicks > elapsedTicks) - savedTicks = ticks; - else - savedTicks += expectedTicks; - savedSecs = secs; - } + static unsigned long savedTicks = 0, savedSecs = 0; + + if(!savedSecs) + { + savedTicks = ticks; + savedSecs = secs; + } + else + { + unsigned long elapsedTicks = ticks - savedTicks; + unsigned long elapsedSecs = secs - savedSecs; + unsigned long expectedTicks = elapsedSecs * 60 + elapsedSecs * 3 / 20; + + if(expectedTicks > elapsedTicks) + savedTicks = ticks; + else + savedTicks += expectedTicks; + savedSecs = secs; + } - if(tp) - { - tp->tv_sec = secs - 86400 * (365 * 66 + 66/4); - tp->tv_usec = (ticks - savedTicks) * 20000000 / 2003; - } + if(tp) + { + tp->tv_sec = secs - 86400 * (365 * 66 + 66/4); + tp->tv_usec = (ticks - savedTicks) * 20000000 / 2003; + } - return 0; + return 0; } diff --git a/prepare-headers.sh b/prepare-headers.sh index a39c9143b9..dd1d473852 100644 --- a/prepare-headers.sh +++ b/prepare-headers.sh @@ -5,55 +5,55 @@ OUT="$2" export LC_ALL=C for file in $(cd "$IN"; ls *.h); do - # Filter by file names. - # Some CIncludes packages include the MPW standard library. - # Header files from that standard library would overwrite - # newlib header files and stop things from working. - case $file in - # Apple/MPW standard library internals - *Def.h|FSpio.h) - USE=false - ;; + # Filter by file names. + # Some CIncludes packages include the MPW standard library. + # Header files from that standard library would overwrite + # newlib header files and stop things from working. + case $file in + # Apple/MPW standard library internals + *Def.h|FSpio.h) + USE=false + ;; - # whitelist all uppercase headers - [A-Z]*.h) - USE=true - ;; + # whitelist all uppercase headers + [A-Z]*.h) + USE=true + ;; - # whitelist OpenTransport - cred.h|dlpi.h|miioccom.h|mistream.h|modnames.h) - USE=true - ;; - # whitelist OpenTransport (continued) - strlog.h|stropts.h|strstat.h|tihdr.h) - USE=true - ;; + # whitelist OpenTransport + cred.h|dlpi.h|miioccom.h|mistream.h|modnames.h) + USE=true + ;; + # whitelist OpenTransport (continued) + strlog.h|stropts.h|strstat.h|tihdr.h) + USE=true + ;; - # Non-standard floating point headers that don't conflict - ddrt.h|fp.h) - USE=true - ;; - # newlib does not provide fenv.h, so use Apple's - fenv.h) - USE=true - ;; + # Non-standard floating point headers that don't conflict + ddrt.h|fp.h) + USE=true + ;; + # newlib does not provide fenv.h, so use Apple's + fenv.h) + USE=true + ;; - # veclib headers - v*.h) - USE=true - ;; + # veclib headers + v*.h) + USE=true + ;; - # unsupported: intrinsics.h perf.h + # unsupported: intrinsics.h perf.h - # all other (lowercase) headers: conflict with GCC or newlib headers - *) - USE=false - ;; - esac + # all other (lowercase) headers: conflict with GCC or newlib headers + *) + USE=false + ;; + esac - if [ $USE = true ]; then - sed 's/\r$//' < "$IN/$file" | tr '\r' '\n' > "$OUT/$file" - fi + if [ $USE = true ]; then + sed 's/\r$//' < "$IN/$file" | tr '\r' '\n' > "$OUT/$file" + fi done ############################# ConditionalMacros.h ############################# @@ -158,16 +158,16 @@ END_MARKER fi for f in Types.h Memory.h Windows.h Errors.h; do - if [ ! -r "$IN/$f" ]; then - echo "#include \"Mac$f\"" > "$OUT/$f" - elif [ ! -r "$IN/Mac$f" ]; then - echo "#include \"$f\"" > "$OUT/Mac$f" - fi + if [ ! -r "$IN/$f" ]; then + echo "#include \"Mac$f\"" > "$OUT/$f" + elif [ ! -r "$IN/Mac$f" ]; then + echo "#include \"$f\"" > "$OUT/Mac$f" + fi done if [ -d "$IN/CoreFoundation" ]; then - mkdir -p "$OUT/CoreFoundation" - for file in $(cd "$IN"; ls CoreFoundation/*.h); do - sed 's/\r$//' < "$IN/$file" | tr '\r' '\n' > "$OUT/$file" - done + mkdir -p "$OUT/CoreFoundation" + for file in $(cd "$IN"; ls CoreFoundation/*.h); do + sed 's/\r$//' < "$IN/$file" | tr '\r' '\n' > "$OUT/$file" + done fi diff --git a/prepare-rincludes.sh b/prepare-rincludes.sh index 30ccb30bc4..8ee6d59b2f 100644 --- a/prepare-rincludes.sh +++ b/prepare-rincludes.sh @@ -6,6 +6,6 @@ export LC_ALL=C # cp $IN/[A-Z]*.r $OUT/ for file in $(cd "$IN"; ls [A-Z]*.r); do - tr '\r' '\n' < $IN/$file > $OUT/$file + tr '\r' '\n' < $IN/$file > $OUT/$file done