Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

+104
View File
@@ -0,0 +1,104 @@
# Local CMOC compiler patches
`cmoc-debug-metadata.patch` is an original VCC Plus extension to CMOC 0.1.100,
modified November 3, 2026 and licensed GPL-3.0-or-later. It is applied to the ignored build copy by
`tools/toolchain/build.py`; the pinned upstream snapshot and its checksums stay
unchanged.
With `-fno-omit-frame-pointer`, the compiler writes `* VCCDBG1 {…}` JSON comments
into retained assembly/listings. Metadata comes from resolved compiler types and
declarations, not a C-source text parser. It contains:
- function entry, frame-ready body and epilogue boundaries;
- lexical block ranges, including `for`-statement scopes;
- signedness, storage size, array dimensions, member offsets and pointer types;
- explicit `floatingFormat` tags: `coco-basic-40` for Color BASIC/native 5-byte floats and `ieee754-binary32-be` for MC6839 single precision;
- linker symbols for globals/static locals and U-relative offsets for parameters
and ordinary locals.
The boundaries are zero-byte assembler labels. They can inhibit some assembly
optimizations in debug builds; default/release compiler invocations emit neither
the comments nor these labels. No instructions or data bytes are introduced by
the metadata. The compiler runtime manifest records `vccDebugMetadata: 1`.
The app accepts metadata only from objects/listings/linker maps verified against
the same frozen sources and final executable. Inspection additionally checks
live mapped code and uses the debugger's atomic, non-I/O memory snapshot. Frame
locals require `-O0` as well as the preserved frame pointer and are unavailable in assembly-only functions, alternative calling
conventions, prologues/epilogues, or builds without a preserved U frame. Unsupported
floating-point formats and recursively truncated types remain explicitly
unavailable. Legacy metadata without `floatingFormat` is accepted but not decoded by guessing from storage size. Known format tags must agree with storage size; a genuine double-precision type is not tagged as supported. CMOC 0.1.100 currently lowers source-level `double` to `float`, so that alias carries the selected single-precision format. Expressions do not execute guest code or modify memory.
To regenerate the patch, edit a separate copy of the upstream source and produce
a unified diff with `a/src/…` and `b/src/…` paths. Verify that applying it to a fresh
copy succeeds and that ordinary optimized builds retain their original bytes.
## Indexed byte arithmetic and comparisons
`cmoc-indexed-byte-subtraction.patch` corrects three peephole rules in the build copy of CMOC 0.1.100 (modified November 7, 2026, GPL-3.0-or-later). On the 6809, B is the low byte of D. A byte load or negation can change the effective address of a later B- or D-indexed operand, including an indirect one. The subtraction and comparison rules now keep the original instruction order in those cases. The rules that remove a stack push also guard operands whose address would change with the stack pointer or an index side effect. Ordinary immediate substitutions remain available.
The [guest regression](../../../tests/toolchain/indexed-subtraction/qualification.c) exercises `184 - heights[i]` with runtime indices, variable bases, byte wraparound, both operand orders and equality/inequality against an array element. The [runner](../../../tests/toolchain/indexed-subtraction/check.py) checks the output against host-calculated expectations on MC6809 and HD6309 at `-O0` and `-O2`. It also runs as part of `tools/toolchain/check.py --rom`. Packaged runtimes identify the change with `vccIndexedByteSubtractionFix: 1` in their manifest.
## Indexed byte loads in function arguments
`cmoc-indexed-argument-load.patch` (November 11, 2026, GPL-3.0-or-later)
corrects `removeUselessLdaOrLdb` in the CMOC 0.1.100 build copy. The rule used
to remove an index reload from `LDB index; LDX #array; LDB D,X`, although B is
the low byte of D and is needed to select the loaded byte. Consecutive indexed
function arguments could therefore use the preceding argument's value as an
array subscript. The rule now uses the existing instruction-effects analysis
to preserve B dependencies in both intervening and final loads, including
indirect B/D-indexed operands. It also checks the actual operand for
predecrement/postincrement side effects. Independent overwritten loads remain
eligible for removal.
The [target regression](../../../tests/toolchain/indexed-arguments/qualification.c)
passes adjacent elements from two arrays at runtime indices 0 and 2, using
byte indices, word indices and pointer bases, with distinct surrounding
sentinels. Its [runner](../../../tests/toolchain/indexed-arguments/check.py)
executes `--coco --no-relocate --switch=jump` binaries at `-O0` and `-O2` on
MC6809 and HD6309; it is included in `tools/toolchain/check.py --rom`.
The [rule check](../../../tests/toolchain/indexed-arguments/check-rule.py)
links the actual built compiler objects and checks dependency/side-effect guards
as well as safe removals. See the [qualification record](../../../docs/development/CMOC_INDEXED_ARGUMENT_LOAD.md).
Packaged runtimes identify the change with `vccIndexedArgumentLoadFix: 1`.
## Logical negation of integer results
`cmoc-add-zero-flags.patch` (November 7, 2026, GPL-3.0-or-later) corrects CMOC 0.1.100's general peephole optimizer. CMOC emits `ADDD #0` to set the flags for a word-sized comparison with zero. A function can return 1 in D with Z still set from clearing A. Removing the add before the `tfrZtoB` helper made `!getReady()` return 1 in that case. The patch removes the general rule's unproven add-zero deletions and byte-test substitutions. The separate optimizations for recognized load/compare/branch sequences still run.
The [guest regression](../../../tests/toolchain/logical-negation.c) prints actual results for zero, widened unsigned bytes and 16-bit values. Run `tools/toolchain/check.py --rom` with a local CoCo 3 ROM to check those results at `-O0` and `-O2` on MC6809 and HD6309. Rebuilt app toolchains record `vccAddZeroFlagsFix: 1` in the manifest.
## Explicit before-directory disk allocation
`writecocofile-before-dir.patch` (November 4, 2026, GPL-3.0-or-later) adds
`--allocate-before-dir` as an explicit choice of the existing forward allocator.
It starts at granule zero, skips occupied granules, and continues above the
directory track if necessary. It does not imply a strict below-directory limit.
The last allocation option wins, as with the existing choices.
`build.py` applies it only to the build copy. `build-runtime.py` records
`vccWriteCoCoFileBeforeDir: 1`. The original CoCo Letters Makefile uses this option;
its former recipe-removal patch is retired and the vendored game matches upstream.
Runtime verification checks allocation order, byte-identical default behavior,
file readback, and spillover beyond the lower half of the disk.
## LWASM project input boundary
The native Assembly workspace passes `--project-inputs` when invoking LWASM.
`lwtools-project-inputs.patch` (November 5, 2026, GPL-3.0-or-later) constrains
source and binary input reads to regular files inside the physical working
directory. It checks each open, including binary data reopened during emission.
The companion `--project-map=FILE` records physical source paths, physical
one-based lines, sections, offsets and original instruction bytes. Macro
expansions, data directives, synthesized 6800/convenience operations and
OS-9 calls cannot become source breakpoints. The Swift client verifies final
DECB bytes after relocation. A project map requested with `--6809` also
rejects source pragmas that change that target.
The app supplies an isolated, symlink-free copy of the source snapshot. Other
invocations retain ordinary LWASM path behavior. Custom Make recipes execute
as user-supplied build commands and have a separate trust boundary.
Rebuild and stage the native runtime with `build-runtime.py` before packaging
the workspace. The runtime manifest records `vccLWASMProjectInputs: 1`;
older assemblers reject the required option.
@@ -0,0 +1,57 @@
--- a/src/ASMText2.cpp
+++ b/src/ASMText2.cpp
@@ -1517,8 +1517,9 @@
}
-// Remove AND, OR, MUL or ADD operations if we can show that
-// they will not change performance of the program.
+// ADD #0 can be an explicit condition-code test. Leave it to rules that
+// prove which flags the surrounding instructions produce and consume.
+// In particular, a called runtime helper may read the flags on entry.
bool
ASMText::removeAndOrMulAddSub(size_t index)
{
@@ -1588,42 +1589,6 @@
commentOut(index, "optim: removeAndOrMulAddSub case 5");
madeChanges = true;
}
- } else if ((instr == "ADDA") || (instr == "ADDB") || (instr == "ADDD")) {
- if ((instr[3] == 'A' && simulator.regs.accum.a.known && simulator.regs.accum.a.val == 0) &&
- (instr[3] == 'B' && simulator.regs.accum.b.known && simulator.regs.accum.b.val == 0) &&
- (instr[3] == 'D' && simulator.regs.accum.dknown() && simulator.regs.accum.dval() == 0)) {
- // We know that A, B or D are zero, so change to a LD
- const Element &e1 = elements[index + 1];
- if (e1.type != INSTR || !isBasicBlockEndingInstruction(e1)) {
- char newInstr[8];
- snprintf(newInstr, sizeof(newInstr), "LD%s", instr.c_str() + 3);
- replaceWithInstr(index, newInstr, oper, "optim: removeAndOrMulAddSub case 6");
- madeChanges = true;
- }
- } else if (extractConstantLiteral(e.fields[1], val)) {
- // We know that the operand is a constant 0 and the side effects are not valued,
- // so we can comment it out
- const Element &e1 = elements[index + 1];
- if (val == 0 && (e1.type == INSTR && !isBasicBlockEndingInstruction(e1))) {
- InsEffects effects(e1);
- if (!(effects.read & CC)) {
- commentOut(index, "optim: removeAndOrMulAddSub case 7");
- madeChanges = true;
- }
- } else if (val == 0 && e1.type == INSTR && isBasicBlockEndingInstruction(e1) &&
- (((instr[3] == 'D') && (simulator.regs.accum.a.known && simulator.regs.accum.a.val == 0)) ||
- (instr[3] == 'B'))) {
- // ADDD #0 and A is definitely zero or ADDB #0 so replace with TSTB
- replaceWithInstr(index, "TSTB", "", "optim: removeAndOrMulAddSub case 8");
- madeChanges = true;
- } else if (val == 0 && e1.type == INSTR && isBasicBlockEndingInstruction(e1) &&
- (((instr[3] == 'D') && (simulator.regs.accum.b.known && simulator.regs.accum.b.val == 0)) ||
- (instr[3] == 'A'))) {
- // ADDD #0 and B is definitely zero or ADDA #0 so replace with TSTA
- replaceWithInstr(index, "TSTA", "", "optim: removeAndOrMulAddSub case 9");
- madeChanges = true;
- }
- }
} else if ((instr == "LEAX") && (oper == "D,X")) {
if (simulator.regs.accum.dknown() && simulator.regs.accum.dval() == 0) {
commentOut(index, "optim: removeAndOrMulAddSub case 10");
@@ -0,0 +1,230 @@
--- a/src/Declaration.cpp
+++ b/src/Declaration.cpp
@@ -15,6 +15,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+#include "VCCDebug.h"
#include "Declaration.h"
#include "TranslationUnit.h"
@@ -334,6 +335,8 @@
bool canBeStaticInit = (initializationExpr && initializationExpr->isStaticallyInitializable(*getTypeDesc()));
if (canBeStaticInit != withStaticInitializer)
return true; // nothing to do
+
+ if (isGlobal()) VCCDebug::variable(out, *this, "", "");
if (withStaticInitializer)
{
--- a/src/ForStmt.cpp
+++ b/src/ForStmt.cpp
@@ -15,6 +15,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+#include "VCCDebug.h"
#include "ForStmt.h"
#include "TranslationUnit.h"
@@ -115,6 +116,8 @@
//cerr << "pushing ForStmt scope:\n";
pushScopeIfExists();
+ const string debugBegin = getScope() && VCCDebug::enabled() ? VCCDebug::label() : "", debugEnd = getScope() && VCCDebug::enabled() ? VCCDebug::label() : "";
+ VCCDebug::scope(out, getScope(), debugBegin, debugEnd);
TranslationUnit &tu = TranslationUnit::instance();
string bodyLabel = TranslationUnit::instance().generateLabel('L');
@@ -128,6 +131,7 @@
tu.popBreakableLabels();
//cerr << "popping ForStmt scope:\n";
+ if (getScope() && VCCDebug::enabled()) out.emitLabel(debugEnd);
popScopeIfExists();
return cs;
}
--- a/src/FunctionDef.cpp
+++ b/src/FunctionDef.cpp
@@ -15,6 +15,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+#include "VCCDebug.h"
#include "FunctionDef.h"
#include "Scope.h"
@@ -853,11 +854,23 @@
functor.emitComments(out);
}
+ // VCC Plus: exact compiler-resolved body/scope boundaries, before epilogue.
+ const string debugBody = VCCDebug::enabled() ? VCCDebug::label() : "", debugEnd = VCCDebug::enabled() ? VCCDebug::label() : "";
+ if (VCCDebug::enabled()) out.emitComment("VCCDBG1 {\"kind\":\"function\",\"name\":" + VCCDebug::quote(functionId)
+ + ",\"location\":" + VCCDebug::quote(getLineNo())
+ + ",\"symbol\":" + VCCDebug::quote(functionLabel)
+ + ",\"begin\":" + VCCDebug::quote(debugBody) + ",\"end\":" + VCCDebug::quote(debugEnd)
+ + ",\"frame\":" + (needStackFrame && !isAssemblyOnly() && callConvention == DEFAULT_CMOC_CALL_CONV
+ && TranslationUnit::instance().getFramePointerOption() == FramePointerOption::KEEP_ALL
+ && TranslationUnit::instance().hasUnoptimizedDebugStorage() ? "true" : "false") + "}");
+
// Generate code for the body:
TranslationUnit::instance().setCurrentFunctionEndLabel(endLabel);
TranslationUnit::instance().pushScope(const_cast<Scope *>(getScope())); // const_cast should be removed...
+ VCCDebug::scope(out, getScope(), debugBody, debugEnd);
bool success = bodyStmts->emitCode(out, false);
+ if (VCCDebug::enabled()) out.emitLabel(debugEnd);
out.emitLabel(endLabel, "end of " + functionId + "()");
if (!asmOnly && callConvention == GCC6809_CALL_CONV && getTypeSize() == 2)
--- a/src/TranslationUnit.cpp
+++ b/src/TranslationUnit.cpp
@@ -2573,3 +2573,6 @@
irFile << "}\n"; // main JSON object
return true;
}
+
+// VCC Plus: optimized stores/register reuse cannot claim stable C locals.
+bool TranslationUnit::hasUnoptimizedDebugStorage() const { return params.optimizationLevel == 0; }
--- a/src/TranslationUnit.h
+++ b/src/TranslationUnit.h
@@ -194,6 +194,7 @@
bool isRelocatabilitySupported() const;
FramePointerOption getFramePointerOption() const;
+ bool hasUnoptimizedDebugStorage() const;
// Called during parsing, right after the parser recognized the #pragma directive.
// May change some fields of this TranslationUnit object.
--- a/src/TreeSequence.cpp
+++ b/src/TreeSequence.cpp
@@ -15,6 +15,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+#include "VCCDebug.h"
#include "TreeSequence.h"
#include "TranslationUnit.h"
@@ -141,6 +142,8 @@
const bool isCommaExpr = !!dynamic_cast<const CommaExpr *>(this);
pushScopeIfExists();
+ const string debugBegin = getScope() && VCCDebug::enabled() ? VCCDebug::label() : "", debugEnd = getScope() && VCCDebug::enabled() ? VCCDebug::label() : "";
+ VCCDebug::scope(out, getScope(), debugBegin, debugEnd);
bool success = true;
for (vector<Tree *>::const_iterator it = sequence.begin(); it != sequence.end(); it++)
@@ -178,6 +181,7 @@
}
}
+ if (getScope() && VCCDebug::enabled()) out.emitLabel(debugEnd);
popScopeIfExists();
return success;
--- /dev/null
+++ b/src/VCCDebug.h
@@ -0,0 +1,101 @@
+// VCC Plus compiler debug extension. SPDX-License-Identifier: GPL-3.0-or-later
+// Metadata comments and labels occupy no guest memory. Never infer C storage
+// or type layout from source text: use the compiler's resolved declarations.
+#ifndef VCC_DEBUG_H
+#define VCC_DEBUG_H
+#include "ASMText.h"
+#include "Declaration.h"
+#include "Scope.h"
+#include "TranslationUnit.h"
+#include "ClassDef.h"
+#include <sstream>
+#include <iomanip>
+namespace VCCDebug {
+inline bool enabled() { return TranslationUnit::instance().getFramePointerOption() == FramePointerOption::KEEP_ALL; }
+inline std::string arrayType(const TypeDesc *, const std::vector<uint16_t> &, unsigned);
+inline std::string quote(const std::string &s) {
+ std::ostringstream o; o << '"';
+ for (unsigned char c : s) {
+ if (c == '"' || c == '\\') o << '\\' << c;
+ else if (c < 32) o << "\\u00" << std::hex << std::setw(2) << std::setfill('0') << unsigned(c) << std::dec;
+ else o << c;
+ }
+ o << '"'; return o.str();
+}
+inline std::string type(const TypeDesc *td, unsigned depth = 0) {
+ std::ostringstream o;
+ const int size = td->type == FUNCTION_TYPE || td->type == VOID_TYPE || (td->type == ARRAY_TYPE && td->numArrayElements == TypeDesc::NO_DIMENSION) ? 0 : TranslationUnit::instance().getTypeSize(*td);
+ o << "{\"name\":" << quote(td->toString()) << ",\"size\":" << (size < 0 ? 0 : size);
+ if (depth > 5) o << ",\"kind\":\"unsupported\"";
+ else if (td->type == BYTE_TYPE || td->type == WORD_TYPE || td->isLong())
+ o << ",\"kind\":\"integer\",\"signed\":" << (td->isSigned ? "true" : "false");
+ else if (td->isReal()) {
+ auto &tu = TranslationUnit::instance();
+ const char *format = "unsupported";
+ if (!td->isDouble() && tu.isFloatingPointSupported()) {
+ if (tu.getFloatingPointLibrary() == FloatingPointLibrary::MC6839_LIB && size == 4)
+ format = "ieee754-binary32-be";
+ else if (size == 5 && (tu.getFloatingPointLibrary() == FloatingPointLibrary::NATIVE_LIB
+ || tu.getTargetPlatform() == COCO_BASIC || tu.getTargetPlatform() == DRAGON))
+ format = "coco-basic-40";
+ }
+ o << ",\"kind\":\"floating\",\"floatingFormat\":" << quote(format);
+ }
+ else if (td->type == POINTER_TYPE)
+ o << ",\"kind\":\"pointer\",\"element\":" << type(td->pointedTypeDesc, depth + 1);
+ else if (td->type == ARRAY_TYPE && td->numArrayElements != TypeDesc::NO_DIMENSION)
+ o << ",\"kind\":\"array\",\"count\":" << td->numArrayElements << ",\"element\":" << type(td->pointedTypeDesc, depth + 1);
+ else if (td->type == CLASS_TYPE) {
+ const ClassDef *cl = TranslationUnit::instance().getClassDef(td->className);
+ o << ",\"kind\":\"aggregate\",\"members\":[";
+ if (cl) for (size_t i=0;i<cl->getNumDataMembers();++i) {
+ auto m = cl->getDataMember(i);
+ if (i) o << ',';
+ auto dims = m->getArrayDimensions(); m->getTypeDesc()->appendDimensions(dims);
+ o << "{\"name\":" << quote(m->getName()) << ",\"offset\":" << cl->getDataMemberOffset(i, NULL)
+ << ",\"type\":" << (dims.empty() ? type(m->getTypeDesc(), depth+1) : arrayType(m->getTypeDesc(), dims, depth+1)) << '}';
+ }
+ o << ']';
+ } else o << ",\"kind\":\"unsupported\"";
+ o << '}'; return o.str();
+}
+inline std::string arrayType(const TypeDesc *original, const std::vector<uint16_t> &dims, unsigned depth) {
+ const TypeDesc *td=original;
+ while (td->type == ARRAY_TYPE) td=td->pointedTypeDesc;
+ std::string result=type(td, depth+1);
+ size_t size=TranslationUnit::instance().getTypeSize(*td);
+ for (auto it=dims.rbegin();it!=dims.rend();++it) {
+ size *= *it;
+ std::ostringstream o; o << "{\"name\":" << quote(original->toString())
+ << ",\"kind\":\"array\",\"size\":" << size << ",\"count\":" << *it << ",\"element\":" << result << '}';
+ result=o.str();
+ }
+ return result;
+}
+inline std::string declarationType(const Declaration &decl) {
+ return decl.getTypeDesc()->type == ARRAY_TYPE ? arrayType(decl.getTypeDesc(), decl.arrayDimensions, 0) : type(decl.getTypeDesc());
+}
+inline std::string label() { return ".vcc.debug." + TranslationUnit::instance().generateLabel('L'); }
+inline void variable(ASMText &out, const Declaration &d, const std::string &begin, const std::string &end) {
+ if (!enabled() || d.isExtern || d.getVariableId().empty() || d.getVariableId()[0] == '$') return;
+ uint16_t size=0; if (!d.getVariableSizeInBytes(size) || !size) return;
+ std::ostringstream o; o << "VCCDBG1 {\"kind\":\"variable\",\"name\":" << quote(d.getVariableId())
+ << ",\"location\":" << quote(d.getLineNo()) << ",\"type\":" << declarationType(d)
+ << ",\"begin\":" << quote(begin) << ",\"end\":" << quote(end)
+ << ",\"static\":" << (d.isStatic() ? "true" : "false");
+ if (d.isGlobal() || d.isLocalStatic()) o << ",\"symbol\":" << quote(d.getLabel());
+ else o << ",\"offset\":" << d.getFrameDisplacement();
+ o << '}'; out.emitComment(o.str());
+}
+inline void scope(ASMText &out, const Scope *s, const std::string &begin, const std::string &end) {
+ if (!enabled() || !s) return;
+ class Visitor : public Scope::DeclarationFunctor {
+ ASMText &out; const std::string &begin, &end;
+ public:
+ Visitor(ASMText &o, const std::string &b, const std::string &e):out(o),begin(b),end(e){}
+ bool operator()(Declaration &d) override { variable(out,d,begin,end); return true; }
+ } visit(out,begin,end);
+ out.emitLabel(begin); s->iterateDeclarations(visit,false);
+}
+}
+#endif
@@ -0,0 +1,45 @@
--- a/src/ASMText2.cpp
+++ b/src/ASMText2.cpp
@@ -4952,29 +4952,31 @@
// Look for this:
-// LDB {foo} ; {bar} involves not pre/post-increment, e.g., LDB ,S+
-// LDX/LEAX {bar} ; {bar} does not involve B, e.g., LDX B,U
-// LDB {baz}
-// Remove the first LDB.
+// LDB {foo} ; no pre/post-increment side effects
+// LDX/LEAX {bar} ; must not read B, including D-indexed operands
+// LDB {baz} ; must not read the previous B in its effective address
+// Remove the first LDB only when its value and side effects are unused.
//
bool
ASMText::removeUselessLdaOrLdb(size_t index)
{
if (! isInstrAnyArg(index, "LDB"))
return false;
- const string &arg = elements[index].fields[0];
- if (startsWith(arg, ",-") || endsWith(arg, "+")) // if pre/post increment
- return false;
+ if (isInstrWithPreDecrOrPostIncr(index))
+ return false; // Removing the load must not remove an index/stack update.
size_t otherLoad = findNextInstrBeforeLabel(index + 1);
if (! isInstrAnyArg(otherLoad, "LDX") && ! isInstrAnyArg(otherLoad, "LEAX"))
return false;
- const string &otherLoadArg = elements[otherLoad].fields[1];
- if (startsWith(otherLoadArg, "B,"))
- return false; // we have "B,reg" as the arg to LDX/LEAX, so previous LDB is useful
+ // B is also the low byte of D. Use the common instruction-effects
+ // analysis for both direct and indirect accumulator-indexed operands.
+ if (InsEffects(elements[otherLoad]).read & B)
+ return false;
size_t secondLdAcc = findNextInstrBeforeLabel(otherLoad + 1);
if (! isInstrAnyArg(secondLdAcc, "LDB"))
return false;
-
+ if (InsEffects(elements[secondLdAcc]).read & B)
+ return false; // The overwritten value may still select the byte to load.
+
// Apply the optimization.
commentOut(index, "optim: removeUselessLdaOrLdb (removed LDB b/c later LDB)");
return true;
@@ -0,0 +1,68 @@
--- a/src/ASMText2.cpp
+++ b/src/ASMText2.cpp
@@ -4159,16 +4159,27 @@
}
+// B is the low half of D. Both direct and indirect accumulator-indexed
+// addresses can therefore depend on the value of B before a rewrite.
+static bool
+usesBInAddress(const string &operand)
+{
+ return startsWith(operand, "B,") || startsWith(operand, "D,")
+ || startsWith(operand, "[B,") || startsWith(operand, "[D,");
+}
+
+
// Look for: LDB foo; PSHS B; LDB bar; CMPB ,S+.
// Change to: LDB bar; CMPB foo.
-// LDB args must not involve S.
+// Swapping the two reads must preserve their offsets and index registers.
//
bool
ASMText::removePushBFromLdbPushLdbCmp(size_t index)
{
if (!isInstrAnyArg(index, "LDB"))
return false;
- if (elements[index].fields[1].find(",S") != string::npos)
+ if (usesBInAddress(elements[index].fields[1]) || isInstrWithPreDecrOrPostIncr(index)
+ || elements[index].fields[1].find(",S") != string::npos)
return false;
size_t pushIndex = findNextInstrBeforeLabel(index + 1);
@@ -4178,7 +4189,8 @@
size_t secondLoadIndex = findNextInstrBeforeLabel(pushIndex + 1);
if (!isInstrAnyArg(secondLoadIndex, "LDB"))
return false;
- if (elements[secondLoadIndex].fields[1].find(",S") != string::npos)
+ if (usesBInAddress(elements[secondLoadIndex].fields[1]) || isInstrWithPreDecrOrPostIncr(secondLoadIndex)
+ || elements[secondLoadIndex].fields[1].find(",S") != string::npos)
return false;
size_t cmpIndex = findNextInstrBeforeLabel(secondLoadIndex + 1);
@@ -4440,6 +4452,13 @@
if (!isInstr(subIndex, "SUBB", ",S+"))
return false;
+ // NEGB changes B before the load's address is used, and removing the
+ // push changes S. Keep the original sequence when either matters.
+ const string &operand = elements[ldbIndex].fields[1];
+ if (usesBInAddress(operand) || operand.find(",S") != string::npos
+ || isInstrWithPreDecrOrPostIncr(ldbIndex))
+ return false;
+
// Apply the optimization.
commentOut(index, "optim: removePushBBeforeSubB"); // remove PSHS
elements[subIndex].fields[0] = "ADDB";
@@ -4833,6 +4852,11 @@
if (isInstrWithPreDecrOrPostIncr(addb))
return false;
+ // Swapping the operands also changes which value of B is available
+ // when each effective address is evaluated.
+ if (usesBInAddress(elements[index].fields[1]) || usesBInAddress(elements[addb].fields[1]))
+ return false;
+
// Apply the optimization.
const string ldbArg = elements[index].fields[1];
elements[index].fields[1] = elements[addb].fields[1];
@@ -0,0 +1,362 @@
--- a/lwasm/input.c
+++ b/lwasm/input.c
@@ -26,6 +26,9 @@
*/
#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
@@ -65,8 +68,40 @@
void *data;
int data2;
char *filespec;
+ const char *source_path;
+ int source_line;
struct input_stack_node *stack;
};
+
+/* VCC Plus native assembly builds run in a private, immutable snapshot.
+ * Resolve the target before opening it, including the second binary-include
+ * read during emission. Ordinary LWASM invocations retain upstream behavior. */
+static char *project_root;
+
+void input_restrict_to_project(void)
+{
+ project_root = realpath(".", NULL);
+ if (!project_root)
+ lw_error("Cannot resolve assembly project folder.\n");
+}
+
+FILE *input_fopen(const char *path)
+{
+ if (project_root)
+ {
+ char resolved[PATH_MAX];
+ struct stat info;
+ size_t length = strlen(project_root);
+ if (!realpath(path, resolved))
+ return NULL;
+ if (strncmp(project_root, resolved, length) || resolved[length] != '/')
+ lw_error("Assembly input leaves the project snapshot: %s\n", path);
+ if (stat(resolved, &info) != 0 || !S_ISREG(info.st_mode))
+ lw_error("Assembly input is not a regular file: %s\n", path);
+ return fopen(resolved, "rb");
+ }
+ return fopen(path, "rb");
+}
static char *make_filename(char *p, char *f)
{
@@ -110,7 +145,7 @@
}
/* this adds real filenames that were opened to a list */
-void input_add_to_resource_list(asmstate_t *as, const char *s)
+static const char *input_add_to_resource_list(asmstate_t *as, const char *s)
{
struct ifl *ifl;
@@ -127,6 +162,7 @@
ifl_head = ifl;
ifl -> fn = lw_strdup(s);
}
+ return ifl -> fn;
}
void input_init(asmstate_t *as)
@@ -155,6 +191,12 @@
char *dn, *dp;
// int o;
+ if (as->project_map_file && project_root)
+ {
+ char resolved[PATH_MAX];
+ if (realpath(fn, resolved))
+ IS->source_path = input_add_to_resource_list(as, resolved + strlen(project_root) + 1);
+ }
dn = lw_strdup(fn);
lw_stack_push(as -> includelist, dn);
@@ -186,6 +228,8 @@
struct input_stack *t;
t = lw_alloc(sizeof(struct input_stack));
+ t -> source_path = NULL;
+ t -> source_line = 0;
t -> filespec = lw_strdup(s);
t -> type = input_type_string;
@@ -204,6 +248,8 @@
char *p, *p2;
t = lw_alloc(sizeof(struct input_stack));
+ t -> source_path = NULL;
+ t -> source_line = 0;
t -> filespec = lw_strdup(s);
for (s2 = s; *s2 && (*s2 != ':'); s2++)
@@ -238,7 +284,7 @@
if (input_isabsolute(s))
{
/* absolute path */
- IS -> data = fopen(s, "rb");
+ IS -> data = input_fopen(s);
debug_message(as, 1, "Opening (abs) %s", s);
if (!IS -> data && !IGNOREERROR)
{
@@ -257,7 +303,7 @@
p = lw_stack_top(as -> file_dir);
p2 = make_filename(p, s);
debug_message(as, 1, "Open: (cd) %s\n", p2);
- IS -> data = fopen(p2, "rb");
+ IS -> data = input_fopen(p2);
if (IS -> data)
{
input_pushpath(as, p2);
@@ -274,7 +320,7 @@
{
p2 = make_filename(p, s);
debug_message(as, 1, "Open (sp): %s\n", p2);
- IS -> data = fopen(p2, "rb");
+ IS -> data = input_fopen(p2);
if (IS -> data)
{
input_pushpath(as, p2);
@@ -300,7 +346,7 @@
if (s[0] == '-' && s[1] == '\0')
IS -> data = stdin;
else
- IS -> data = fopen(s, "rb");
+ IS -> data = input_fopen(s);
if (!IS -> data)
{
@@ -328,7 +374,7 @@
debug_message(as, 2, "Open file (st abs) %s", s);
if (as -> flags & FLAG_DEPEND)
printf("%s\n", s);
- fp = fopen(s, "rb");
+ fp = input_fopen(s);
if (!fp)
{
return NULL;
@@ -343,7 +389,7 @@
p = lw_stack_top(as -> file_dir);
p2 = make_filename(p ? p : "", s);
debug_message(as, 2, "Open file (st cd) %s", p2);
- fp = fopen(p2, "rb");
+ fp = input_fopen(p2);
if (fp)
{
if (as -> flags & FLAG_DEPEND)
@@ -362,7 +408,7 @@
{
p2 = make_filename(p, s);
debug_message(as, 2, "Open file (st ip) %s", p2);
- fp = fopen(p2, "rb");
+ fp = input_fopen(p2);
if (fp)
{
if (as -> flags & FLAG_DEPEND)
@@ -471,6 +517,7 @@
if (eol)
{
s = lw_strdup(linebuff);
+ IS->source_line++;
return s;
}
}
@@ -537,6 +584,15 @@
default:
lw_error("Problem reading from unknown input type\n");
return NULL;
+ }
+}
+
+void input_project_location(asmstate_t *as, line_t *line)
+{
+ if (IS && IS->type != input_type_string)
+ {
+ line->project_source = IS->source_path;
+ line->project_line = IS->source_line;
}
}
--- a/lwasm/input.h
+++ b/lwasm/input.h
@@ -32,6 +32,9 @@
void input_stack_push(asmstate_t *as, input_stack_entry *se);
input_stack_entry *input_stack_pop(asmstate_t *as, int magic, int (*fn)(input_stack_entry *e, void *data), void *data);
+void input_restrict_to_project(void);
+FILE *input_fopen(const char *path);
+void input_project_location(asmstate_t *as, line_t *line);
void input_init(asmstate_t *as);
void input_openstring(asmstate_t *as, char *s, char *str);
void input_open(asmstate_t *as, char *s);
--- a/lwasm/list.c
+++ b/lwasm/list.c
@@ -24,6 +24,7 @@
#include <string.h>
#include <lw_alloc.h>
+#include <lw_error.h>
#include <lw_string.h>
#include "lwasm.h"
@@ -489,3 +490,43 @@
if (of && of != stdout)
fclose(of);
}
+
+/* VCC Plus project source map. Keep the normal human-readable listing intact.
+ * Physical file lines are captured at input; macro strings have no file identity.
+ * The client still validates original object bytes, link relocations and the BIN. */
+void do_project_map(asmstate_t *as)
+{
+ FILE *out = fopen(as->project_map_file, "w");
+ line_t *line;
+ const int synthetic = lwasm_insn_is6800 | lwasm_insn_is6809conv |
+ lwasm_insn_is6309conv | lwasm_insn_isemuext;
+ if (!out) lw_error("Cannot write project instruction map.\n");
+ for (line = as->line_head; line; line = line->next)
+ {
+ const char *section = line->csect ? line->csect->name : "";
+ lw_expr_t address;
+ int i;
+ if (!line->project_source || !line->emitted_opcode || line->insn < 0 ||
+ (instab[line->insn].flags & synthetic) || !strcmp(instab[line->insn].opcode, "os9") ||
+ line->outputl < 1 || line->outputl > 8 || line->outputl != line->len ||
+ strpbrk(line->project_source, "\t\r\n") || strpbrk(section, "\t\r\n"))
+ continue;
+ address = lw_expr_copy(line->addr);
+ as->exportcheck = 1;
+ as->csect = line->csect;
+ lwasm_reduce_expr(as, address);
+ as->exportcheck = 0;
+ if (lw_expr_istype(address, lw_expr_type_int))
+ {
+ int value = lw_expr_intval(address);
+ if (value >= 0 && value <= 65535)
+ {
+ fprintf(out, "%s\t%d\t%s\t%04X\t", line->project_source, line->project_line, section, value);
+ for (i = 0; i < line->outputl; ++i) fprintf(out, "%02X", line->output[i]);
+ fputc('\n', out);
+ }
+ }
+ lw_expr_destroy(address);
+ }
+ if (fclose(out)) lw_error("Cannot finish writing project instruction map.\n");
+}
--- a/lwasm/lwasm.c
+++ b/lwasm/lwasm.c
@@ -504,6 +504,7 @@
void lwasm_emitop(line_t *cl, int opc)
{
+ cl->emitted_opcode = 1;
if (cl->cycle_base == 0)
lwasm_cycle_update_count(cl, opc); /* only call first time, never on postbyte */
--- a/lwasm/lwasm.h
+++ b/lwasm/lwasm.h
@@ -278,6 +278,9 @@
struct line_s
{
+ const char *project_source;
+ int project_line;
+ int emitted_opcode;
lw_expr_t addr; // assembly address of the line
lw_expr_t daddr; // data address of the line (os9 only)
lw_expr_t phase; // the "phase" setting (assumed address for assembly)
@@ -440,6 +443,8 @@
sectiontab_t *sections; // section table
exportlist_t *exportlist; // list of exported symbols
importlist_t *importlist; // list of imported symbols
+ char *project_map_file;
+ int project_6809_only;
char *list_file; // name of file to list to
char *symbol_dump_file; // name of file to dump symbol table to
int tabwidth; // tab width in list file
--- a/lwasm/main.c
+++ b/lwasm/main.c
@@ -71,6 +71,8 @@
{ "6800compat", 0x200, 0, 0, "Enable 6800 compatibility instructions, equivalent to --pragma=6800compat" },
{ "no-output", 0x105, 0, 0, "Inhibit creation of output file" },
{ "no-warn", 0x109, "FLAG", 0, "Suppress warnings of the specified type" },
+ { "project-map", 0x10d, "FILE", 0, "Write physical source instruction locations for a project snapshot" },
+ { "project-inputs", 0x10c, 0, 0, "Restrict all assembly inputs to the current project folder" },
{ "error-format", 0x10b, "STYLE", 0, "Error output style: lwasm (default), gcc, vs" },
{ 0 }
};
@@ -82,6 +84,12 @@
switch (key)
{
+ case 0x10d:
+ as->project_map_file = lw_strdup(arg);
+ break;
+ case 0x10c:
+ input_restrict_to_project();
+ break;
case 'I':
lw_stringlist_addstring(as -> include_list, arg);
break;
@@ -333,6 +341,7 @@
void do_output(asmstate_t *as);
void do_symdump(asmstate_t *as);
void do_list(asmstate_t *as);
+void do_project_map(asmstate_t *as);
void do_map(asmstate_t *as);
lw_expr_t lwasm_evaluate_special(int t, void *ptr, void *priv);
lw_expr_t lwasm_evaluate_var(char *var, void *priv);
@@ -391,6 +400,7 @@
asmstate.output_file = lw_strdup("a.out");
}
+ asmstate.project_6809_only = asmstate.project_map_file && (asmstate.pragmas & PRAGMA_6809);
input_init(&asmstate);
for (passnum = 0; passlist[passnum].fn; passnum++)
@@ -450,6 +460,7 @@
}
do_symdump(&asmstate);
do_list(&asmstate);
+ if (asmstate.project_map_file) do_project_map(&asmstate);
do_map(&asmstate);
if (asmstate.testmode_errorcount > 0) exit(1);
--- a/lwasm/pass1.c
+++ b/lwasm/pass1.c
@@ -115,12 +115,15 @@
memset(cl, 0, sizeof(line_t));
cl -> outputl = -1;
cl -> linespec = lw_strdup(input_curspec(as));
+ if (as->project_map_file) input_project_location(as, cl);
cl -> prev = as -> line_tail;
cl -> insn = -1;
cl -> as = as;
cl -> inmod = as -> inmod;
cl -> csect = as -> csect;
cl -> pragmas = as -> pragmas;
+ if (as->project_6809_only && !(cl->pragmas & PRAGMA_6809))
+ lwasm_register_error2(as, cl, E_6309_INVALID, "Source changes the selected 6809 project target.");
cl -> context = as -> context;
cl -> hasoperand = 1; // default: assume operand present; cleared by inherent insns
cl -> ltext = lw_strdup(line);
--- a/lwasm/pseudo.c
+++ b/lwasm/pseudo.c
@@ -1662,7 +1662,7 @@
FILE *fp;
int c, i;
- fp = fopen(l -> lstr, "rb");
+ fp = input_fopen(l -> lstr);
if (!fp)
{
lwasm_register_error2(as, l, E_FILE_OPEN, "%s", "(emit)!");
@@ -0,0 +1,32 @@
--- a/src/writecocofile.cpp
+++ b/src/writecocofile.cpp
@@ -1,3 +1,8 @@
+/* VCC Plus modification, November 4, 2026: support an explicit
+ --allocate-before-dir option using the existing forward allocator.
+ This modification is licensed GPL-3.0-or-later.
+*/
+
/* writecocofile.cpp - A tool to write native files to a CoCo DECB disk image.
Copyright (C) 2003-2026 Pierre Sarrazin <http://sarrazip.com/>
@@ -874,6 +879,8 @@
"--kill|-k Kill the designated file.\n"
"--read|-r Read instead of writing. Refuses to overwrite existing native file.\n"
"--stdout|-s Like --read, but print file contents on standard out.\n"
+ "--allocate-before-dir Allocate from granule zero (the default), preferring space\n"
+ " before the directory, then continuing above it if needed.\n"
"--allocate-after-dir When adding a file, allocate granules after the directory track,\n"
" then continue allocating below that track if needed.\n"
"--allocate-from-end When adding a file, allocate granules from the end.\n"
@@ -1376,6 +1383,11 @@
granuleAllocator.reset(new BackwardGranuleAllocator());
continue;
}
+ if (curopt == "--allocate-before-dir")
+ {
+ granuleAllocator.reset(new ForwardGranuleAllocator());
+ continue;
+ }
if (curopt == "--allocate-after-dir")
{
granuleAllocator.reset(new PostDirTrackGranuleAllocator());