?login_element?

Subversion Repositories NedoOS

Rev

Rev 556 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /*
  2.  
  3.   SjASMPlus Z80 Cross Compiler
  4.  
  5.   This is modified sources of SjASM by Aprisobal - aprisobal@tut.by
  6.  
  7.   Copyright (c) 2006 Sjoerd Mastijn
  8.  
  9.   This software is provided 'as-is', without any express or implied warranty.
  10.   In no event will the authors be held liable for any damages arising from the
  11.   use of this software.
  12.  
  13.   Permission is granted to anyone to use this software for any purpose,
  14.   including commercial applications, and to alter it and redistribute it freely,
  15.   subject to the following restrictions:
  16.  
  17.   1. The origin of this software must not be misrepresented; you must not claim
  18.          that you wrote the original software. If you use this software in a product,
  19.          an acknowledgment in the product documentation would be appreciated but is
  20.          not required.
  21.  
  22.   2. Altered source versions must be plainly marked as such, and must not be
  23.          misrepresented as being the original software.
  24.  
  25.   3. This notice may not be removed or altered from any source distribution.
  26.  
  27. */
  28.  
  29. // sjio.cpp
  30.  
  31. #include "termcolor.hpp"
  32.  
  33. #include "sjdefs.h"
  34.  
  35. #include <fcntl.h>
  36.  
  37. #define DESTBUFLEN 8192
  38.  
  39. static void CloseBreakpointsFile();
  40.  
  41. // ReadLine buffer and variables around
  42. char rlbuf[4096 * 2]; //x2 to prevent errors
  43. char * rlpbuf, * rlpbuf_end, * rlppos;
  44. bool colonSubline;
  45. int blockComment;
  46.  
  47. constexpr int LIST_EMIT_BYTES_BUFFER_SIZE = 1024 * 64;
  48. int ListEmittedBytes[LIST_EMIT_BYTES_BUFFER_SIZE], nListBytes = 0;
  49. char WriteBuffer[DESTBUFLEN];
  50. int tape_seek = 0;
  51. int tape_length = 0;
  52. int tape_parity = 0x55;
  53. FILE* FP_tapout = NULL;
  54. FILE* FP_Input = NULL, * FP_Output = NULL, * FP_RAW = NULL;
  55. FILE* FP_ListingFile = NULL,* FP_ExportFile = NULL;
  56. int ListAddress;
  57. aint WBLength = 0;
  58. bool IsSkipErrors = false;
  59.  
  60. static void initErrorLine() {           // adds filename + line of definition if possible
  61.         *ErrorLine = 0;
  62.         *ErrorLine2 = 0;
  63.         // when OpenFile is reporting error, the filename is still nullptr, but pass==1 already
  64.         if (pass < 1 || LASTPASS < pass || nullptr == CurSourcePos.filename) return;
  65.         // during assembling, show also file+line info
  66.         TextFilePos errorPos = DefinitionPos.line ? DefinitionPos : CurSourcePos;
  67.         bool isEmittedMsgEnabled = true;
  68. #ifdef USE_LUA
  69.         if (LuaStartPos.line) {
  70.                 errorPos = LuaStartPos;
  71.                 lua_Debug ar;
  72.  
  73.                 // find either top level of lua stack, or standalone file, otherwise it's impossible
  74.                 // to precisely report location of error (ASM can have 2+ LUA blocks defining functions)
  75.                 int level = 1;                  // level 0 is "C" space, ignore that always
  76.                 // suppress "is emitted here" when directly inlined in current code
  77.                 isEmittedMsgEnabled = (0 < listmacro);
  78.                 while (true) {
  79.                         if (!lua_getstack(LUA, level, &ar)) break;      // no more lua stack levels
  80.                         if (!lua_getinfo(LUA, "Sl", &ar)) break;        // no more info about current level
  81.                         if (strcmp("[string \"script\"]", ar.short_src)) {
  82.                                 // standalone definition in external file found, pinpoint it precisely
  83.                                 errorPos.filename = ar.short_src;
  84.                                 errorPos.line = ar.currentline;
  85.                                 isEmittedMsgEnabled = true;                             // and add "emitted here" in any case
  86.                                 break;  // no more lua-stack traversing, stop here
  87.                         }
  88.                         // if source was inlined script, update the possible source line
  89.                         errorPos.line = LuaStartPos.line + ar.currentline;
  90.                         // and keep traversing stack until top level is found (to make the line meaningful)
  91.                         ++level;
  92.                 }
  93.         }
  94. #endif //USE_LUA
  95.         SPRINTF2(ErrorLine, LINEMAX2, "%s(%d): ", errorPos.filename, errorPos.line);
  96.         // if the error filename:line is not identical with current source line, add ErrorLine2 about emit
  97.         if (isEmittedMsgEnabled &&
  98.                 (strcmp(errorPos.filename, CurSourcePos.filename) || errorPos.line != CurSourcePos.line)) {
  99.                 SPRINTF2(ErrorLine2, LINEMAX2, "%s(%d): ^ emitted from here\n", CurSourcePos.filename, CurSourcePos.line);
  100.         }
  101. }
  102.  
  103. static void outputErrorLine(const EOutputVerbosity errorLevel) {
  104.         // always print the message into listing file (the OutputVerbosity does not apply to listing)
  105.         if (GetListingFile()) {
  106.                 fputs(ErrorLine, GetListingFile());
  107.                 if (*ErrorLine2) fputs(ErrorLine2, GetListingFile());
  108.         }
  109.         // print the error into stderr if OutputVerbosity allows this type of message
  110.         if (Options::OutputVerbosity <= errorLevel) {
  111.                 _CERR ErrorLine _END;
  112.                 if (*ErrorLine2)  _CERR ErrorLine2 _END;
  113.         }
  114. }
  115.  
  116. void Error(const char* message, const char* badValueMessage, EStatus type) {
  117.         // check if it is correct pass by the type of error
  118.         if (type == EARLY && LASTPASS <= pass) return;
  119.         if ((type == SUPPRESS || type == IF_FIRST || type == PASS3) && pass < LASTPASS) return;
  120.         // check if this one should be skipped due to type constraints and current-error-state
  121.         if (FATAL != type && PreviousErrorLine == CompiledCurrentLine) {
  122.                 // non-fatal error, on the same line as previous, maybe skip?
  123.                 if (IsSkipErrors || IF_FIRST == type) return;
  124.         }
  125.         // update current-error-state (reset "skip" on new parsed-line, set "skip" by SUPPRESS type)
  126.         IsSkipErrors = (IsSkipErrors && (PreviousErrorLine == CompiledCurrentLine)) || (SUPPRESS == type);
  127.         PreviousErrorLine = CompiledCurrentLine;
  128.         ++ErrorCount;                                                   // number of non-skipped (!) errors
  129.  
  130.         DefineTable.Replace("__ERRORS__", ErrorCount);
  131.  
  132.         initErrorLine();
  133.         STRCAT(ErrorLine, LINEMAX2-1, "error: ");
  134. #ifdef USE_LUA
  135.         if (LuaStartPos.line) STRCAT(ErrorLine, LINEMAX2-1, "[LUA] ");
  136. #endif
  137.         STRCAT(ErrorLine, LINEMAX2-1, message);
  138.         if (badValueMessage) {
  139.                 STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage);
  140.         }
  141.         if (!strchr(ErrorLine, '\n')) STRCAT(ErrorLine, LINEMAX2-1, "\n");      // append EOL if needed
  142.         outputErrorLine(OV_ERROR);
  143.         // terminate whole assembler in case of fatal error
  144.         if (type == FATAL) {
  145.                 ExitASM(1);
  146.         }
  147. }
  148.  
  149. void ErrorInt(const char* message, aint badValue, EStatus type) {
  150.         char numBuf[24];
  151.         SPRINTF1(numBuf, 24, "%d", badValue);
  152.         Error(message, numBuf, type);
  153. }
  154.  
  155. void ErrorOOM() {               // out of memory
  156.         Error("Not enough memory!", nullptr, FATAL);
  157. }
  158.  
  159. void Warning(const char* message, const char* badValueMessage, EWStatus type)
  160. {
  161.         // check if it is correct pass by the type of error
  162.         if (type == W_EARLY && LASTPASS <= pass) return;
  163.         if (type == W_PASS3 && pass < LASTPASS) return;
  164.  
  165.         // turn the warning into error if "Warnings as errors" is switched on
  166.         if (Options::syx.WarningsAsErrors) switch (type) {
  167.                 case W_EARLY:   Error(message, badValueMessage, EARLY); return;
  168.                 case W_PASS3:   Error(message, badValueMessage, PASS3); return;
  169.                 case W_ALL:             Error(message, badValueMessage, ALL); return;
  170.         }
  171.  
  172.         ++WarningCount;
  173.  
  174.         DefineTable.Replace("__WARNINGS__", WarningCount);
  175.  
  176.         initErrorLine();
  177.         STRCAT(ErrorLine, LINEMAX2-1, "warning: ");
  178. #ifdef USE_LUA
  179.         if (LuaStartPos.line) STRCAT(ErrorLine, LINEMAX2-1, "[LUA] ");
  180. #endif
  181.         STRCAT(ErrorLine, LINEMAX2-1, message);
  182.         if (badValueMessage) {
  183.                 STRCAT(ErrorLine, LINEMAX2-1, ": "); STRCAT(ErrorLine, LINEMAX2-1, badValueMessage);
  184.         }
  185.         if (!strchr(ErrorLine, '\n')) STRCAT(ErrorLine, LINEMAX2-1, "\n");      // append EOL if needed
  186.         outputErrorLine(OV_WARNING);
  187. }
  188.  
  189. // find position of extension in filename (points at dot char or beyond filename if no extension)
  190. // filename is pointer to writeable format containing file name (can be full path) (NOT NULL)
  191. // if initWithName and filenameBufferSize are explicitly provided, filename will be first overwritten with those
  192. char* FilenameExtPos(char* filename, const char* initWithName, size_t initNameMaxLength) {
  193.         // if the init value is provided with positive buffer size, init the buffer first
  194.         if (0 < initNameMaxLength && initWithName) {
  195.                 STRCPY(filename, initNameMaxLength, initWithName);
  196.         }
  197.         // find start of the base filename
  198.         const char* baseName = FilenameBasePos(filename);
  199.         // find extension of the filename and return position of it
  200.         char* const filenameEnd = filename + strlen(filename);
  201.         char* extPos = filenameEnd;
  202.         while (baseName < extPos && '.' != *extPos) --extPos;
  203.         if (baseName < extPos) return extPos;
  204.         // no extension found (empty filename, or "name", or ".name"), return end of filename
  205.         return filenameEnd;
  206. }
  207.  
  208. const char* FilenameBasePos(const char* fullname) {
  209.         const char* const filenameEnd = fullname + strlen(fullname);
  210.         const char* baseName = filenameEnd;
  211.         while (fullname < baseName && '/' != baseName[-1] && '\\' != baseName[-1]) --baseName;
  212.         return baseName;
  213. }
  214.  
  215. void ConstructDefaultFilename(char* dest, size_t dest_size, const char* ext, bool checkIfDestIsEmpty) {
  216.         if (nullptr == dest || nullptr == ext || !ext[0]) exit(1);      // invalid arguments
  217.         // if the destination buffer has already some content and check is requested, exit
  218.         if (checkIfDestIsEmpty && dest[0]) return;
  219.         size_t extSz = strlen(ext);
  220.         dest[0] = 0;
  221.         // construct the new default name - search for explicit name in sourcefiles
  222.         for (SSource & src : sourceFiles) {
  223.                 if (!src.fname[0]) continue;
  224.                 STRNCPY(dest, dest_size, src.fname, dest_size-1-extSz);
  225.                 dest[dest_size-1-extSz] = 0;
  226.                 break;
  227.         }
  228.         if (!dest[0]) STRNCPY(dest, dest_size, "asm", dest_size-1);             // no explicit, use "asm" base
  229.         // replace the extension
  230.         STRCPY(FilenameExtPos(dest), dest_size, ext);
  231. }
  232.  
  233. void CheckRamLimitExceeded() {
  234.         if (Options::IsLongPtr) return;         // in "longptr" mode with no device keep the address as is
  235.         static bool notWarnedCurAdr = true;
  236.         static bool notWarnedDisp = true;
  237.         char buf[64];
  238.         if (CurAddress >= 0x10000) {
  239.                 if (LASTPASS == pass && notWarnedCurAdr) {
  240.                         SPRINTF2(buf, 64, "RAM limit exceeded 0x%X by %s", (unsigned int)CurAddress, PseudoORG ? "DISP":"ORG");
  241.                         Warning(buf);
  242.                         notWarnedCurAdr = false;
  243.                 }
  244.                 if (PseudoORG) CurAddress &= 0xFFFF;    // fake DISP address gets auto-wrapped FFFF->0
  245.         } else notWarnedCurAdr = true;
  246.         if (PseudoORG && adrdisp >= 0x10000) {
  247.                 if (LASTPASS == pass && notWarnedDisp) {
  248.                         SPRINTF1(buf, 64, "RAM limit exceeded 0x%X by ORG", (unsigned int)adrdisp);
  249.                         Warning(buf);
  250.                         notWarnedDisp = false;
  251.                 }
  252.         } else notWarnedDisp = true;
  253. }
  254.  
  255. void WriteDest() {
  256.         if (!WBLength) {
  257.                 return;
  258.         }
  259.         destlen += WBLength;
  260.         if (FP_Output != NULL && (aint) fwrite(WriteBuffer, 1, WBLength, FP_Output) != WBLength) {
  261.                 Error("Write error (disk full?)", NULL, FATAL);
  262.         }
  263.         if (FP_RAW != NULL && (aint) fwrite(WriteBuffer, 1, WBLength, FP_RAW) != WBLength) {
  264.                 Error("Write error (disk full?)", NULL, FATAL);
  265.         }
  266.  
  267.         if (FP_tapout)
  268.         {
  269.                 int write_length = tape_length + WBLength > 65535 ? 65535 - tape_length : WBLength;
  270.  
  271.                 if ( (aint)fwrite(WriteBuffer, 1, write_length, FP_tapout) != write_length) Error("Write error (disk full?)", NULL, FATAL);
  272.  
  273.                 for (int i = 0; i < write_length; i++) tape_parity ^= WriteBuffer[i];
  274.                 tape_length += write_length;
  275.  
  276.                 if (write_length < WBLength)
  277.                 {
  278.                         WBLength = 0;
  279.                         CloseTapFile();
  280.                         Error("Tape block exceeds maximal size");
  281.                 }
  282.         }
  283.         WBLength = 0;
  284. }
  285.  
  286. void PrintHex(char* & dest, aint value, int nibbles) {
  287.         if (nibbles < 1 || 8 < nibbles) ExitASM(33);    // invalid argument
  288.         const char oldChAfter = dest[nibbles];
  289.         const aint mask = (int(sizeof(aint)*2) <= nibbles) ? ~0L : (1L<<(nibbles*4))-1L;
  290.         if (nibbles != sprintf(dest, "%0*X", nibbles, value&mask)) ExitASM(33);
  291.         dest += nibbles;
  292.         *dest = oldChAfter;
  293. }
  294.  
  295. void PrintHex32(char*& dest, aint value) {
  296.         PrintHex(dest, value, 8);
  297. }
  298.  
  299. void PrintHexAlt(char*& dest, aint value)
  300. {
  301.         char buffer[24] = { 0 }, * bp = buffer;
  302.         sprintf(buffer, "%04X", value);
  303.         while (*bp) *dest++ = *bp++;
  304. }
  305.  
  306. static char pline[4*LINEMAX];
  307.  
  308. // buffer must be at least 4*LINEMAX chars long
  309. void PrepareListLine(char* buffer, aint hexadd)
  310. {
  311.         ////////////////////////////////////////////////////
  312.         // Line numbers to 1 to 99999 are supported only  //
  313.         // For more lines, then first char is incremented //
  314.         ////////////////////////////////////////////////////
  315.  
  316.         int digit = ' ';
  317.         int linewidth = reglenwidth;
  318.         aint linenumber = CurSourcePos.line % 10000;
  319.         if (linewidth > 5)
  320.         {
  321.                 linewidth = 5;
  322.                 digit = CurSourcePos.line / 10000 + '0';
  323.                 if (digit > '~') digit = '~';
  324.                 if (CurSourcePos.line >= 10000) linenumber += 10000;
  325.         }
  326.         memset(buffer, ' ', 24);
  327.         if (listmacro) buffer[23] = '>';
  328.         sprintf(buffer, "%*u", linewidth, linenumber); buffer[linewidth] = ' ';
  329.         memcpy(buffer + linewidth, "++++++", IncludeLevel > 6 - linewidth ? 6 - linewidth : IncludeLevel);
  330.         sprintf(buffer + 6, "%04X", hexadd & 0xFFFF); buffer[10] = ' ';
  331.         if (digit > '0') *buffer = digit & 0xFF;
  332.         // if substitutedLine is completely empty, list rather source line any way
  333.         if (!*substitutedLine) substitutedLine = line;
  334.         STRCPY(buffer + 24, LINEMAX2-24, substitutedLine);
  335.         // add EOL comment if substituted was used and EOL comment is available
  336.         if (substitutedLine != line && eolComment) STRCAT(buffer, LINEMAX2, eolComment);
  337. }
  338.  
  339. static void ListFileStringRtrim() {
  340.         // find end of currently prepared line
  341.         char* beyondLine = pline+24;
  342.         while (*beyondLine) ++beyondLine;
  343.         // and remove trailing white space (space, tab, newline, carriage return, etc..)
  344.         while (pline < beyondLine && White(beyondLine[-1])) --beyondLine;
  345.         // set new line and new string terminator after
  346.         *beyondLine++ = '\n';
  347.         *beyondLine = 0;
  348. }
  349.  
  350. // returns FILE* handle to either actual file defined by --lst=xxx, or stderr if --msg=lst, or NULL
  351. // ! do not fclose this handle, for fclose logic use the FP_ListingFile variable itself !
  352. FILE* GetListingFile() {
  353.         if (NULL != FP_ListingFile) return FP_ListingFile;
  354.         if (OV_LST == Options::OutputVerbosity) return stderr;
  355.         return NULL;
  356. }
  357.  
  358. void ListFile(bool showAsSkipped) {
  359.         if (LASTPASS != pass || NULL == GetListingFile() || donotlist || Options::syx.IsListingSuspended) {
  360.                 donotlist = nListBytes = 0;
  361.                 return;
  362.         }
  363.         int pos = 0;
  364.         do {
  365.                 if (showAsSkipped) substitutedLine = line;      // override substituted lines in skipped mode
  366.                 PrepareListLine(pline, ListAddress);
  367.                 if (pos) pline[24] = 0;         // remove source line on sub-sequent list-lines
  368.                 char* pp = pline + 10;
  369.                 int BtoList = (nListBytes < 4) ? nListBytes : 4;
  370.                 for (int i = 0; i < BtoList; ++i) {
  371.                         if (-2 == ListEmittedBytes[i + pos]) pp += sprintf(pp, "...");
  372.                         else pp += sprintf(pp, " %02X", ListEmittedBytes[i + pos]);
  373.                 }
  374.                 *pp = ' ';
  375.                 if (showAsSkipped) pline[11] = '~';
  376.                 ListFileStringRtrim();
  377.                 fputs(pline, GetListingFile());
  378.                 nListBytes -= BtoList;
  379.                 ListAddress += BtoList;
  380.                 pos += BtoList;
  381.         } while (0 < nListBytes);
  382.         nListBytes = 0;
  383. }
  384.  
  385. void ListSilentOrExternalEmits() {
  386.         // catch silent/external emits like "sj.add_byte(0x123)" from Lua script
  387.         if (0 == nListBytes) return;            // no silent/external emit happened
  388.         char silentOrExternalBytes[] = "; these bytes were emitted silently/externally (lua script?)";
  389.         substitutedLine = silentOrExternalBytes;
  390.         eolComment = nullptr;
  391.         ListFile();
  392.         substitutedLine = line;
  393. }
  394.  
  395. static bool someByteEmitted = false;
  396.  
  397. bool DidEmitByte() {    // returns true if some byte was emitted since last call to this function
  398.         bool didEmit = someByteEmitted;         // value to return
  399.         someByteEmitted = false;                        // reset the flag
  400.         return didEmit;
  401. }
  402.  
  403. static void EmitByteNoListing(int byte, bool preserveDeviceMemory = false) {
  404.         someByteEmitted = true;
  405.         if (LASTPASS == pass) {
  406.                 WriteBuffer[WBLength++] = (char)byte;
  407.                 if (DESTBUFLEN == WBLength) WriteDest();
  408.         }
  409.         // the page-checking in device mode must be done in all passes, the slot can have "wrap" option
  410.         if (DeviceID) {
  411.                 Device->CheckPage(CDevice::CHECK_EMIT);
  412.                 if (MemoryPointer) {
  413.                         if (LASTPASS == pass && !preserveDeviceMemory) *MemoryPointer = (char)byte;
  414.                         ++MemoryPointer;
  415.                 }
  416.         } else {
  417.                 CheckRamLimitExceeded();
  418.         }
  419.         ++CurAddress;
  420.         if (PseudoORG) ++adrdisp;
  421. }
  422.  
  423. void EmitByte(int byte) {
  424.         byte &= 0xFF;
  425.         if (nListBytes < LIST_EMIT_BYTES_BUFFER_SIZE-1) {
  426.                 ListEmittedBytes[nListBytes++] = byte;          // write also into listing
  427.         } else {
  428.                 if (nListBytes < LIST_EMIT_BYTES_BUFFER_SIZE) {
  429.                         // too many bytes, show it in listing as "..."
  430.                         ListEmittedBytes[nListBytes++] = -2;
  431.                 }
  432.         }
  433.         EmitByteNoListing(byte);
  434. }
  435.  
  436. void EmitWord(int word) {
  437.         EmitByte(word % 256);
  438.         EmitByte(word / 256);
  439. }
  440.  
  441. void EmitBytes(const int* bytes) {
  442.         if (*bytes == -1) {
  443.                 Error("Illegal instruction", line, IF_FIRST);
  444.                 SkipToEol(lp);
  445.         }
  446.         while (*bytes != -1) EmitByte(*bytes++);
  447. }
  448.  
  449. void EmitWords(int* words) {
  450.         while (*words != -1) EmitWord(*words++);
  451. }
  452.  
  453. void EmitBlock(aint byte, aint len, bool preserveDeviceMemory, int emitMaxToListing) {
  454.         if (len <= 0) {
  455.                 CurAddress = (CurAddress + len) & 0xFFFF;
  456.                 if (PseudoORG) adrdisp = (adrdisp + len) & 0xFFFF;
  457.                 if (DeviceID)   Device->CheckPage(CDevice::CHECK_NO_EMIT);
  458.                 else                    CheckRamLimitExceeded();
  459.                 return;
  460.         }
  461.         if (LIST_EMIT_BYTES_BUFFER_SIZE <= nListBytes + emitMaxToListing) {     // clamp emit to list buffer
  462.                 emitMaxToListing = LIST_EMIT_BYTES_BUFFER_SIZE - nListBytes;
  463.         }
  464.         while (len--) {
  465.                 int dVal = (preserveDeviceMemory && DeviceID && MemoryPointer) ? MemoryPointer[0] : byte;
  466.                 EmitByteNoListing(byte, preserveDeviceMemory);
  467.                 if (LASTPASS == pass && emitMaxToListing) {
  468.                         // put "..." marker into listing if some more bytes are emitted after last listed
  469.                         if ((0 == --emitMaxToListing) && len) ListEmittedBytes[nListBytes++] = -2;
  470.                         else ListEmittedBytes[nListBytes++] = dVal&0xFF;
  471.                 }
  472.         }
  473. }
  474.  
  475. char* GetPath(const char* fname, char** filenamebegin, bool systemPathsBeforeCurrent)
  476. {
  477.         char fullFilePath[MAX_PATH] = { 0 };
  478.         CStringsList* dir = Options::IncludeDirsList;   // include-paths to search
  479.         // search current directory first (unless "systemPathsBeforeCurrent")
  480.         if (!systemPathsBeforeCurrent) {
  481.                 // if found, just skip the `while (dir)` loop
  482.                 if (SJ_SearchPath(CurrentDirectory, fname, nullptr, MAX_PATH, fullFilePath, filenamebegin)) dir = nullptr;
  483.                 else fullFilePath[0] = 0;       // clear fullFilePath every time when not found
  484.         }
  485.         while (dir) {
  486.                 if (SJ_SearchPath(dir->string, fname, nullptr, MAX_PATH, fullFilePath, filenamebegin)) break;
  487.                 fullFilePath[0] = 0;    // clear fullFilePath every time when not found
  488.                 dir = dir->next;
  489.         }
  490.         // if the file was not found in the list, and current directory was not searched yet
  491.         if (!fullFilePath[0] && systemPathsBeforeCurrent) {
  492.                 //and the current directory was not searched yet, do it now, set empty string if nothing
  493.                 if (!SJ_SearchPath(CurrentDirectory, fname, NULL, MAX_PATH, fullFilePath, filenamebegin)) {
  494.                         fullFilePath[0] = 0;    // clear fullFilePath every time when not found
  495.                 }
  496.         }
  497.         if (!fullFilePath[0] && filenamebegin) {        // if still not found, reset also *filenamebegin
  498.                 *filenamebegin = fullFilePath;
  499.         }
  500.         // copy the result into new memory
  501.         char* kip = STRDUP(fullFilePath);
  502.         if (kip == NULL) ErrorOOM();
  503.         // convert filenamebegin pointer into the copied string (from temporary buffer pointer)
  504.         if (filenamebegin) *filenamebegin += (kip - fullFilePath);
  505.         return kip;
  506. }
  507.  
  508. // if offset is negative, it functions as "how many bytes from end of file"
  509. // if length is negative, it functions as "how many bytes from end of file to not load"
  510. void BinIncFile(char* fname, int offset, int length) {
  511.         // open the desired file
  512.         FILE* bif;
  513.         char* fullFilePath = GetPath(fname);
  514.         if (!FOPEN_ISOK(bif, fullFilePath, "rb")) Error("Error opening file", fname, FATAL);
  515.         free(fullFilePath);
  516.  
  517.         // Get length of file
  518.         int totlen = 0, advanceLength;
  519.         if (fseek(bif, 0, SEEK_END) || (totlen = ftell(bif)) < 0) Error("telling file length", fname, FATAL);
  520.  
  521.         // process arguments (extra features like negative offset/length or INT_MAX length)
  522.         // negative offset means "from the end of file"
  523.         if (offset < 0) offset += totlen;
  524.         // negative length means "except that many from end of file"
  525.         if (length < 0) length += totlen - offset;
  526.         // default length INT_MAX is "till the end of file"
  527.         if (INT_MAX == length) length = totlen - offset;
  528.         // verbose output of final values (before validation may terminate assembler)
  529.         if (LASTPASS == pass && Options::OutputVerbosity <= OV_ALL) {
  530.                 char diagnosticTxt[MAX_PATH];
  531.                 SPRINTF4(diagnosticTxt, MAX_PATH, "include data: name=%s (%d bytes) Offset=%d  Len=%d", fname, totlen, offset, length);
  532.                 _CERR diagnosticTxt _ENDL;
  533.         }
  534.         // validate the resulting [offset, length]
  535.         if (offset < 0 || length < 0 || totlen < offset + length) {
  536.                 Error("file too short", fname, FATAL);
  537.         }
  538.         if (0 == length) {
  539.                 Warning("include data: requested to include no data (length=0)");
  540.                 fclose(bif);
  541.                 return;
  542.         }
  543.  
  544.         // Seek to the beginning of part to include
  545.         if (fseek(bif, offset, SEEK_SET) || ftell(bif) != offset) {
  546.                 Error("seeking in file to offset", fname, FATAL);
  547.         }
  548.  
  549.         if (pass != LASTPASS) {
  550.                 while (length) {
  551.                         advanceLength = length;         // maximum possible to advance in address space
  552.                         if (DeviceID) {                         // particular device may adjust that to less
  553.                                 Device->CheckPage(CDevice::CHECK_EMIT);
  554.                                 if (MemoryPointer) {    // fill up current memory page if possible
  555.                                         advanceLength = Page->RAM + Page->Size - MemoryPointer;
  556.                                         if (length < advanceLength) advanceLength = length;
  557.                                         MemoryPointer += advanceLength;         // also update it! Doh!
  558.                                 }
  559.                         }
  560.                         length -= advanceLength;
  561.                         if (length <= 0 && 0 == advanceLength) Error("BinIncFile internal error", NULL, FATAL);
  562.                         if (PseudoORG) adrdisp = adrdisp + advanceLength;
  563.                         CurAddress = CurAddress + advanceLength;
  564.                 }
  565.         } else {
  566.                 // Reading data from file
  567.                 char* data = new char[length + 1], * bp = data;
  568.                 if (NULL == data) ErrorOOM();
  569.                 size_t res = fread(bp, 1, length, bif);
  570.                 if (res != (size_t)length) Error("reading data from file failed", fname, FATAL);
  571.                 while (length--) EmitByteNoListing(*bp++);
  572.                 delete[] data;
  573.         }
  574.         fclose(bif);
  575. }
  576.  
  577. static void OpenDefaultList(const char *fullpath);
  578.  
  579. static stdin_log_t::const_iterator stdin_read_it;
  580. static stdin_log_t* stdin_log = nullptr;
  581.  
  582. void OpenFile(const char* nfilename, bool systemPathsBeforeCurrent, stdin_log_t* fStdinLog)
  583. {
  584.         const char* oFileNameFull = fileNameFull;
  585.         TextFilePos oSourcePos = CurSourcePos;
  586.         char* oCurrentDirectory, * fullpath;
  587.         TCHAR* filenamebegin;
  588.  
  589.         if (++IncludeLevel > 20) {
  590.                 Error("Over 20 files nested", NULL, FATAL);
  591.         }
  592.         if (!*nfilename && fStdinLog) {
  593.                 fullpath = STRDUP("console_input");
  594.                 filenamebegin = fullpath;
  595.                 FP_Input = stdin;
  596.                 stdin_log = fStdinLog;
  597.                 stdin_read_it = stdin_log->cbegin();    // reset read iterator (for 2nd+ pass)
  598.         } else {
  599.                 fullpath = GetPath(nfilename, &filenamebegin, systemPathsBeforeCurrent);
  600.  
  601.                 if (!*fullpath || !FOPEN_ISOK(FP_Input, fullpath, "rb")) {
  602.                         free(fullpath);
  603.                         Error("Error opening file", nfilename, FATAL);
  604.                 }
  605.         }
  606.         // archive the filename (for referencing it in SLD tracing data or listing/errors)
  607.         auto ofnIt = std::find(openedFileNames.cbegin(), openedFileNames.cend(), fullpath);
  608.         if (ofnIt == openedFileNames.cend()) {          // new filename, add it to archive
  609.                 openedFileNames.push_back(fullpath);
  610.                 ofnIt = --openedFileNames.cend();
  611.         }
  612.         fileNameFull = ofnIt->c_str();                          // get const pointer into archive
  613.         CurSourcePos.newFile(Options::IsShowFullPath ? fileNameFull : FilenameBasePos(fileNameFull));
  614.  
  615.         // refresh pre-defined values related to file/include
  616.         DefineTable.Replace("__INCLUDE_LEVEL__", IncludeLevel);
  617.         DefineTable.Replace("__FILE__", fileNameFull);
  618.         if (0 == IncludeLevel) DefineTable.Replace("__BASE_FILE__", fileNameFull);
  619.  
  620.         // open default listing file for each new source file (if default listing is ON)
  621.         if (LASTPASS == pass && 0 == IncludeLevel && Options::IsDefaultListingName) {
  622.                 OpenDefaultList(fullpath);                      // explicit listing file is already opened
  623.         }
  624.         // show in listing file which file was opened
  625.         FILE* listFile = GetListingFile();
  626.         if (LASTPASS == pass && listFile) {
  627.                 fputs("# file opened: ", listFile);
  628.                 fputs(fileNameFull, listFile);
  629.                 fputs("\n", listFile);
  630.         }
  631.  
  632.         oCurrentDirectory = CurrentDirectory;
  633.         *filenamebegin = 0;
  634.         CurrentDirectory = fullpath;
  635.  
  636.         rlpbuf = rlpbuf_end = rlbuf;
  637.         colonSubline = false;
  638.         blockComment = 0;
  639.  
  640.         ReadBufLine();
  641.  
  642.         if (stdin != FP_Input) fclose(FP_Input);
  643.         else {
  644.                 if (1 == pass) {
  645.                         stdin_log->push_back(0);        // add extra zero terminator
  646.                         clearerr(stdin);                        // reset EOF on the stdin for another round of input
  647.                 }
  648.         }
  649.         CurrentDirectory = oCurrentDirectory;
  650.  
  651.         // show in listing file which file was closed
  652.         if (LASTPASS == pass && listFile) {
  653.                 fputs("# file closed: ", listFile);
  654.                 fputs(fileNameFull, listFile);
  655.                 fputs("\n", listFile);
  656.  
  657.                 // close listing file (if "default" listing filename is used)
  658.                 if (FP_ListingFile && 0 == IncludeLevel && Options::IsDefaultListingName) {
  659.                         if (Options::AddLabelListing) LabelTable.Dump();
  660.                         fclose(FP_ListingFile);
  661.                         FP_ListingFile = NULL;
  662.                 }
  663.         }
  664.  
  665.         --IncludeLevel;
  666.  
  667.         // Free memory
  668.         free(fullpath);
  669.  
  670.         if (CurSourcePos.line > maxlin) {
  671.                 maxlin = CurSourcePos.line;
  672.         }
  673.         fileNameFull = oFileNameFull;
  674.         CurSourcePos = oSourcePos;
  675.  
  676.         // refresh pre-defined values related to file/include
  677.         DefineTable.Replace("__INCLUDE_LEVEL__", IncludeLevel);
  678.         DefineTable.Replace("__FILE__", fileNameFull ? fileNameFull : "<none>");
  679.         if (-1 == IncludeLevel) DefineTable.Replace("__BASE_FILE__", "<none>");
  680. }
  681.  
  682. void IncludeFile(const char* nfilename, bool systemPathsBeforeCurrent)
  683. {
  684.         auto oStdin_log = stdin_log;
  685.         auto oStdin_read_it = stdin_read_it;
  686.         FILE* oFP_Input = FP_Input;
  687.         FP_Input = 0;
  688.  
  689.         char* pbuf = rlpbuf, * pbuf_end = rlpbuf_end, * buf = STRDUP(rlbuf);
  690.         if (buf == NULL) ErrorOOM();
  691.         bool oColonSubline = colonSubline;
  692.         if (blockComment) Error("Internal error 'block comment'", NULL, FATAL); // comment can't INCLUDE
  693.  
  694.         OpenFile(nfilename, systemPathsBeforeCurrent);
  695.  
  696.         colonSubline = oColonSubline;
  697.         rlpbuf = pbuf, rlpbuf_end = pbuf_end;
  698.         STRCPY(rlbuf, 8192, buf);
  699.         free(buf);
  700.  
  701.         FP_Input = oFP_Input;
  702.         stdin_log = oStdin_log;
  703.         stdin_read_it = oStdin_read_it;
  704. }
  705.  
  706. typedef struct {
  707.         char    name[12];
  708.         size_t  length;
  709.         byte    marker[16];
  710. } BOMmarkerDef;
  711.  
  712. const BOMmarkerDef UtfBomMarkers[] = {
  713.         { { "UTF8" }, 3, { 0xEF, 0xBB, 0xBF } },
  714.         { { "UTF32BE" }, 4, { 0, 0, 0xFE, 0xFF } },
  715.         { { "UTF32LE" }, 4, { 0xFF, 0xFE, 0, 0 } },             // must be detected *BEFORE* UTF16LE
  716.         { { "UTF16BE" }, 2, { 0xFE, 0xFF } },
  717.         { { "UTF16LE" }, 2, { 0xFF, 0xFE } }
  718. };
  719.  
  720. static bool ReadBufData() {
  721.         // check here also if `line` buffer is not full
  722.         if ((LINEMAX-2) <= (rlppos - line)) Error("Line too long", NULL, FATAL);
  723.         // now check for read data
  724.         if (rlpbuf < rlpbuf_end) return 1;              // some data still in buffer
  725.         // check EOF on files in every pass, stdin only in first, following will starve the stdin_log
  726.         if ((stdin != FP_Input || 1 == pass) && feof(FP_Input)) return 0;       // no more data in file
  727.         // read next block of data
  728.         rlpbuf = rlbuf;
  729.         // handle STDIN file differently (pass1 = read it, pass2+ replay "log" variable)
  730.         if (1 == pass || stdin != FP_Input) {   // ordinary file is re-read every pass normally
  731.                 rlpbuf_end = rlbuf + fread(rlbuf, 1, 4096, FP_Input);
  732.                 *rlpbuf_end = 0;                                        // add zero terminator after new block
  733.         }
  734.         if (stdin == FP_Input) {
  735.                 // store copy of stdin into stdin_log during pass 1
  736.                 if (1 == pass && rlpbuf < rlpbuf_end) {
  737.                         stdin_log->insert(stdin_log->end(), rlpbuf, rlpbuf_end);
  738.                 }
  739.                 // replay the log in 2nd+ pass
  740.                 if (1 < pass) {
  741.                         rlpbuf_end = rlpbuf;
  742.                         long toCopy = std::min(8000L, (long)std::distance(stdin_read_it, stdin_log->cend()));
  743.                         if (0 < toCopy) {
  744.                                 memcpy(rlbuf, &(*stdin_read_it), toCopy);
  745.                                 stdin_read_it += toCopy;
  746.                                 rlpbuf_end += toCopy;
  747.                         }
  748.                         *rlpbuf_end = 0;                                // add zero terminator after new block
  749.                 }
  750.         }
  751.         // check UTF BOM markers only at the beginning of the file (source line == 0)
  752.         if (CurSourcePos.line) return (rlpbuf < rlpbuf_end);    // return true if some data were read
  753.         //UTF BOM markers detector
  754.         for (const auto & bomMarkerData : UtfBomMarkers) {
  755.                 if (rlpbuf_end < (rlpbuf + bomMarkerData.length)) continue;     // not enough bytes in buffer
  756.                 if (memcmp(rlpbuf, bomMarkerData.marker, bomMarkerData.length)) continue;       // marker not found
  757.                 if (&bomMarkerData != UtfBomMarkers) {  // UTF8 is first in the array, other markers show error
  758.                         Error("Invalid UTF encoding detected (only ASCII and UTF8 works)", bomMarkerData.name, FATAL);
  759.                 }
  760.                 rlpbuf += bomMarkerData.length; // skip the UTF8 BOM marker
  761.         }
  762.         return (rlpbuf < rlpbuf_end);                   // return true if some data were read
  763. }
  764.  
  765. void ReadBufLine(bool Parse, bool SplitByColon) {
  766.         // if everything else fails (no data, not running, etc), return empty line
  767.         *line = 0;
  768.         bool IsLabel = true;
  769.         // try to read through the buffer and produce new line from it
  770.         while (IsRunning && ReadBufData()) {
  771.                 // start of new line (or fake "line" by colon)
  772.                 rlppos = line;
  773.                 substitutedLine = line;         // also reset "substituted" line to the raw new one
  774.                 eolComment = NULL;
  775.                 if (colonSubline) {                     // starting from colon (creating new fake "line")
  776.                         colonSubline = false;   // (can't happen inside block comment)
  777.                         *(rlppos++) = ' ';
  778.                         IsLabel = false;
  779.                 } else {                                        // starting real new line
  780.                         IsLabel = (0 == blockComment);
  781.                 }
  782.                 bool afterNonAlphaNum, afterNonAlphaNumNext = true;
  783.                 // copy data from read buffer into `line` buffer until EOL/colon is found
  784.                 while (
  785.                                 ReadBufData() && '\n' != *rlpbuf && '\r' != *rlpbuf &&  // split by EOL
  786.                                 // split by colon only on 2nd+ char && SplitByColon && not inside block comment
  787.                                 (blockComment || !SplitByColon || rlppos == line || ':' != *rlpbuf)) {
  788.                         // copy the new character to new line
  789.                         *rlppos = *rlpbuf++;
  790.                         afterNonAlphaNum = afterNonAlphaNumNext;
  791.                         afterNonAlphaNumNext = !isalnum((byte)*rlppos);
  792.                         // Block comments logic first (anything serious may happen only "outside" of block comment
  793.                         if ('*' == *rlppos && ReadBufData() && '/' == *rlpbuf) {
  794.                                 if (0 < blockComment) --blockComment;   // block comment ends here, -1 from nesting
  795.                                 ++rlppos;       *rlppos++ = *rlpbuf++;          // copy the second char too
  796.                                 continue;
  797.                         }
  798.                         if ('/' == *rlppos && ReadBufData() && '*' == *rlpbuf) {
  799.                                 ++rlppos, ++blockComment;                               // block comment starts here, nest +1 more
  800.                                 *rlppos++ = *rlpbuf++;                                  // copy the second char too
  801.                                 continue;
  802.                         }
  803.                         if (blockComment) {                                                     // inside block comment just copy chars
  804.                                 ++rlppos;
  805.                                 continue;
  806.                         }
  807.                         // check if still in label area, if yes, copy the finishing colon as char (don't split by it)
  808.                         if ((IsLabel = IsLabel && islabchar(*rlppos))) {
  809.                                 ++rlppos;                                       // label character
  810.                                 if (ReadBufData() && ':' == *rlpbuf) {  // colon after label, add it
  811.                                         *rlppos++ = *rlpbuf++;
  812.                                         IsLabel = false;
  813.                                 }
  814.                                 continue;
  815.                         }
  816.                         // not in label any more, check for EOL comments ";" or "//"
  817.                         if ((';' == *rlppos) || ('/' == *rlppos && ReadBufData() && '/' == *rlpbuf)) {
  818.                                 eolComment = rlppos;
  819.                                 ++rlppos;                                       // EOL comment ";"
  820.                                 while (ReadBufData() && '\n' != *rlpbuf && '\r' != *rlpbuf) *rlppos++ = *rlpbuf++;
  821.                                 continue;
  822.                         }
  823.                         // check for string literals - double/single quotes
  824.                         if (afterNonAlphaNum && ('"' == *rlppos || '\'' == *rlppos)) {
  825.                                 const bool quotes = '"' == *rlppos;
  826.                                 int escaped = 0;
  827.                                 do {
  828.                                         if (escaped) --escaped;
  829.                                         ++rlppos;                               // previous char confirmed
  830.                                         *rlppos = ReadBufData() ? *rlpbuf : 0;  // copy next char (if available)
  831.                                         if (!*rlppos || '\r' == *rlppos || '\n' == *rlppos) *rlppos = 0;        // not valid
  832.                                         else ++rlpbuf;                  // buffer char read (accepted)
  833.                                         if (quotes && !escaped && '\\' == *rlppos) escaped = 2; // escape sequence detected
  834.                                 } while (*rlppos && (escaped || (quotes ? '"' : '\'') != *rlppos));
  835.                                 if (*rlppos) ++rlppos;          // there should be ending "/' in line buffer, confirm it
  836.                                 continue;
  837.                         }
  838.                         // anything else just copy
  839.                         ++rlppos;                               // previous char confirmed
  840.                 } // while "some char in buffer, and it's not line delimiter"
  841.                 // line interrupted somehow, may be correctly finished, check + finalize line and process it
  842.                 *rlppos = 0;
  843.                 // skip <EOL> char sequence in read buffer
  844.                 if (ReadBufData() && ('\r' == *rlpbuf || '\n' == *rlpbuf)) {
  845.                         char CRLFtest = (*rlpbuf++) ^ ('\r'^'\n');      // flip CR->LF || LF->CR (and eats first)
  846.                         if (ReadBufData() && CRLFtest == *rlpbuf) ++rlpbuf;     // if CRLF/LFCR pair, eat also second
  847.                         // if this was very last <EOL> in file (on non-empty line), add one more fake empty line
  848.                         if (!ReadBufData() && *line) *rlpbuf_end++ = '\n';      // to make listing files "as before"
  849.                 } else {
  850.                         // advance over single colon if that was the reason to terminate line parsing
  851.                         colonSubline = SplitByColon && ReadBufData() && (':' == *rlpbuf) && ++rlpbuf;
  852.                 }
  853.                 // do +1 for very first colon-segment only (rest is +1 due to artificial space at beginning)
  854.                 size_t advanceColumns = colonSubline ? (0 == CurSourcePos.colEnd) + strlen(line) : 0;
  855.                 CurSourcePos.nextSegment(colonSubline, advanceColumns);
  856.                 // line is parsed and ready to be processed
  857.                 if (Parse)      ParseLine();    // processed here in loop
  858.                 else            return;                 // processed externally
  859.         } // while (IsRunning && ReadBufData())
  860. }
  861.  
  862. static void OpenListImp(const char* listFilename) {
  863.         // if STDERR is configured to contain listing, disable other listing files
  864.         if (OV_LST == Options::OutputVerbosity) return;
  865.         if (NULL == listFilename || !listFilename[0]) return;
  866.         if (!FOPEN_ISOK(FP_ListingFile, listFilename, "w")) {
  867.                 Error("Error opening file", listFilename, FATAL);
  868.         }
  869. }
  870.  
  871. void OpenList() {
  872.         // if STDERR is configured to contain listing, disable other listing files
  873.         if (OV_LST == Options::OutputVerbosity) return;
  874.         // check if listing file is already opened, or it is set to "default" file names
  875.         if (Options::IsDefaultListingName || NULL != FP_ListingFile) return;
  876.         // Only explicit listing files are opened here
  877.         OpenListImp(Options::ListingFName);
  878. }
  879.  
  880. static void OpenDefaultList(const char *fullpath) {
  881.         // if STDERR is configured to contain listing, disable other listing files
  882.         if (OV_LST == Options::OutputVerbosity) return;
  883.         // check if listing file is already opened, or it is set to explicit file name
  884.         if (!Options::IsDefaultListingName || NULL != FP_ListingFile) return;
  885.         if (NULL == fullpath || !*fullpath) return;             // no filename provided
  886.         // Create default listing name, and try to open it
  887.         char tempListName[LINEMAX+10];          // make sure there is enough room for new extension
  888.         char* extPos = FilenameExtPos(tempListName, fullpath, LINEMAX); // find extension position
  889.         STRCPY(extPos, 5, ".lst");                      // overwrite it with ".lst"
  890.         // list filename prepared, open it
  891.         OpenListImp(tempListName);
  892. }
  893.  
  894. void CloseDest() {
  895.         // Flush buffer before any other operations
  896.         WriteDest();
  897.         // does main output file exist? (to close it)
  898.         if (FP_Output == NULL) return;
  899.         // pad to desired size (and check for exceed of it)
  900.         if (size != -1L) {
  901.                 if (destlen > size) {
  902.                         ErrorInt("File exceeds 'size' by", destlen - size);
  903.                 }
  904.                 memset(WriteBuffer, 0, DESTBUFLEN);
  905.                 while (destlen < size) {
  906.                         WBLength = std::min(aint(DESTBUFLEN), size-destlen);
  907.                         WriteDest();
  908.                 }
  909.                 size = -1L;
  910.         }
  911.         fclose(FP_Output);
  912.         FP_Output = NULL;
  913. }
  914.  
  915. void SeekDest(long offset, int method) {
  916.         WriteDest();
  917.         if (FP_Output != NULL && fseek(FP_Output, offset, method)) {
  918.                 Error("File seek error (FPOS)", NULL, FATAL);
  919.         }
  920. }
  921.  
  922. void NewDest(char* newfilename, int mode) {
  923.         // close previous output file
  924.         CloseDest();
  925.  
  926.         // and open new file (keep previous/default name, if no explicit was provided)
  927.         if (newfilename && *newfilename) STRCPY(Options::DestinationFName, LINEMAX, newfilename);
  928.         OpenDest(mode);
  929. }
  930.  
  931. void OpenDest(int mode) {
  932.         destlen = 0;
  933.         if (mode != OUTPUT_TRUNCATE && !FileExists(Options::DestinationFName)) {
  934.                 mode = OUTPUT_TRUNCATE;
  935.         }
  936.         if (!Options::NoDestinationFile && !FOPEN_ISOK(FP_Output, Options::DestinationFName, mode == OUTPUT_TRUNCATE ? "wb" : "r+b")) {
  937.                 Error("Error opening file", Options::DestinationFName, FATAL);
  938.         }
  939.         Options::NoDestinationFile = false;
  940.         if (NULL == FP_RAW && '-' == Options::RAWFName[0] && 0 == Options::RAWFName[1]) {
  941.                 FP_RAW = stdout;
  942.                 fflush(stdout);
  943.                 switchStdOutIntoBinaryMode();
  944.         }
  945.         if (FP_RAW == NULL && Options::RAWFName[0] && !FOPEN_ISOK(FP_RAW, Options::RAWFName, "wb")) {
  946.                 Error("Error opening file", Options::RAWFName);
  947.         }
  948.         if (FP_Output != NULL && mode != OUTPUT_TRUNCATE) {
  949.                 if (fseek(FP_Output, 0, mode == OUTPUT_REWIND ? SEEK_SET : SEEK_END)) {
  950.                         Error("File seek error (OUTPUT)", NULL, FATAL);
  951.                 }
  952.         }
  953. }
  954.  
  955. void CloseTapFile()
  956. {
  957.         char tap_data[2];
  958.  
  959.         WriteDest();
  960.         if (FP_tapout == NULL) return;
  961.  
  962.         tap_data[0] = tape_parity & 0xFF;
  963.         if (fwrite(tap_data, 1, 1, FP_tapout) != 1) Error("Write error (disk full?)", NULL, FATAL);
  964.  
  965.         if (fseek(FP_tapout, tape_seek, SEEK_SET)) Error("File seek end error in TAPOUT", NULL, FATAL);
  966.  
  967.         tap_data[0] =  tape_length     & 0xFF;
  968.         tap_data[1] = (tape_length>>8) & 0xFF;
  969.         if (fwrite(tap_data, 1, 2, FP_tapout) != 2) Error("Write error (disk full?)", NULL, FATAL);
  970.  
  971.         fclose(FP_tapout);
  972.         FP_tapout = NULL;
  973. }
  974.  
  975. void OpenTapFile(char * tapename, int flagbyte)
  976. {
  977.         CloseTapFile();
  978.  
  979.         if (!FOPEN_ISOK(FP_tapout,tapename, "r+b"))     Error( "Error opening file in TAPOUT", tapename, FATAL);
  980.         if (fseek(FP_tapout, 0, SEEK_END))                      Error("File seek end error in TAPOUT", tapename, FATAL);
  981.  
  982.         tape_seek = ftell(FP_tapout);
  983.         tape_parity = flagbyte;
  984.         tape_length = 2;
  985.  
  986.         char tap_data[4] = { 0,0,0,0 };
  987.         tap_data[2] = (char)flagbyte;
  988.  
  989.         if (fwrite(tap_data, 1, 3, FP_tapout) != 3) {
  990.                 fclose(FP_tapout);
  991.                 Error("Write error (disk full?)", NULL, FATAL);
  992.         }
  993. }
  994.  
  995. int FileExists(char* file_name) {
  996.         int exists = 0;
  997.         FILE* test;
  998.         if (FOPEN_ISOK(test, file_name, "r")) {
  999.                 exists = 1;
  1000.                 fclose(test);
  1001.         }
  1002.         return exists;
  1003. }
  1004.  
  1005. void Close() {
  1006.         if (*ModuleName) {
  1007.                 Warning("ENDMODULE missing for module", ModuleName, W_ALL);
  1008.         }
  1009.  
  1010.         CloseDest();
  1011.         CloseTapFile();
  1012.         if (FP_ExportFile != NULL) {
  1013.                 fclose(FP_ExportFile);
  1014.                 FP_ExportFile = NULL;
  1015.         }
  1016.         if (FP_RAW != NULL) {
  1017.                 if (stdout != FP_RAW) fclose(FP_RAW);
  1018.                 FP_RAW = NULL;
  1019.         }
  1020.         if (FP_ListingFile != NULL) {
  1021.                 fclose(FP_ListingFile);
  1022.                 FP_ListingFile = NULL;
  1023.         }
  1024.         CloseSld();
  1025.         CloseBreakpointsFile();
  1026. }
  1027.  
  1028. int SaveRAM(FILE* ff, int start, int length) {
  1029.         //unsigned int addadr = 0,save = 0;
  1030.         aint save = 0;
  1031.         if (!DeviceID) return 0;                // unreachable currently
  1032.         if (length + start > 0x10000) {
  1033.                 length = -1;
  1034.         }
  1035.         if (length <= 0) {
  1036.                 length = 0x10000 - start;
  1037.         }
  1038.  
  1039.         CDeviceSlot* S;
  1040.         for (int i=0;i<Device->SlotsCount;i++) {
  1041.                 S = Device->GetSlot(i);
  1042.                 if (start >= (int)S->Address  && start < (int)(S->Address + S->Size)) {
  1043.                         if (length < (int)(S->Size - (start - S->Address))) {
  1044.                                 save = length;
  1045.                         } else {
  1046.                                 save = S->Size - (start - S->Address);
  1047.                         }
  1048.                         if ((aint) fwrite(S->Page->RAM + (start - S->Address), 1, save, ff) != save) {
  1049.                                 return 0;
  1050.                         }
  1051.                         length -= save;
  1052.                         start += save;
  1053.                         if (length <= 0) {
  1054.                                 return 1;
  1055.                         }
  1056.                 }
  1057.         }
  1058.         return 0;               // unreachable (with current devices)
  1059. }
  1060.  
  1061. unsigned int MemGetWord(unsigned int address) {
  1062.         return MemGetByte(address) + (MemGetByte(address+1)<<8);
  1063. }
  1064.  
  1065. unsigned char MemGetByte(unsigned int address) {
  1066.         if (!DeviceID || pass != LASTPASS) {
  1067.                 return 0;
  1068.         }
  1069.  
  1070.         CDeviceSlot* S;
  1071.         for (int i=0;i<Device->SlotsCount;i++) {
  1072.                 S = Device->GetSlot(i);
  1073.                 if (address >= (unsigned int)S->Address  && address < (unsigned int)S->Address + (unsigned int)S->Size) {
  1074.                         return S->Page->RAM[address - S->Address];
  1075.                 }
  1076.         }
  1077.  
  1078.         ErrorInt("MemGetByte: Error reading address", address);
  1079.         return 0;
  1080. }
  1081.  
  1082.  
  1083. int SaveBinary(char* fname, int start, int length) {
  1084.         FILE* ff;
  1085.         if (!FOPEN_ISOK(ff, fname, "wb")) {
  1086.                 Error("Error opening file", fname, FATAL);
  1087.         }
  1088.         int result = SaveRAM(ff, start, length);
  1089.         fclose(ff);
  1090.         return result;
  1091. }
  1092.  
  1093.  
  1094. // all arguments must be sanitized by caller (this just writes data block into opened file)
  1095. bool SaveDeviceMemory(FILE* file, const size_t start, const size_t length) {
  1096.         return (length == fwrite(Device->Memory + start, 1, length, file));
  1097. }
  1098.  
  1099.  
  1100. // start and length must be sanitized by caller
  1101. bool SaveDeviceMemory(const char* fname, const size_t start, const size_t length) {
  1102.         FILE* ff;
  1103.         if (!FOPEN_ISOK(ff, fname, "wb")) Error("Error opening file", fname, FATAL);
  1104.         bool res = SaveDeviceMemory(ff, start, length);
  1105.         fclose(ff);
  1106.         return res;
  1107. }
  1108.  
  1109.  
  1110. int SaveHobeta(char* fname, char* fhobname, int start, int length) {
  1111.         unsigned char header[0x11];
  1112.         int i;
  1113.  
  1114.         if (length + start > 0x10000) {
  1115.                 length = -1;
  1116.         }
  1117.         if (length <= 0) {
  1118.                 length = 0x10000 - start;
  1119.         }
  1120.  
  1121.         memset(header,' ',9);
  1122.         i = strlen(fhobname);
  1123.         if (i > 1)
  1124.         {
  1125.                 char *ext = strrchr(fhobname, '.');
  1126.                 if (ext && ext[1])
  1127.                 {
  1128.                         header[8] = ext[1];
  1129.                         i = ext-fhobname;
  1130.                 }
  1131.         }
  1132.         memcpy(header, fhobname, std::min(i,8));
  1133.  
  1134.         if (header[8] == 'B')   {
  1135.                 header[0x09] = (unsigned char)(length & 0xff);
  1136.                 header[0x0a] = (unsigned char)(length >> 8);
  1137.         } else  {
  1138.                 header[0x09] = (unsigned char)(start & 0xff);
  1139.                 header[0x0a] = (unsigned char)(start >> 8);
  1140.         }
  1141.  
  1142.         header[0x0b] = (unsigned char)(length & 0xff);
  1143.         header[0x0c] = (unsigned char)(length >> 8);
  1144.         header[0x0d] = 0;
  1145.         if (header[0x0b] == 0) {
  1146.                 header[0x0e] = header[0x0c];
  1147.         } else {
  1148.                 header[0x0e] = header[0x0c] + 1;
  1149.         }
  1150.         length = header[0x0e] * 0x100;
  1151.         int chk = 0;
  1152.         for (i = 0; i <= 14; chk = chk + (header[i] * 257) + i,i++) {
  1153.                 ;
  1154.         }
  1155.         header[0x0f] = (unsigned char)(chk & 0xff);
  1156.         header[0x10] = (unsigned char)(chk >> 8);
  1157.  
  1158.         FILE* ff;
  1159.         if (!FOPEN_ISOK(ff, fname, "wb")) {
  1160.                 Error("Error opening file", fname, FATAL);
  1161.         }
  1162.  
  1163.         int result = (17 == fwrite(header, 1, 17, ff)) && SaveRAM(ff, start, length);
  1164.         fclose(ff);
  1165.         return result;
  1166. }
  1167.  
  1168. EReturn ReadFile() {
  1169.         while (ReadLine()) {
  1170.                 const bool isInsideDupCollectingLines = !RepeatStack.empty() && !RepeatStack.top().IsInWork;
  1171.                 if (!isInsideDupCollectingLines) {
  1172.                         char* p = line;
  1173.                         SkipBlanks(p);
  1174.                         if ('.' == *p) ++p;
  1175.                         if (cmphstr(p, "endif")) {
  1176.                                 lp = ReplaceDefine(p);          // skip any empty substitutions and comments
  1177.                                 substitutedLine = line;         // override substituted listing for ENDIF
  1178.                                 return ENDIF;
  1179.                         } else if (cmphstr(p, "else")) {
  1180.                                 lp = ReplaceDefine(p);          // skip any empty substitutions and comments
  1181.                                 substitutedLine = line;         // override substituted listing for ELSE
  1182.                                 ListFile();
  1183.                                 return ELSE;
  1184.                         }
  1185.                 }
  1186.                 ParseLineSafe();
  1187.         }
  1188.         return END;
  1189. }
  1190.  
  1191.  
  1192. EReturn SkipFile() {
  1193.         int iflevel = 0;
  1194.         while (ReadLine()) {
  1195.                 char* p = line;
  1196.                 SkipBlanks(p);
  1197.                 if ('.' == *p) ++p;
  1198.                 if (cmphstr(p, "if") || cmphstr(p, "ifn") || cmphstr(p, "ifused") ||
  1199.                         cmphstr(p, "ifnused") || cmphstr(p, "ifdef") || cmphstr(p, "ifndef")) {
  1200.                         ++iflevel;
  1201.                 } else if (cmphstr(p, "endif")) {
  1202.                         if (iflevel) {
  1203.                                 --iflevel;
  1204.                         } else {
  1205.                                 lp = ReplaceDefine(p);          // skip any empty substitutions and comments
  1206.                                 substitutedLine = line;         // override substituted listing for ENDIF
  1207.                                 return ENDIF;
  1208.                         }
  1209.                 } else if (cmphstr(p, "else")) {
  1210.                         if (!iflevel) {
  1211.                                 lp = ReplaceDefine(p);          // skip any empty substitutions and comments
  1212.                                 substitutedLine = line;         // override substituted listing for ELSE
  1213.                                 ListFile();
  1214.                                 return ELSE;
  1215.                         }
  1216.                 }
  1217.                 ListFile(true);
  1218.         }
  1219.         return END;
  1220. }
  1221.  
  1222. int ReadLineNoMacro(bool SplitByColon) {
  1223.         if (!IsRunning || !ReadBufData()) return 0;
  1224.         ReadBufLine(false, SplitByColon);
  1225.         return 1;
  1226. }
  1227.  
  1228. int ReadLine(bool SplitByColon) {
  1229.         DefinitionPos = TextFilePos();
  1230.         if (IsRunning && lijst) {               // read MACRO lines, if macro is being emitted
  1231.                 if (!lijstp) return 0;
  1232.                 DefinitionPos = lijstp->definition;
  1233.                 STRCPY(line, LINEMAX, lijstp->string);
  1234.                 substitutedLine = line;         // reset substituted listing
  1235.                 eolComment = NULL;                      // reset end of line comment
  1236.                 lijstp = lijstp->next;
  1237.                 return 1;
  1238.         }
  1239.         return ReadLineNoMacro(SplitByColon);
  1240. }
  1241.  
  1242. int ReadFileToCStringsList(CStringsList*& f, const char* end) {
  1243.         // f itself should be already NULL, not resetting it here
  1244.         CStringsList** s = &f;
  1245.         while (ReadLineNoMacro()) {
  1246.                 char* p = line;
  1247.                 SkipBlanks(p);
  1248.                 if ('.' == *p) ++p;
  1249.                 if (cmphstr(p, end)) {          // finished, read rest after end marker into line buffers
  1250.                         lp = ReplaceDefine(p);
  1251.                         return 1;
  1252.                 }
  1253.                 *s = new CStringsList(line);
  1254.                 s = &((*s)->next);
  1255.                 ListFile(true);
  1256.         }
  1257.         return 0;
  1258. }
  1259.  
  1260. void WriteExp(char* n, aint v) {
  1261.         char lnrs[16],* l = lnrs;
  1262.         if (FP_ExportFile == NULL) {
  1263.                 if (!FOPEN_ISOK(FP_ExportFile, Options::ExportFName, "w")) {
  1264.                         Error("Error opening file", Options::ExportFName, FATAL);
  1265.                 }
  1266.         }
  1267.         STRCPY(ErrorLine, LINEMAX2, n);
  1268.         STRCAT(ErrorLine, LINEMAX2-1, ": EQU ");
  1269.         STRCAT(ErrorLine, LINEMAX2-1, "0x");
  1270.         PrintHex32(l, v); *l = 0;
  1271.         STRCAT(ErrorLine, LINEMAX2-1, lnrs);
  1272.         STRCAT(ErrorLine, LINEMAX2-1, "\n");
  1273.         fputs(ErrorLine, FP_ExportFile);
  1274. }
  1275.  
  1276. /////// source-level-debugging support by Ckirby
  1277.  
  1278. static FILE* FP_SourceLevelDebugging = NULL;
  1279. static char sldMessage[LINEMAX];
  1280. static const char* WriteToSld_noSymbol = "";
  1281. static char sldMessage_sourcePos[80];
  1282. static char sldMessage_definitionPos[80];
  1283. static const char* sldMessage_posFormat = "%d:%d:%d";   // at +3 is "%d:%d" and at +6 is "%d"
  1284.  
  1285. static void WriteToSldFile_TextFilePos(char* buffer, const TextFilePos & pos) {
  1286.         int offsetFormat = !pos.colBegin ? 6 : !pos.colEnd ? 3 : 0;
  1287.         snprintf(buffer, 79, sldMessage_posFormat + offsetFormat, pos.line, pos.colBegin, pos.colEnd);
  1288. }
  1289.  
  1290. static void OpenSldImp(const char* sldFilename) {
  1291.         if (nullptr == sldFilename || !sldFilename[0]) return;
  1292.         if (!FOPEN_ISOK(FP_SourceLevelDebugging, sldFilename, "w")) {
  1293.                 Error("Error opening file", sldFilename, FATAL);
  1294.         }
  1295.         fputs("|SLD.data.version|0\n", FP_SourceLevelDebugging);
  1296. }
  1297.  
  1298. // will write directly into Options::SourceLevelDebugFName array
  1299. static void OpenSld_buildDefaultNameIfNeeded() {
  1300.         // check if SLD file name is already explicitly defined, or default is wanted
  1301.         if (Options::SourceLevelDebugFName[0] || !Options::IsDefaultSldName) return;
  1302.         // name is still empty, and default is wanted, create one (start with "out" or first source name)
  1303.         ConstructDefaultFilename(Options::SourceLevelDebugFName, LINEMAX, ".sld.txt", false);
  1304. }
  1305.  
  1306. // returns true only in the LASTPASS and only when "sld" file was specified by user
  1307. // and only when assembling is in "virtual DEVICE" mode (for "none" device no tracing is emitted)
  1308. bool IsSldExportActive() {
  1309.         return (nullptr != FP_SourceLevelDebugging && DeviceID);
  1310. }
  1311.  
  1312. void OpenSld() {
  1313.         // check if source-level-debug file is already opened
  1314.         if (nullptr != FP_SourceLevelDebugging) return;
  1315.         // build default filename if not explicitly provided, and default was requested
  1316.         OpenSld_buildDefaultNameIfNeeded();
  1317.         // try to open it if not opened yet
  1318.         OpenSldImp(Options::SourceLevelDebugFName);
  1319. }
  1320.  
  1321. void CloseSld() {
  1322.         if (!FP_SourceLevelDebugging) return;
  1323.         fclose(FP_SourceLevelDebugging);
  1324.         FP_SourceLevelDebugging = nullptr;
  1325. }
  1326.  
  1327. void WriteToSldFile(int pageNum, int value, char type, const char* symbol) {
  1328.         // SLD line format:
  1329.         // <file name>|<source line>|<definition file>|<definition line>|<page number>|<value>|<type>|<data>\n
  1330.         //
  1331.         // * string <file name> can't be empty (empty is for specific "control lines" with different format)
  1332.         //
  1333.         // * unsigned <source line> when <file name> is not empty, line number (in human way starting at 1)
  1334.         // The actual format is "%d[:%d[:%d]]", first number is always line. If second number is present,
  1335.         // that's the start column (in bytes), and if also third number is present, that's end column.
  1336.         //
  1337.         // * string <definition file> where the <definition line> was defined, if empty, it's equal to <file name>
  1338.         //
  1339.         // * unsigned <definition line> explicit zero value in regular source, but inside macros
  1340.         // the <source line> keeps pointing at line emitting the macro, while this value points
  1341.         // to source with actual definitions of instructions/etc (nested macro in macro <source line>
  1342.         // still points at the top level source which initiated it).
  1343.         // The format is again "%d[:%d[:%d]]" same as <source line>, optionally including the columns data.
  1344.         //
  1345.         // * int <value> is not truncated to page range, but full 16b Z80 address or even 32b value (equ)
  1346.         //
  1347.         // * string <data> content depends on char <type>:
  1348.         // 'T' = instruction Trace, empty data
  1349.         // 'D' = EQU symbol, <data> is the symbol name ("label")
  1350.         // 'F' = function label, <data> is the symbol name
  1351.         // 'Z' = device (memory model) changed, <data> has special custom formatting
  1352.         //
  1353.         // 'Z' device <data> format:
  1354.         // pages.size:<page size>,pages.count:<page count>,slots.count:<slots count>[,slots.adr:<slot0 adr>,...,<slotLast adr>]
  1355.         // unsigned <page size> is also any-slot size in current version.
  1356.         // unsigned <page count> and <slots count> define how many pages/slots there are
  1357.         // uint16_t <slotX adr> is starting address of slot memory region in Z80 16b addressing
  1358.         //
  1359.         // specific lines (<file name> string was empty):
  1360.         // |SLD.data.version|<version number>
  1361.         // <version number> is SLD file format version, currently should be 0
  1362.         // ||<anything till EOL>
  1363.         // comment line, not to be parsed
  1364.         if (nullptr == FP_SourceLevelDebugging || !type) return;
  1365.         if (nullptr == symbol) symbol = WriteToSld_noSymbol;
  1366.         const char* macroFN = DefinitionPos.filename && strcmp(DefinitionPos.filename, CurSourcePos.filename) ?
  1367.                                                         DefinitionPos.filename : "";
  1368.         WriteToSldFile_TextFilePos(sldMessage_sourcePos, CurSourcePos);
  1369.         WriteToSldFile_TextFilePos(sldMessage_definitionPos, DefinitionPos);
  1370.         snprintf(sldMessage, LINEMAX, "%s|%s|%s|%s|%d|%d|%c|%s\n",
  1371.                                 CurSourcePos.filename, sldMessage_sourcePos, macroFN, sldMessage_definitionPos,
  1372.                                 pageNum, value, type, symbol);
  1373.         fputs(sldMessage, FP_SourceLevelDebugging);
  1374. }
  1375.  
  1376. /////// Breakpoints list (for different emulators)
  1377. static FILE* FP_BreakpointsFile = nullptr;
  1378. static EBreakpointsFile breakpointsType;
  1379. static int breakpointsCounter;
  1380.  
  1381. void OpenBreakpointsFile(const char* filename, const EBreakpointsFile type) {
  1382.         if (nullptr == filename || !filename[0]) {
  1383.                 Error("empty filename", filename, EARLY);
  1384.                 return;
  1385.         }
  1386.         if (FP_BreakpointsFile) {
  1387.                 Error("breakpoints file was already opened", nullptr, EARLY);
  1388.                 return;
  1389.         }
  1390.         if (!FOPEN_ISOK(FP_BreakpointsFile, filename, "w")) {
  1391.                 Error("Error opening file", filename, FATAL);
  1392.         }
  1393.         breakpointsCounter = 0;
  1394.         breakpointsType = type;
  1395. }
  1396.  
  1397. static void CloseBreakpointsFile() {
  1398.         if (!FP_BreakpointsFile) return;
  1399.         fclose(FP_BreakpointsFile);
  1400.         FP_BreakpointsFile = nullptr;
  1401. }
  1402.  
  1403. void WriteBreakpoint(const aint val) {
  1404.         if (!FP_BreakpointsFile) {
  1405.                 if (warningNotSuppressed()) Warning("breakpoints file was not specified");
  1406.                 return;
  1407.         }
  1408.         ++breakpointsCounter;
  1409.         switch (breakpointsType) {
  1410.                 case BPSF_UNREAL:
  1411.                         check16u(val);
  1412.                         fprintf(FP_BreakpointsFile, "x0=0x%04X\n", val&0xFFFF);
  1413.                         break;
  1414.                 case BPSF_ZESARUX:
  1415.                         if (1 == breakpointsCounter) fputs(" --enable-breakpoints ", FP_BreakpointsFile);
  1416.                         if (100 < breakpointsCounter) {
  1417.                                 Warning("Maximum amount of 100 breakpoints has been already reached, this one is ignored");
  1418.                                 break;
  1419.                         }
  1420.                         check16u(val);
  1421.                         fprintf(FP_BreakpointsFile, "--set-breakpoint %d \"PC=%d\" ", breakpointsCounter, val&0xFFFF);
  1422.                         break;
  1423.         }
  1424. }
  1425.  
  1426. //eof sjio.cpp
  1427.