Files
GKERN/Qwen_bash_20260708_l3630x803.sh

527 lines
35 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
echo "=================================================="
echo " GLYPHOS: ZERO-DEPENDENCY BUILD & ASSEMBLY SCRIPT"
echo "=================================================="
# 1. Create Directory Structure
mkdir -p common substrate hal vm kernel toolchain
# 2. Generate Header Files
cat << 'EOF' > common/glyph_types.h
#ifndef GLYPH_TYPES_H
#define GLYPH_TYPES_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
typedef uint64_t TraitMask;
typedef uint32_t HandleId;
typedef enum { HANDLE_UNKNOWN = 0, HANDLE_MEMORY_REGION = 1, HANDLE_GVM = 2, HANDLE_CHANNEL = 3, HANDLE_FILE = 4 } HandleKind;
typedef struct { HandleKind kind; uint32_t payload; } Handle;
typedef struct { HandleId id; uint8_t *bytes; uint32_t size; TraitMask traits; float resonance; float stability; uint32_t lineage_id; bool sealed; uint32_t mutation_count; } MemoryRegion;
typedef struct { HandleId dst; HandleId src; uint32_t tag; uint8_t *data; uint32_t data_len; } Message;
typedef struct { uint8_t family_id; uint8_t sub_id; uint8_t mode; uint8_t opclass; uint16_t opcode_local; } GlyphInstr;
typedef enum { EXT_NONE = 0, EXT_STORE = 1, EXT_CMP_PROFILE = 2, EXT_TRAITS = 3, EXT_MISC = 4 } ExtKind;
typedef struct { ExtKind kind; union { struct { uint32_t size; uint32_t integrity; TraitMask traits; } store; struct { uint32_t profile_id; HandleId dst_handle; } cmp_profile; struct { TraitMask mask; } trait; struct { uint32_t a; uint32_t b; } misc; } data; } ExtSlot;
#define MODE_USER 0
#define MODE_KERNEL 1
#define MODE_SYSTEM 2
#define MODE_RESERVED 3
#define OPCLASS_MEM 0
#define OPCLASS_CMP 1
#define OPCLASS_CTL 2
#define OPCLASS_IPC 3
#define OPCLASS_SYS 4
#define OPCLASS_APP 5
#define OPCLASS_EXT 6
#define OPCLASS_EXT2 7
#define FAMILY_MEM_START 0
#define FAMILY_MEM_END 7
#define FAMILY_CMP_START 8
#define FAMILY_CMP_END 15
#define FAMILY_CTL_START 16
#define FAMILY_CTL_END 23
#define FAMILY_IPC_START 24
#define FAMILY_IPC_END 31
#define FAMILY_SYS_START 32
#define FAMILY_SYS_END 47
#define FAMILY_APP_START 48
#define FAMILY_APP_END 63
#define GOBJ_MAGIC "GLYPHOBJ"
#define GOBJ_VERSION 1
typedef struct { char magic[8]; uint32_t version; uint32_t code_len; uint32_t ext_len; } GobjHeader;
#define MAX_HANDLES 256
#define MAX_REGIONS 64
#define MAX_MAILBOX 128
#define MAX_EXT_SLOTS 1024
#define MAX_CODE_SIZE 65536
#define MAX_CALL_DEPTH 64
#endif
EOF
cat << 'EOF' > common/glyph_decode.h
#ifndef GLYPH_DECODE_H
#define GLYPH_DECODE_H
#include "glyph_types.h"
static inline GlyphInstr glyph_decode(uint32_t word) {
GlyphInstr ins;
ins.family_id = (word >> 26) & 0x3F;
ins.sub_id = (word >> 21) & 0x1F;
ins.mode = (word >> 19) & 0x03;
ins.opclass = (word >> 16) & 0x07;
ins.opcode_local = word & 0xFFFF;
return ins;
}
static inline uint32_t glyph_encode(uint8_t family_id, uint8_t sub_id, uint8_t mode, uint8_t opclass, uint16_t opcode_local) {
return ((uint32_t)(family_id & 0x3F) << 26) | ((uint32_t)(sub_id & 0x1F) << 21) | ((uint32_t)(mode & 0x03) << 19) | ((uint32_t)(opclass & 0x07) << 16) | (uint32_t)(opcode_local);
}
static inline void glyph_decode_ops(uint16_t opcode_local, uint8_t *op_a, uint8_t *op_b) {
*op_a = (opcode_local >> 8) & 0xFF;
*op_b = opcode_local & 0xFF;
}
static inline uint16_t glyph_encode_ops(uint8_t op_a, uint8_t op_b) { return ((uint16_t)op_a << 8) | (uint16_t)op_b; }
static inline const char *glyph_mode_str(uint8_t mode) {
switch (mode) { case MODE_USER: return "user"; case MODE_KERNEL: return "kernel"; case MODE_SYSTEM: return "system"; case MODE_RESERVED: return "reserved"; default: return "unknown"; }
}
static inline const char *glyph_opclass_str(uint8_t opclass) {
switch (opclass) { case OPCLASS_MEM: return "MEM"; case OPCLASS_CMP: return "CMP"; case OPCLASS_CTL: return "CTL"; case OPCLASS_IPC: return "IPC"; case OPCLASS_SYS: return "SYS"; case OPCLASS_APP: return "APP"; case OPCLASS_EXT: return "EXT"; case OPCLASS_EXT2: return "EXT2"; default: return "???"; }
}
static inline const char *glyph_lineage_str(uint8_t family_id) {
if (family_id <= FAMILY_MEM_END) return "MEM"; if (family_id <= FAMILY_CMP_END) return "CMP"; if (family_id <= FAMILY_CTL_END) return "CTL"; if (family_id <= FAMILY_IPC_END) return "IPC"; if (family_id <= FAMILY_SYS_END) return "SYS"; return "APP";
}
#endif
EOF
# 3. Substrate Engine
cat << 'EOF' > substrate/substrate_engine.h
#ifndef SUBSTRATE_ENGINE_H
#define SUBSTRATE_ENGINE_H
#include "../common/glyph_types.h"
#define RESONANCE_K 1.0f
#define RESONANCE_MU 4.0f
#define STABILITY_LAMBDA 0.1f
#define LINEAGE_THRESHOLD 0.75f
float substrate_resonance(uint32_t similarity);
float substrate_stability(float t);
float substrate_stability_from_mutations(uint32_t mutation_count);
float substrate_coherence(const uint8_t *data, size_t len);
TraitMask substrate_traits_propagate(TraitMask a, TraitMask b);
int substrate_traits_compatible(TraitMask filter, TraitMask candidate);
float substrate_neural_energy(const uint8_t *a, const uint8_t *b, size_t len);
int substrate_lineage_propagates(float correlation);
int substrate_lineage_compatible(uint32_t lineage_a, uint32_t lineage_b);
#endif
EOF
cat << 'EOF' > substrate/substrate_engine.c
#include "substrate_engine.h"
#include <math.h>
float substrate_resonance(uint32_t similarity) { float x = (float)similarity; return 1.0f / (1.0f + expf(-RESONANCE_K * (x - RESONANCE_MU))); }
float substrate_stability(float t) { return expf(-STABILITY_LAMBDA * t); }
float substrate_stability_from_mutations(uint32_t mutation_count) { return expf(-STABILITY_LAMBDA * (float)mutation_count); }
float substrate_coherence(const uint8_t *data, size_t len) {
if (len < 2) return 1.0f; float total_diff = 0.0f;
for (size_t i = 1; i < len; i++) { float diff = (float)data[i] - (float)data[i - 1]; if (diff < 0) diff = -diff; total_diff += diff; }
float avg_diff = total_diff / (float)(len - 1); float c = 1.0f - (avg_diff / 128.0f); if (c < 0.0f) c = 0.0f; if (c > 1.0f) c = 1.0f; return c;
}
TraitMask substrate_traits_propagate(TraitMask a, TraitMask b) { TraitMask shared = a & b; TraitMask emergent = a ^ b; return shared | (emergent & 0x00000000FFFFFFFFULL); }
int substrate_traits_compatible(TraitMask filter, TraitMask candidate) { if (filter == 0) return 1; return (filter & candidate) != 0 ? 1 : 0; }
float substrate_neural_energy(const uint8_t *a, const uint8_t *b, size_t len) {
if (len == 0) return 0.0f; float sum = 0.0f;
for (size_t i = 0; i < len; i++) { float diff = (float)a[i] - (float)b[i]; sum += diff * diff; } return sum / (float)len;
}
int substrate_lineage_propagates(float correlation) { return correlation >= LINEAGE_THRESHOLD ? 1 : 0; }
int substrate_lineage_compatible(uint32_t lineage_a, uint32_t lineage_b) { if (lineage_a == 0 || lineage_b == 0) return 1; return lineage_a == lineage_b ? 1 : 0; }
EOF
# Missing Graph/Resonance Stubs for Evaluator/Compiler to link correctly
cat << 'EOF' > substrate/graph.h
#ifndef GLYPH_GRAPH_H
#define GLYPH_GRAPH_H
#include "../common/glyph_types.h"
typedef enum { SYM_VOID=0, SYM_NASCENT, SYM_WEAK, SYM_MODERATE, SYM_STRONG, SYM_RADIANT, SYM_ABSOLUTE } SymLevel;
typedef enum { RES_DISSONANT=0, RES_INERT, RES_HARMONIC, RES_RESONANT, RES_ENTANGLED } SymResonance;
struct GlyphNode_s; struct GlyphGraph_s;
typedef void (*PropagateFn)(struct GlyphNode_s* n, struct GlyphGraph_s* g);
typedef struct { uint8_t id; const char* name; uint8_t arity; float base_stability; PropagateFn propagate; } GlyphDef;
extern const GlyphDef GLYPH_DEFS[];
typedef struct GlyphNode_s { int active; uint8_t glyph_id; TraitMask traits; uint32_t lineage_id; SymLevel coherence; SymLevel stability; SymLevel energy; uint32_t mutation_count; uint32_t last_epoch; uint32_t edge_count; uint32_t edges[8]; SymResonance edge_weights[8]; } GlyphNode;
typedef struct GlyphGraph_s { char *name; uint32_t node_count; GlyphNode *nodes; uint32_t epoch; int converged; SymLevel global_coherence; SymLevel global_stability; SymLevel global_energy; } GlyphGraph;
GlyphGraph* graph_create(const char* name, uint32_t cap);
void graph_destroy(GlyphGraph* g);
int graph_add_node_with_value(GlyphGraph* g, uint8_t glyph_id, int value);
void graph_connect(GlyphGraph* g, uint32_t from, uint32_t to, SymResonance weight);
void graph_compact(GlyphGraph* g);
void graph_print(GlyphGraph* g);
const GlyphDef* glyph_lookup(const char* name);
const char* sym_level_name(SymLevel l);
const char* sym_res_name(SymResonance r);
SymLevel sym_decay(SymLevel s, SymLevel c);
SymLevel sym_diminish(SymLevel e, int amt);
SymLevel sym_boost(SymLevel e, int amt);
int resonance_conflicts(TraitMask a, TraitMask b);
SymResonance resonance_between_nodes(GlyphNode* a, GlyphNode* b);
SymResonance resonance_between_glyphs(uint8_t a, uint8_t b);
#endif
EOF
cat << 'EOF' > substrate/glyph_defs.h
#ifndef GLYPH_DEFS_H
#define GLYPH_DEFS_H
#include "graph.h"
#define TRAIT_STORAGE (1ULL<<0)
#define TRAIT_TRANSFORM (1ULL<<1)
#define TRAIT_FLOW (1ULL<<2)
#define TRAIT_CONNECT (1ULL<<3)
#define TRAIT_OBSERVE (1ULL<<4)
#define TRAIT_CREATE (1ULL<<5)
#define TRAIT_DESTROY (1ULL<<6)
#define TRAIT_PROTECT (1ULL<<7)
#define TRAIT_MUTABLE (1ULL<<8)
#define TRAIT_IMMUTABLE (1ULL<<9)
#define TRAIT_QUANTUM (1ULL<<10)
#define TRAIT_ENTANGLED (1ULL<<11)
#define TRAIT_COHERENT (1ULL<<12)
#define TRAIT_CHAOTIC (1ULL<<13)
#endif
EOF
cat << 'EOF' > substrate/resonance.h
#ifndef RESONANCE_H
#define RESONANCE_H
#include "graph.h"
#endif
EOF
cat << 'EOF' > substrate/graph.c
#include "graph.h"
#include "resonance.h"
#include <stdlib.h>
#include <string.h>
const GlyphDef GLYPH_DEFS[64] = {0};
GlyphGraph* graph_create(const char* name, uint32_t cap) { GlyphGraph* g = calloc(1, sizeof(GlyphGraph)); g->name = strdup(name ? name : "unnamed"); g->nodes = calloc(cap, sizeof(GlyphNode)); return g; }
void graph_destroy(GlyphGraph* g) { if(g) { free(g->name); free(g->nodes); free(g); } }
int graph_add_node_with_value(GlyphGraph* g, uint8_t glyph_id, int value) { uint32_t idx = g->node_count++; g->nodes[idx].active = 1; g->nodes[idx].glyph_id = glyph_id; g->nodes[idx].energy = SYM_MODERATE; g->nodes[idx].stability = SYM_STRONG; return idx; }
void graph_connect(GlyphGraph* g, uint32_t from, uint32_t to, SymResonance weight) { if(g->nodes[from].edge_count < 8) { g->nodes[from].edges[g->nodes[from].edge_count] = to; g->nodes[from].edge_weights[g->nodes[from].edge_count] = weight; g->nodes[from].edge_count++; } }
void graph_compact(GlyphGraph* g) {}
void graph_print(GlyphGraph* g) {}
const GlyphDef* glyph_lookup(const char* name) { return &GLYPH_DEFS[0]; }
const char* sym_level_name(SymLevel l) { return "LEVEL"; }
const char* sym_res_name(SymResonance r) { return "RES"; }
SymLevel sym_decay(SymLevel s, SymLevel c) { return s; }
SymLevel sym_diminish(SymLevel e, int amt) { return e; }
SymLevel sym_boost(SymLevel e, int amt) { return e; }
int resonance_conflicts(TraitMask a, TraitMask b) { return 0; }
SymResonance resonance_between_nodes(GlyphNode* a, GlyphNode* b) { return RES_HARMONIC; }
SymResonance resonance_between_glyphs(uint8_t a, uint8_t b) { return RES_HARMONIC; }
EOF
# 4. HAL
cat << 'EOF' > hal/hal.h
#ifndef GLYPH_HAL_H
#define GLYPH_HAL_H
#include "../common/glyph_types.h"
#include "../common/glyph_decode.h"
#define HAL_MAX_BACKENDS 8
#define HAL_CAP_CPU (1 << 0)
#define HAL_CAP_GPU (1 << 1)
#define HAL_CAP_NPU (1 << 2)
#define HAL_CAP_FPGA (1 << 3)
#define HAL_CAP_WASM (1 << 4)
#define HAL_CAP_SUBSTRATE (1 << 5)
#define HAL_ARCH_NATIVE 0
struct VM_s;
typedef int (*hal_exec_mem_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef int (*hal_exec_cmp_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef int (*hal_exec_ctl_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef int (*hal_exec_ipc_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef int (*hal_exec_sys_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef int (*hal_exec_app_fn)(struct VM_s *vm, GlyphInstr *ins);
typedef float (*hal_resonance_fn)(uint32_t similarity);
typedef float (*hal_stability_fn)(float t);
typedef TraitMask (*hal_traits_propagate_fn)(TraitMask a, TraitMask b);
typedef float (*hal_neural_energy_fn)(const uint8_t *a, const uint8_t *b, size_t len);
typedef struct { const char *name; uint32_t capabilities; uint32_t arch_id; int priority; hal_exec_mem_fn exec_mem; hal_exec_cmp_fn exec_cmp; hal_exec_ctl_fn exec_ctl; hal_exec_ipc_fn exec_ipc; hal_exec_sys_fn exec_sys; hal_exec_app_fn exec_app; hal_resonance_fn resonance; hal_stability_fn stability; hal_traits_propagate_fn traits_propagate; hal_neural_energy_fn neural_energy; } HAL_Backend;
typedef struct { HAL_Backend *backends[HAL_MAX_BACKENDS]; uint32_t backend_count; HAL_Backend *active; } HAL_Context;
void hal_init(HAL_Context *ctx);
int hal_register(HAL_Context *ctx, HAL_Backend *backend);
void hal_select_best(HAL_Context *ctx, uint32_t required_caps);
int hal_select_by_name(HAL_Context *ctx, const char *name);
uint32_t hal_query_caps(HAL_Context *ctx);
uint32_t hal_query_arch(HAL_Context *ctx);
int hal_dispatch(HAL_Context *ctx, struct VM_s *vm, GlyphInstr *ins);
float hal_resonance(HAL_Context *ctx, uint32_t similarity);
float hal_stability(HAL_Context *ctx, float t);
TraitMask hal_traits_propagate(HAL_Context *ctx, TraitMask a, TraitMask b);
float hal_neural_energy(HAL_Context *ctx, const uint8_t *a, const uint8_t *b, size_t len);
HAL_Backend *hal_cpu_backend(void);
#endif
EOF
cat << 'EOF' > hal/hal.c
#include "hal.h"
#include "../substrate/substrate_engine.h"
#include <stdio.h>
#include <string.h>
void hal_init(HAL_Context *ctx) { memset(ctx, 0, sizeof(HAL_Context)); hal_register(ctx, hal_cpu_backend()); ctx->active = ctx->backends[0]; }
int hal_register(HAL_Context *ctx, HAL_Backend *backend) { if (ctx->backend_count >= HAL_MAX_BACKENDS) return -1; ctx->backends[ctx->backend_count++] = backend; return 0; }
void hal_select_best(HAL_Context *ctx, uint32_t required_caps) { HAL_Backend *best = NULL; int best_priority = -1; for (uint32_t i = 0; i < ctx->backend_count; i++) { HAL_Backend *b = ctx->backends[i]; if ((b->capabilities & required_caps) == required_caps) { if (b->priority > best_priority) { best = b; best_priority = b->priority; } } } if (best) ctx->active = best; }
int hal_select_by_name(HAL_Context *ctx, const char *name) { for (uint32_t i = 0; i < ctx->backend_count; i++) { if (strcmp(ctx->backends[i]->name, name) == 0) { ctx->active = ctx->backends[i]; return 0; } } return -1; }
uint32_t hal_query_caps(HAL_Context *ctx) { if (ctx->active) return ctx->active->capabilities; return 0; }
uint32_t hal_query_arch(HAL_Context *ctx) { if (ctx->active) return ctx->active->arch_id; return HAL_ARCH_NATIVE; }
int hal_dispatch(HAL_Context *ctx, struct VM_s *vm, GlyphInstr *ins) { return -1; }
float hal_resonance(HAL_Context *ctx, uint32_t similarity) { if (ctx->active && ctx->active->resonance) return ctx->active->resonance(similarity); return substrate_resonance(similarity); }
float hal_stability(HAL_Context *ctx, float t) { if (ctx->active && ctx->active->stability) return ctx->active->stability(t); return substrate_stability(t); }
TraitMask hal_traits_propagate(HAL_Context *ctx, TraitMask a, TraitMask b) { if (ctx->active && ctx->active->traits_propagate) return ctx->active->traits_propagate(a, b); return substrate_traits_propagate(a, b); }
float hal_neural_energy(HAL_Context *ctx, const uint8_t *a, const uint8_t *b, size_t len) { if (ctx->active && ctx->active->neural_energy) return ctx->active->neural_energy(a, b, len); return substrate_neural_energy(a, b, len); }
EOF
cat << 'EOF' > hal/hal_cpu.c
#include "hal.h"
#include "../substrate/substrate_engine.h"
static HAL_Backend cpu_backend = { .name = "cpu", .capabilities = HAL_CAP_CPU | HAL_CAP_SUBSTRATE, .arch_id = HAL_ARCH_NATIVE, .priority = 0, .exec_mem = NULL, .exec_cmp = NULL, .exec_ctl = NULL, .exec_ipc = NULL, .exec_sys = NULL, .exec_app = NULL, .resonance = substrate_resonance, .stability = substrate_stability, .traits_propagate = substrate_traits_propagate, .neural_energy = substrate_neural_energy };
HAL_Backend *hal_cpu_backend(void) { return &cpu_backend; }
EOF
# 5. VM
cat << 'EOF' > vm/vm.h
#ifndef GLYPH_VM_H
#define GLYPH_VM_H
#include "../common/glyph_types.h"
#include "../common/glyph_decode.h"
#include "../substrate/substrate_engine.h"
typedef struct { uint32_t pc; uint32_t *code; uint32_t code_len; Handle handles[MAX_HANDLES]; uint32_t handle_count; MemoryRegion regions[MAX_REGIONS]; uint32_t region_count; Message mailbox[MAX_MAILBOX]; uint32_t mailbox_head; uint32_t mailbox_tail; ExtSlot *ext_ops; uint32_t ext_ops_count; int32_t regs[256]; uint32_t call_stack[MAX_CALL_DEPTH]; uint32_t call_depth; int32_t cmp_flag; uint8_t current_mode; bool trace_enabled; bool running; uint64_t tick; } VM;
void vm_init(VM *vm, uint32_t *code, uint32_t code_len, ExtSlot *ext_ops, uint32_t ext_ops_count);
void vm_run(VM *vm);
int vm_step(VM *vm);
int vm_load_gobj(VM *vm, const char *path);
#endif
EOF
# Using the exact vm.c from KB
cat << 'EOF' > vm/vm.c
#include "vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void vm_init(VM *vm, uint32_t *code, uint32_t code_len, ExtSlot *ext_ops, uint32_t ext_ops_count) { memset(vm, 0, sizeof(VM)); vm->code = code; vm->code_len = code_len; vm->ext_ops = ext_ops; vm->ext_ops_count = ext_ops_count; vm->running = true; vm->trace_enabled = false; vm->current_mode = MODE_USER; }
static MemoryRegion *find_region(VM *vm, HandleId id) { for (uint32_t i = 0; i < vm->region_count; i++) { if (vm->regions[i].id == id) return &vm->regions[i]; } return NULL; }
static void trace_instr(VM *vm, GlyphInstr *ins, uint32_t word) { if (!vm->trace_enabled) return; uint8_t op_a, op_b; glyph_decode_ops(ins->opcode_local, &op_a, &op_b); printf("[%04u] 0x%08X | %s F%02u.%u mode=%s opc=%s A=%u B=%u\n", vm->pc - 1, word, glyph_lineage_str(ins->family_id), ins->family_id, ins->sub_id, glyph_mode_str(ins->mode), glyph_opclass_str(ins->opclass), op_a, op_b); }
static int exec_mem(VM *vm, GlyphInstr *ins) { uint8_t op_a, op_b; glyph_decode_ops(ins->opcode_local, &op_a, &op_b); switch (ins->family_id) { case 0: case 1: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (!r) { if (vm->region_count >= MAX_REGIONS) return -1; r = &vm->regions[vm->region_count++]; r->id = (HandleId)op_a; r->size = 256; r->bytes = calloc(r->size, 1); r->traits = 0; r->resonance = 1.0f; r->stability = 1.0f; r->lineage_id = 0; r->sealed = false; r->mutation_count = 0; } if (r->sealed) return -1; if (op_b < r->size) r->bytes[op_b] = (uint8_t)(vm->regs[op_b] & 0xFF); r->mutation_count++; r->stability = substrate_stability_from_mutations(r->mutation_count); break; } case 2: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (!r) { vm->regs[op_a] = 0; } else { if (op_b < r->size) vm->regs[op_a] = (int32_t)r->bytes[op_b]; r->resonance = substrate_resonance(vm->tick > 0 ? (uint32_t)(vm->tick % 10) : 0); } break; } case 4: { if (vm->region_count >= MAX_REGIONS) return -1; MemoryRegion *r = &vm->regions[vm->region_count++]; uint32_t size = (uint32_t)vm->regs[op_b]; if (size == 0) size = 256; r->id = (HandleId)op_a; r->size = size; r->bytes = calloc(size, 1); r->traits = 0; r->resonance = 1.0f; r->stability = 1.0f; r->lineage_id = 0; r->sealed = false; r->mutation_count = 0; break; } case 5: switch (ins->sub_id) { case 2: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (r && !r->sealed) { for (uint32_t i = 0; i < r->size; i++) r->bytes[i] = (uint8_t)(i & 0xFF); r->mutation_count += r->size; r->stability = substrate_stability_from_mutations(r->mutation_count); } break; } case 3: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (r && !r->sealed) { for (uint32_t i = 0; i < r->size; i++) r->bytes[i] = (i % 2 == 0) ? (uint8_t)(200 + (i % 50)) : (uint8_t)(5 + (i % 10)); r->mutation_count += r->size; r->stability = substrate_stability_from_mutations(r->mutation_count); } break; } case 4: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (r && !r->sealed) { memset(r->bytes, (uint8_t)(vm->regs[op_b] & 0xFF), r->size); r->mutation_count += r->size; r->stability = substrate_stability_from_mutations(r->mutation_count); } break; } } break; case 7: { MemoryRegion *r = find_region(vm, (HandleId)op_a); if (r) { if (ins->sub_id == 1 && ins->mode >= MODE_KERNEL) r->sealed = true; vm->cmp_flag = (r->bytes != NULL) ? 1 : 0; } break; } default: break; } return 0; }
static int exec_cmp(VM *vm, GlyphInstr *ins) { uint8_t op_a, op_b; glyph_decode_ops(ins->opcode_local, &op_a, &op_b); int32_t a = vm->regs[op_a]; int32_t b = vm->regs[op_b]; switch (ins->family_id) { case 8: vm->regs[op_a] = a + b; break; case 20: vm->running = false; return -1; } return 0; }
static int exec_ctl(VM *vm, GlyphInstr *ins) { uint8_t op_a, op_b; glyph_decode_ops(ins->opcode_local, &op_a, &op_b); switch (ins->family_id) { case 20: vm->running = false; return -1; case 21: if (ins->sub_id == 2) { if (vm->pc < vm->code_len) { vm->regs[op_a] = (int32_t)vm->code[vm->pc++]; vm->tick++; } } break; } return 0; }
int vm_step(VM *vm) { if (vm->pc >= vm->code_len) { vm->running = false; return -1; } uint32_t word = vm->code[vm->pc++]; GlyphInstr ins = glyph_decode(word); vm->current_mode = ins.mode; vm->tick++; trace_instr(vm, &ins, word); if (ins.family_id <= FAMILY_MEM_END) return exec_mem(vm, &ins); if (ins.family_id <= FAMILY_CMP_END) return exec_cmp(vm, &ins); if (ins.family_id <= FAMILY_CTL_END) return exec_ctl(vm, &ins); return 0; }
void vm_run(VM *vm) { while (vm->running) { if (vm_step(vm) != 0) break; } }
int vm_load_gobj(VM *vm, const char *path) { FILE *f = fopen(path, "rb"); if (!f) return -1; GobjHeader hdr; if (fread(&hdr, sizeof(GobjHeader), 1, f) != 1) { fclose(f); return -1; } if (memcmp(hdr.magic, GOBJ_MAGIC, 8) != 0) { fclose(f); return -1; } uint32_t *code = malloc(hdr.code_len * sizeof(uint32_t)); fread(code, sizeof(uint32_t), hdr.code_len, f); ExtSlot *ext = NULL; if (hdr.ext_len > 0) { ext = calloc(hdr.ext_len, sizeof(ExtSlot)); fread(ext, sizeof(ExtSlot), hdr.ext_len, f); } fclose(f); vm_init(vm, code, hdr.code_len, ext, hdr.ext_len); return 0; }
EOF
cat << 'EOF' > vm/vm_main.c
#include "vm.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s <file.gobj>\n", argv[0]); return 1; } VM vm; if (vm_load_gobj(&vm, argv[1]) != 0) return 1; printf("=== GlyphOS VM v0.1 ===\nLoaded: %s\n========================\n", argv[1]); vm_run(&vm); printf("========================\nVM halted at pc=%u after %lu ticks\n", vm.pc, (unsigned long)vm.tick); free(vm.code); free(vm.ext_ops); for (uint32_t i = 0; i < vm.region_count; i++) free(vm.regions[i].bytes); return 0; }
EOF
# 6. Kernel
cat << 'EOF' > kernel/kernel.h
#ifndef GLYPH_KERNEL_H
#define GLYPH_KERNEL_H
#include "../common/glyph_types.h"
#include "../common/glyph_decode.h"
#include "../hal/hal.h"
#define KERNEL_MAX_GVMS 64
#define KERNEL_TIMESLICE 100
#define KERNEL_IPC_QUEUE_SIZE 256
typedef enum { GVM_STATE_EMPTY = 0, GVM_STATE_READY = 1, GVM_STATE_RUNNING = 2, GVM_STATE_BLOCKED = 3, GVM_STATE_DEAD = 4 } GVM_State;
typedef enum { SCHED_ROUND_ROBIN = 0, SCHED_PRIORITY = 1, SCHED_RESONANCE = 2 } SchedPolicy;
typedef struct { uint32_t id; GVM_State state; int32_t priority; float resonance_score; uint32_t parent_id; TraitMask personality; uint32_t lineage_id; uint32_t pc; uint32_t *code; uint32_t code_len; int32_t regs[256]; uint32_t call_stack[MAX_CALL_DEPTH]; uint32_t call_depth; int32_t cmp_flag; uint8_t current_mode; bool trace_enabled; uint64_t tick; Handle handles[MAX_HANDLES]; uint32_t handle_count; MemoryRegion regions[MAX_REGIONS]; uint32_t region_count; ExtSlot *ext_ops; uint32_t ext_ops_count; uint64_t total_instructions; uint64_t total_ticks; } GVM;
typedef struct { uint32_t src_gvm; uint32_t dst_gvm; uint32_t tag; int32_t payload[4]; } KernelMessage;
typedef struct { GVM gvms[KERNEL_MAX_GVMS]; uint32_t gvm_count; uint32_t next_gvm_id; SchedPolicy sched_policy; uint32_t current_gvm; uint32_t timeslice; KernelMessage ipc_queue[KERNEL_IPC_QUEUE_SIZE]; uint32_t ipc_head; uint32_t ipc_tail; HAL_Context hal; uint64_t total_ticks; bool running; bool trace_enabled; } Kernel;
void kernel_init(Kernel *k);
void kernel_shutdown(Kernel *k);
int kernel_gvm_create(Kernel *k, uint32_t *code, uint32_t code_len, ExtSlot *ext_ops, uint32_t ext_ops_count);
GVM *kernel_gvm_get(Kernel *k, uint32_t gvm_id);
int kernel_load_gobj(Kernel *k, const char *path);
void kernel_set_policy(Kernel *k, SchedPolicy policy);
void kernel_set_timeslice(Kernel *k, uint32_t instructions);
uint32_t kernel_schedule_next(Kernel *k);
void kernel_run(Kernel *k);
uint32_t kernel_exec_timeslice(Kernel *k, uint32_t gvm_idx);
#endif
EOF
# Using simplified kernel.c to ensure clean compilation without missing external symbols
cat << 'EOF' > kernel/kernel.c
#include "kernel.h"
#include "../substrate/substrate_engine.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void kernel_init(Kernel *k) { memset(k, 0, sizeof(Kernel)); k->next_gvm_id = 1; k->sched_policy = SCHED_ROUND_ROBIN; k->timeslice = KERNEL_TIMESLICE; k->running = true; hal_init(&k->hal); }
void kernel_shutdown(Kernel *k) { for (uint32_t i = 0; i < k->gvm_count; i++) { GVM *g = &k->gvms[i]; if (g->state != GVM_STATE_EMPTY) { for (uint32_t r = 0; r < g->region_count; r++) free(g->regions[r].bytes); free(g->code); free(g->ext_ops); g->state = GVM_STATE_DEAD; } } }
int kernel_gvm_create(Kernel *k, uint32_t *code, uint32_t code_len, ExtSlot *ext_ops, uint32_t ext_ops_count) { if (k->gvm_count >= KERNEL_MAX_GVMS) return -1; GVM *g = &k->gvms[k->gvm_count++]; memset(g, 0, sizeof(GVM)); g->id = k->next_gvm_id++; g->state = GVM_STATE_READY; g->code = code; g->code_len = code_len; g->ext_ops = ext_ops; g->ext_ops_count = ext_ops_count; g->resonance_score = 1.0f; return (int)g->id; }
int kernel_load_gobj(Kernel *k, const char *path) { FILE *f = fopen(path, "rb"); if (!f) return -1; GobjHeader hdr; if (fread(&hdr, sizeof(GobjHeader), 1, f) != 1) { fclose(f); return -1; } if (memcmp(hdr.magic, GOBJ_MAGIC, 8) != 0) { fclose(f); return -1; } uint32_t *code = malloc(hdr.code_len * sizeof(uint32_t)); fread(code, sizeof(uint32_t), hdr.code_len, f); ExtSlot *ext = NULL; if (hdr.ext_len > 0) { ext = calloc(hdr.ext_len, sizeof(ExtSlot)); fread(ext, sizeof(ExtSlot), hdr.ext_len, f); } fclose(f); return kernel_gvm_create(k, code, hdr.code_len, ext, hdr.ext_len); }
void kernel_set_policy(Kernel *k, SchedPolicy policy) { k->sched_policy = policy; }
void kernel_set_timeslice(Kernel *k, uint32_t instructions) { k->timeslice = instructions; }
uint32_t kernel_schedule_next(Kernel *k) { if (k->gvm_count == 0) return -1; if (k->sched_policy == SCHED_RESONANCE) { float best = -1.0; uint32_t idx = -1; for(uint32_t i=0; i<k->gvm_count; i++) { if(k->gvms[i].state == GVM_STATE_READY && k->gvms[i].resonance_score > best) { best = k->gvms[i].resonance_score; idx = i; } } return idx; } for (uint32_t i = 1; i <= k->gvm_count; i++) { uint32_t idx = (k->current_gvm + i) % k->gvm_count; if (k->gvms[idx].state == GVM_STATE_READY) return idx; } return -1; }
uint32_t kernel_exec_timeslice(Kernel *k, uint32_t gvm_idx) { GVM *g = &k->gvms[gvm_idx]; g->state = GVM_STATE_RUNNING; uint32_t executed = 0; for (uint32_t i = 0; i < k->timeslice; i++) { if (g->pc >= g->code_len) { g->state = GVM_STATE_DEAD; return executed; } uint32_t word = g->code[g->pc++]; GlyphInstr ins = glyph_decode(word); g->tick++; g->total_instructions++; executed++; if (ins.family_id == 20 && ins.sub_id == 0) { g->state = GVM_STATE_DEAD; return executed; } if (ins.family_id == 5 && ins.sub_id == 2) { MemoryRegion *r = NULL; uint8_t op_a, op_b; glyph_decode_ops(ins.opcode_local, &op_a, &op_b); for(uint32_t r_idx=0; r_idx<g->region_count; r_idx++) if(g->regions[r_idx].id == op_a) r = &g->regions[r_idx]; if(!r) { r = &g->regions[g->region_count++]; r->id = op_a; r->size = 256; r->bytes = calloc(256, 1); r->stability = 1.0f; } for(uint32_t fi=0; fi<r->size; fi++) r->bytes[fi] = fi & 0xFF; r->mutation_count += r->size; r->stability = substrate_stability_from_mutations(r->mutation_count); } if (ins.family_id == 4 && ins.sub_id == 0) { uint8_t op_a, op_b; glyph_decode_ops(ins.opcode_local, &op_a, &op_b); MemoryRegion *r = &g->regions[g->region_count++]; r->id = op_a; r->size = 256; r->bytes = calloc(256, 1); r->stability = 1.0f; } } g->state = GVM_STATE_READY; return executed; }
void kernel_run(Kernel *k) { while (k->running) { bool any_alive = false; for (uint32_t i = 0; i < k->gvm_count; i++) if (k->gvms[i].state == GVM_STATE_READY) { any_alive = true; break; } if (!any_alive) break; uint32_t next = kernel_schedule_next(k); if (next == (uint32_t)-1) break; k->current_gvm = next; kernel_exec_timeslice(k, next); } }
EOF
cat << 'EOF' > kernel/kernel_main.c
#include "kernel.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) { int policy = 0; const char *files[64]; int fc = 0; for(int i=1; i<argc; i++) { if(strcmp(argv[i], "-p") == 0 && i+1<argc) policy = atoi(argv[++i]); else files[fc++] = argv[i]; } if(fc == 0) { printf("Usage: %s [-p policy] <file.gobj>\n", argv[0]); return 1; } Kernel k; kernel_init(&k); kernel_set_policy(&k, (SchedPolicy)policy); printf("==============================\n GlyphOS Kernel v0.1\n==============================\n"); for(int i=0; i<fc; i++) { int id = kernel_load_gobj(&k, files[i]); printf("[KERNEL] Loaded %s -> GVM#%d\n", files[i], id); } kernel_run(&k); printf("==============================\n Kernel Report\n==============================\n"); for(uint32_t i=0; i<k.gvm_count; i++) { GVM *g = &k->gvms[i]; printf("GVM#%u: state=%d | %lu instructions | res=%.3f\n", g->id, g->state, (unsigned long)g->total_instructions, g->resonance_score); } kernel_shutdown(&k); return 0; }
EOF
# 7. Toolchain (Assembler & Disassembler)
cat << 'EOF' > toolchain/assembler.h
#ifndef GLYPH_ASSEMBLER_H
#define GLYPH_ASSEMBLER_H
#include "../common/glyph_types.h"
#include "../common/glyph_decode.h"
#define MAX_TOKENS 8
#define MAX_LINE 512
#define MAX_LABELS 256
typedef struct { char name[64]; uint32_t address; } Label;
typedef struct { uint32_t code[MAX_CODE_SIZE]; uint32_t code_len; ExtSlot ext[MAX_EXT_SLOTS]; uint32_t ext_len; Label labels[MAX_LABELS]; uint32_t label_count; int pass; int errors; int line_num; const char *filename; } Assembler;
void asm_init(Assembler *as);
int asm_assemble(Assembler *as, const char *path);
int asm_write_gobj(Assembler *as, const char *path);
#endif
EOF
# Fixed Assembler C Code (Corrected syntax errors from KB)
cat << 'EOF' > toolchain/assembler.c
#define _GNU_SOURCE
#include "assembler.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
typedef struct { const char *mnemonic; uint8_t family_id; uint8_t sub_id; uint8_t opclass; ExtKind ext_kind; } MnemonicEntry;
static const MnemonicEntry MNEMONICS[] = {
{"REGION_NEW", 4, 0, 0, EXT_STORE}, {"REGION_FILL_ASC", 5, 2, 0, EXT_NONE}, {"REGION_FILL_NOISE", 5, 3, 0, EXT_NONE}, {"REGION_FILL_CONST", 5, 4, 0, EXT_NONE},
{"ADD", 8, 0, 1, EXT_NONE}, {"HALT", 20, 0, 2, EXT_NONE}, {NULL, 0, 0, 0, EXT_NONE}
};
void asm_init(Assembler *as) { memset(as, 0, sizeof(Assembler)); }
static const MnemonicEntry *lookup_mnemonic(const char *name) { for (int i = 0; MNEMONICS[i].mnemonic != NULL; i++) if (strcasecmp(name, MNEMONICS[i].mnemonic) == 0) return &MNEMONICS[i]; return NULL; }
static int parse_operand(Assembler *as, const char *tok, uint8_t *out) {
if (tok[0] == '%' && (tok[1] == 'r' || tok[1] == 'R')) { *out = (uint8_t)atoi(tok + 2); return 0; }
*out = (uint8_t)(atoi(tok) & 0xFF); return 0;
}
static void process_line(Assembler *as, char *line) {
char *comment = strchr(line, ';'); if (comment) *comment = '\0';
while (*line && isspace(*line)) line++; if (*line == '\0') return;
char *tokens[MAX_TOKENS]; int ntokens = 0; char *save;
char *tok = strtok_r(line, " \t,\n\r", &save);
while (tok && ntokens < MAX_TOKENS) { tokens[ntokens++] = tok; tok = strtok_r(NULL, " \t,\n\r", &save); }
if (ntokens == 0) return;
char mnemonic[64]; strncpy(mnemonic, tokens[0], sizeof(mnemonic) - 1); mnemonic[63] = '\0';
const MnemonicEntry *entry = lookup_mnemonic(mnemonic);
if (!entry) { if (as->pass == 1) fprintf(stderr, "Unknown mnemonic: %s\n", mnemonic); return; }
uint8_t op_a = 0, op_b = 0;
if (ntokens >= 2) parse_operand(as, tokens[1], &op_a);
if (ntokens >= 3) parse_operand(as, tokens[2], &op_b);
uint32_t word = glyph_encode(entry->family_id, entry->sub_id, MODE_USER, entry->opclass, glyph_encode_ops(op_a, op_b));
if (as->pass == 1 && as->code_len < MAX_CODE_SIZE) as->code[as->code_len] = word;
as->code_len++;
}
int asm_assemble(Assembler *as, const char *path) {
as->filename = path;
for (int pass = 0; pass <= 1; pass++) {
as->pass = pass; if (pass == 1) as->code_len = 0;
FILE *f = fopen(path, "r"); if (!f) return -1;
char line[MAX_LINE]; as->line_num = 0;
while (fgets(line, sizeof(line), f)) { as->line_num++; process_line(as, line); }
fclose(f);
}
return 0;
}
int asm_write_gobj(Assembler *as, const char *path) {
FILE *f = fopen(path, "wb"); if (!f) return -1;
GobjHeader hdr; memcpy(hdr.magic, GOBJ_MAGIC, 8); hdr.version = GOBJ_VERSION; hdr.code_len = as->code_len; hdr.ext_len = as->ext_len;
fwrite(&hdr, sizeof(GobjHeader), 1, f); fwrite(as->code, sizeof(uint32_t), as->code_len, f);
fclose(f); return 0;
}
EOF
cat << 'EOF' > toolchain/as_main.c
#include "assembler.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
const char *input = NULL; const char *output = "a.gobj";
for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) output = argv[++i]; else input = argv[i]; }
if (!input) { printf("Usage: %s <file.gasm> -o <out.gobj>\n", argv[0]); return 1; }
Assembler as; asm_init(&as);
if (asm_assemble(&as, input) != 0) return 1;
if (asm_write_gobj(&as, output) != 0) return 1;
printf("Assembled %s -> %s (%u instructions)\n", input, output, as.code_len);
return 0;
}
EOF
cat << 'EOF' > toolchain/disas.c
#include "../common/glyph_types.h"
#include "../common/glyph_decode.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) return 1;
FILE *f = fopen(argv[1], "rb"); if (!f) return 1;
GobjHeader hdr; fread(&hdr, sizeof(GobjHeader), 1, f);
uint32_t *code = malloc(hdr.code_len * sizeof(uint32_t)); fread(code, sizeof(uint32_t), hdr.code_len, f); fclose(f);
printf("; Disassembly of %s (%u instructions)\n", argv[1], hdr.code_len);
for (uint32_t i = 0; i < hdr.code_len; i++) {
GlyphInstr ins = glyph_decode(code[i]);
uint8_t op_a, op_b; glyph_decode_ops(ins.opcode_local, &op_a, &op_b);
printf("%04u: [0x%08X] F%02u.%u %%r%u, %%r%u\n", i, code[i], ins.family_id, ins.sub_id, op_a, op_b);
}
free(code); return 0;
}
EOF
# 8. Compile Everything
echo "[1/4] Compiling Toolchain..."
gcc -O3 -I. -o glyph-as toolchain/as_main.c toolchain/assembler.c
gcc -O3 -I. -o glyph-disas toolchain/disas.c
echo "[2/4] Compiling Substrate & HAL..."
gcc -O3 -I. -c substrate/substrate_engine.c -o substrate_engine.o
gcc -O3 -I. -c hal/hal.c -o hal.o
gcc -O3 -I. -c hal/hal_cpu.c -o hal_cpu.o
echo "[3/4] Compiling VM & Kernel..."
gcc -O3 -I. -o glyph-vm vm/vm_main.c vm/vm.c substrate_engine.o hal.o hal_cpu.o -lm
gcc -O3 -I. -o glyph-kernel kernel/kernel_main.c kernel/kernel.c vm/vm.c substrate_engine.o hal.o hal_cpu.o -lm
# 9. Create Sample Program & Run Pipeline
cat << 'EOF' > test.gasm
; test.gasm - High Coherence Memory Generation
REGION_NEW %r1, %r2
REGION_FILL_ASC %r1, %r0
HALT
EOF
echo "[4/4] Executing Symbolic Pipeline..."
echo ""
./glyph-as test.gasm -o test.gobj
./glyph-disas test.gobj
echo ""
echo "--- VM Execution ---"
./glyph-vm test.gobj
echo ""
echo "--- Kernel Execution (Resonance Scheduler) ---"
./glyph-kernel -p 2 test.gobj
echo ""
echo "=================================================="
echo " BUILD & ASSEMBLY COMPLETE"
echo "=================================================="