<commit_before>/*
    Title:  An interpreter for a compact instruction set.
    Author:     <NAME>, Cambridge University Computer Laboratory

    Copyright (c) 2000
        Cambridge University Technical Services Limited

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#ifdef _WIN32_WCE
#include "winceconfig.h"
#include "wincelib.h"
#else
#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x) 0
#endif

#include "globals.h"
#include "int_opcodes.h"
#include "machine_dep.h"
#include "sys.h"
#include "profiling.h"
#include "arb.h"
#include "processes.h"
#include "run_time.h"
#include "mpoly.h"
#include "gc.h"
#include "basicio.h"
#include "timing.h"
#include "arb.h"
#include "reals.h"
#include "objsize.h"
#include "xwindows.h"
#include "foreign.h"
#include "process_env.h"
#include "network.h"
#include "basicio.h"
#include "sighandler.h"
#include "os_specific.h"
#include "diagnostics.h"
#include "polystring.h"
#include "save_vec.h"
#include "memmgr.h"

#define VERSION_NUMBER  POLY_version_number

#define arg1    (pc[0] + pc[1]*256)
#define arg2    (pc[2] + pc[3]*256)
#define arg3    (pc[4] + pc[5]*256)
#define arg4    (pc[6] + pc[7]*256)

#define True    TAGGED(1)
#define False   TAGGED(0)

#define CHECKED_REGS 2
#define UNCHECKED_REGS 0

#define EXTRA_STACK 0 // Don't need any extra - signals aren't handled on the Poly stack.

/* the amount of ML stack space to reserve for registers,
   C exception handling etc. The compiler requires us to
   reserve 2 stack-frames worth (2 * 20 words) plus whatever
   we require for the register save area. We actually reserve
   slightly more than this. SPF 3/3/97
*/
#define OVERFLOW_STACK_SIZE \
  (50 + \
   sizeof(StackObject)/sizeof(PolyWord) + \
   CHECKED_REGS + \
   UNCHECKED_REGS + \
   EXTRA_STACK)

extern StackObject *poly_stack;

class Interpreter : public MachineDependent {
public:
    Interpreter(): allocSpace(0) {}

    virtual void InitStackFrame(StackObject *stack, Handle proc, Handle arg);
    // Switch to Poly and return with the io function to call.
    virtual int SwitchToPoly(void);
    virtual void SetForRetry(int ioCall) {} // Nothing to do
    virtual void InitInterfaceVector(void);
    virtual void SetException(StackObject *stack,poly_exn *exc);
    virtual void InterruptCode(void);
    virtual int  GetIOFunctionRegisterMask(int ioCall) { raise_syscall("No register masks", 0); return 0; }
    virtual bool GetPCandSPFromContext(SIGNALCONTEXT *context, PolyWord * &sp,  POLYCODEPTR &pc)
        { return false; /* Not relevant */}
    virtual bool InRunTimeSystem(void) { return true; } // Always
    virtual void CallIO0(Handle(*ioFun)(void));
    virtual void CallIO1(Handle(*ioFun)(Handle));
    virtual void CallIO2(Handle(*ioFun)(Handle, Handle));
    virtual void CallIO3(Handle(*ioFun)(Handle, Handle, Handle));
    virtual void CallIO4(Handle(*ioFun)(Handle, Handle, Handle, Handle));
    virtual void CallIO5(Handle(*ioFun)(Handle, Handle, Handle, Handle, Handle));
    virtual Handle CallBackResult(void);
    virtual Architectures MachineArchitecture(void) { return MA_Interpreted; }

    // These next two have to be handled as special cases.  They need to jump
    // to CALL_CLOSURE to handle the cases where the functions we are tracing or
    // calling are actually IO functions and don't have code addresses.  Actually
    // we could instead make the interpreter handle small tagged integers as
    // code addresses specially.
    virtual void SetExceptionTrace(void) { ASSERT(false); }
    virtual void CallCodeTupled(void) { ASSERT(false); }

    void storetrace(POLYUNSIGNED wordsNeeded);
    LocalMemSpace *allocSpace;
};

// Do a garbage collection.
void Interpreter::storetrace(POLYUNSIGNED wordsNeeded)
{
    allocSpace = gMem.GetLargestSpace(wordsNeeded);
    if (allocSpace)
        return;
    if (! QuickGC(wordsNeeded))
    {
        fprintf(stderr,"Run out of store - interrupting console processes\n");
        processes->interrupt_console_processes();
    }
    allocSpace = gMem.GetLargestSpace(wordsNeeded);
    ASSERT(allocSpace != 0);
}

void Interpreter::InitStackFrame(StackObject *stack, Handle proc, Handle arg)
/* Initialise stack frame. */
{
    PolyObject *closure = DEREFWORDHANDLE(proc);
    POLYUNSIGNED stack_size = stack->Length();
    stack->p_space = OVERFLOW_STACK_SIZE;
    stack->p_pc = *(byte**)(closure);
    stack->p_sp  = (PolyWord*)stack + stack_size-3; /* sp */
    stack->p_nreg = CHECKED_REGS; /* exception arg and last instruction. */
    stack->p_reg[CHECKED_REGS] = PolyWord::FromUnsigned(UNCHECKED_REGS);
    stack->p_reg[0] = TAGGED(0); /* Used for exception argument. */
    stack->p_reg[1] = TAGGED(256); /* No instruction. */
    stack->p_sp  = (PolyWord*)stack + stack_size;

    /* Set up exception handler */
    /* No previous handler so point it at itself. */
    stack->p_sp--;
    *(stack->p_sp) = PolyWord::FromStackAddr(stack->p_sp);
    *(--stack->p_sp) = TAGGED(0); /* Default return address. */
    *(--stack->p_sp) = TAGGED(0); /* Default handler. */
    stack->p_hr = stack->p_sp;

    /* If this function takes an argument store it on the stack. */
    if (arg != 0) *(--stack->p_sp) = DEREFWORD(arg);

    *(--stack->p_sp) = TAGGED(0); /* Return address. */
    *(--stack->p_sp) = closure; /* Closure address */
}

int interrupt_requested = 0;
int profile_count_wanted = 0;

void Interpreter::InterruptCode(void)
/* Stop the Poly code at a suitable place. */
/* We may get an asynchronous interrupt at any time. */
{
    interrupt_requested = 1;
}


void Interpreter::SetException(StackObject *stack, poly_exn *exc)
/* Set up the stack of a process to raise an exception. */
{
    stack->p_reg[1] = TAGGED(INSTR_raise_ex);
    *(--stack->p_sp) = (PolyWord)exc; /* push exception data */
}

int Interpreter::SwitchToPoly(void)
/* (Re)-enter the Poly code from C. */
{
    register PolyWord *sp; /* Stack pointer. */
    register byte *pc; /* Program counter. */
    register PolyWord *sl; /* Stack limit register. */
    register int  li;  /* Last instruction. */
    POLYUNSIGNED tailCount;
    PolyWord *tailPtr;
    POLYUNSIGNED returnCount;
    POLYUNSIGNED storeWords;
    int instrBytes;

    RESTART: /* Load or reload the registers and run the code. */
    sp = poly_stack->p_sp; /* Reload these. */
    pc = poly_stack->p_pc;
    li = UNTAGGED(poly_stack->p_reg[1]);
    sl = (PolyWord*)poly_stack+OVERFLOW_STACK_SIZE;
    // Get the largest space available.  If we have just called storetrace because we
    // were trying to allocate but the current space wouldn't satisfy it we will now
    // have a space and the space we get here will be at least large enough so we won't loop.
    allocSpace = gMem.GetLargestSpace();
    ASSERT(allocSpace);
    if (li != 256) goto RETRY; /* Re-execute instruction if necessary. */

    for(;;){ /* Each instruction */

//        char buff[100];
        li = *pc++; /* Get next instruction. */

        RETRY:
//      sprintf(buff, "PC=%x, i=%x\n", pc, li);
//      OutputDebugString(buff);
        /* Check for stack overflow and interrupts. These can be done less
           frequently than every instruction. */
        if (sp < sl) {
            poly_stack->p_sp = sp;
            poly_stack->p_pc = pc;
            poly_stack->p_reg[1] = TAGGED(li);
            check_current_stack_size(sp);
            goto RESTART;
        }

        if (interrupt_requested) {
            interrupt_requested = 0;
            poly_stack->p_sp = sp;
            poly_stack->p_pc = pc;
            poly_stack->p_reg[1] = TAGGED(li);
            execute_pending_interrupts();
            goto RESTART;
        }

        if (profile_count_wanted) {
            add_count(pc, sp, profile_count_wanted);
            profile_count_wanted = 0;
        }

        switch(li) {

        case INSTR_enter_int: pc++; /* Skip the argument. */ break;

        case INSTR_jump_false:
            {
                PolyWord u = *sp++; /* Pop argument */
                if (u == True) { pc += 1; break; }
                /* else - false - take the jump */
            }

        case INSTR_jump: pc += *pc + 1; break;

        case INSTR_push_handler: /* Save the old handler value. */
            *(--sp) = PolyWord::FromStackAddr(poly_stack->p_hr); /* Push old handler */
            break;

        case INSTR_set_handler: /* Set up a handler */
            *(--sp) = PolyWord::FromCodePtr(pc + *pc + 1); /* Address of handler */
            poly_stack->p_hr = sp-1; /*Point to identifier about to be pushed*/
            pc += 1;
            break;

        case INSTR_del_handler: /* Delete handler retaining the result. */
            {
                PolyWord u = *sp++;
                sp = poly_stack->p_hr;
                PolyWord *t;
                while ((t = (*sp).AsStackAddr()) < sp || t > end_of_stack) sp++;
                poly_stack->p_hr = t;
                *sp = u;
                pc += *pc + 1; /* Skip the handler */
                break;
            }

        case INSTR_jump_i_false:
            if (*sp++ == True) { pc += 1; break; }
            /* else - false - take the jump */

        case INSTR_jump_i: /* Indirect jump */
            {
                pc += *pc + 1;
                /* This may jump backwards. */
                int u = arg1;
                if (u > 32767) u -= 65536;
                pc += u + 2;
                break;
            }

        case INSTR_set_handler_i: /* Set up a handler */
            {
                byte *u = pc + *pc + 1;
                *(--sp) = /* Address of handler */
                    PolyWord::FromCodePtr(u + u[0] + u[1]*256 + 2);
                poly_stack->p_hr = sp-1;
                pc += 1;
                break;
            }

        case INSTR_del_handler_i: /* Delete handler retaining the result. */
            {
                PolyWord u = *sp++;
                PolyWord *t;
                sp = poly_stack->p_hr;
                while((t = (*sp).AsStackAddr()) < sp || t > end_of_stack) sp++;
                poly_stack->p_hr = t;
                *sp = u;
                pc += *pc + 1; /* Skip the handler */
                pc += arg1 + 2;
                break;
            }

        case INSTR_case:
            {
                POLYSIGNED u = UNTAGGED(*sp++); /* Get the value */
                if (u > arg1 || u < 0) pc += (arg1+2)*2; /* Out of range */
                else {
                    pc += 2;
                    pc += /* Index */pc[u*2]+pc[u*2 + 1]*256; }
                break;
            }

        case INSTR_call_sl: /* Static link call */
            {
                /* Get static link value. */
                PolyWord *t = sp+arg2;
                for(int i = 1; i <= arg3; i++) t = (t[-1]).AsStackAddr();
                PolyWord *constAddr = (PolyWord*)(pc+arg1+2); /* Get entry point. */
                *(--sp) = PolyWord::FromCodePtr(pc+6); /* Push return address to point after instruction. */
                *(--sp) = PolyWord::FromStackAddr(t); /* Push static link */
                pc = (*constAddr).AsCodePtr();
                break;
            }

        case INSTR_call_sl_X:
            {
                /* Get static link value. */
                PolyWord *t = sp+arg3;

                for(int u = 1; u <= arg4; u++) t = (t[-1]).AsStackAddr();

                PolyWord *constAddr = (PolyWord*)(pc+arg2+(arg1+4)*sizeof(PolyWord)+4); /* Get entry point. */
                *(--sp) = PolyWord::FromCodePtr(pc+8); /* Push return address to point after instruction. */
                *(--sp) = PolyWord::FromStackAddr(t); /* Push static link */
                pc = (*constAddr).AsCodePtr();
                break;
            }

        case INSTR_tail_3_b:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + *pc;
           goto TAIL_CALL;

        case INSTR_tail_3_2:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + 2;
           goto TAIL_CALL;

        case INSTR_tail_3_3:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + 3;
           goto TAIL_CALL;

        case INSTR_tail_4_b:
           tailCount = 4;
           tailPtr = sp + tailCount;
           sp = tailPtr + *pc;
           goto TAIL_CALL;

        case INSTR_tail_b_b:
           tailCount = *pc;
           tailPtr = sp + tailCount;
           sp = tailPtr + pc[1];
           goto TAIL_CALL;

        case INSTR_tail:
           /* Tail recursive call. */
           /* Move items up the stack. */
           /* There may be an overlap if the function we are calling
              has more args than this one. */
           tailCount = arg1;
           tailPtr = sp + tailCount;
           sp = tailPtr + arg2;
           TAIL_CALL: /* For general case. */
           if (tailCount < 2) Crash("Invalid argument\n");
           for (; tailCount > 0; tailCount--) *(--sp) = *(--tailPtr);
           pc = (*sp++).AsCodePtr(); /* Pop the original return address. */
           li = INSTR_call_closure; /* If we have to re-execute. */
           /* And drop through. */

        case INSTR_call_closure: /* Closure call - may be machine code. */
        CALL_CLOSURE:  /* Jumped to from POLY_SYS_callcode */
            {
                PolyWord *t = (*sp).AsStackAddr(); /* Closure */
                PolyWord u = *t;   /* Get code address. (1st word of closure) */

                if (IS_INT(u)) { /* Closure address is io vector */
                    sp++; /* Remove closure. */
                    POLYSIGNED uu = UNTAGGED(u);
                    switch(uu) {

                    case POLY_SYS_callcode_tupled:
                        {
                            t = (*sp++).AsStackAddr();
                            PolyWord v = t[1]; /* Arguments. */
                            if (v != TAGGED(0)) /* No args. */
                            {
                                PolyWord *vv = v.AsStackAddr();
                                POLYUNSIGNED u = v.AsObjPtr()->Length(); /* No. of args. */
                                for (; u > 0; u--) *(--sp) = *(vv++);
                            }
                            *(--sp) = t[0]; /* Push closure. */
                            goto CALL_CLOSURE;
                        }
 
                    case POLY_SYS_int_eq: u = *sp++; *sp = (u == *sp)?True:False; break;

                    case POLY_SYS_int_neq: u = *sp++; *sp = (u != *sp)?True:False; break;

                    case POLY_SYS_word_eq: 
                       u = *sp++;
                       *sp = u == *sp ? True : False;
                       break;

                    case POLY_SYS_word_neq:
                       u = *sp++;
                       *sp = u == *sp ? False : True;
                       break;

                    case POLY_SYS_word_geq:
                        u = *sp++; *sp = ((*sp).AsUnsigned() >= u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_leq:
                        u = *sp++; *sp = ((*sp).AsUnsigned() <= u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_gtr:
                        u = *sp++; *sp = ((*sp).AsUnsigned() > u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_lss:
                        u = *sp++; *sp = ((*sp).AsUnsigned() < u.AsUnsigned())?True:False; break;

                    case POLY_SYS_or_word:
                        u = *sp++; *sp = TAGGED(UNTAGGED(*sp) | UNTAGGED(u)); break; 

                    case POLY_SYS_and_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED(*sp) & UNTAGGED(u)); break; 

                    case POLY_SYS_not_bool:  *sp = (*sp == True) ? False : True; break; 

                    case POLY_SYS_string_length: 
                        /* Length is first word of string unless it is a
                           single character. */
                        if (IS_INT(*sp)) *sp = TAGGED(1);
                        else *sp = TAGGED(((PolyStringObject*)(*sp).AsObjPtr())->length);
                        break; 

                    case POLY_SYS_set_string_length: 
                        {
                            /* Store the length word of a string. */
                            POLYUNSIGNED len = UNTAGGED(*sp++);
                            ((PolyStringObject*)(*sp).AsObjPtr())->length = len;
                            *sp = TAGGED(0);
                            break; 
                        }

                    case POLY_SYS_mul_word:
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) * UNTAGGED_UNSIGNED(u)); break;

                    case POLY_SYS_plus_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) + UNTAGGED_UNSIGNED(u)); break;

                    case POLY_SYS_minus_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) - UNTAGGED_UNSIGNED(u)); break; 

                    case POLY_SYS_div_word:
                        {
                            POLYUNSIGNED u = UNTAGGED_UNSIGNED(*sp++);
                            if (u == 0)
                                raise_exception0(EXC_divide);
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) / u); break;
                        }

                    case POLY_SYS_mod_word:
                        {
                            POLYUNSIGNED u = UNTAGGED_UNSIGNED(*sp++);
                            if (u == 0)
                                raise_exception0(EXC_divide);
                            // It's essential to use UNTAGGED_UNSIGNED here.
                            // The old version used UNTAGGED which uses an arithmetic shift
                            // and produces the wrong answer.
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) % u);
                            break;
                        }

                    case POLY_SYS_xor_word:
                        {
                            PolyWord u = *sp++;
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) ^ UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_left_word: 
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                                *sp = TAGGED(0);
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) << UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_right_word:
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                                *sp = TAGGED(0);
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) >> UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_right_arith_word:
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                            {
                                if (UNTAGGED_UNSIGNED(*sp) < 0)
                                    *sp = TAGGED(-1);
                                else *sp = TAGGED(0);
                            }
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) >> UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_load_byte:
                        {
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            *sp = TAGGED((*sp).AsCodePtr()[u]);
                            break; 
                        }

                    case POLY_SYS_load_word: 
                        {
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            *sp = (*sp).AsObjPtr()->Get(u);
                            break;
                        }

                    case POLY_SYS_assign_byte: 
                        {
                            POLYUNSIGNED t = UNTAGGED(*sp++);
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            (*sp).AsCodePtr()[u] = (byte)t;
                            *sp = TAGGED(0);
                            break; 
                        }

                    case POLY_SYS_assign_word: 
                        {
                            PolyWord t = *sp++;
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            (*sp).AsStackAddr()[u] = t;
                            *sp = TAGGED(0);
                            break;
                        }

                    case POLY_SYS_lockseg:
                        {
                            PolyObject *obj = (*sp).AsObjPtr();
                            POLYUNSIGNED lengthW = obj->LengthWord();
                            /* Clear the mutable bit. */
                            obj->SetLengthWord(lengthW & ~_OBJ_MUTABLE_BIT);
                            *sp = TAGGED(0);
                            break;
                        }

                    case POLY_SYS_get_length: 
                        /* Return the length word. */
                        *sp = TAGGED((*sp).AsObjPtr()->Length());
                        break;

                    case POLY_SYS_is_short:
                        *sp = IS_INT(*sp) ? TAGGED(1) : TAGGED(0); break;

                    case POLY_SYS_io_operation:
                        /* The io_operation call has changed between the old Poly
                           version and the new ML version.  In Poly it took two
                           parameters, the first always being an empty type.
                           In ML it takes just one parameter. */
                        if (*sp == TAGGED(0)) sp++;
                        *sp = (PolyObject*)IoEntry(UNTAGGED(*sp));
                        break;

                    case POLY_SYS_exception_trace:
                        u = *sp; /* Procedure to call. */
                        *(--sp) = PolyWord::FromCodePtr(pc); /* Push a return address. */
                        *(--sp) = PolyWord::FromStackAddr(poly_stack->p_hr); /* Push old handler */
                        *(--sp) = TAGGED(0); /* Marks exception trace. */
                        *(--sp) = TAGGED(0); /* Catch everything. */
                        poly_stack->p_hr = sp; /* Handler is here. */
                        pc = TAGGED(1).AsCodePtr(); /* Special return address. */
                        *(--sp) = TAGGED(0); /* Unit argument to the function. */
                        *(--sp) = u; /* Push the procedure. */
                        goto CALL_CLOSURE;

                    case POLY_SYS_is_big_endian: {
                        union { unsigned long wrd; char chrs[sizeof(unsigned long)]; } endian;
                        endian.wrd = 1;
                        *(--sp) = endian.chrs[0] == 0 ? TAGGED(1) : TAGGED(0);
                        break;
                    }

                    case POLY_SYS_bytes_per_word:
                        *(--sp) = TAGGED(sizeof(PolyWord)); break;
 
                    default:
                        // For all the calls that aren't built in ...
                        /* Save the state so that the instruction can be retried if necessary. */
                        poly_stack->p_pc = pc; /* Pc value after instruction. */
                        poly_stack->p_reg[1] = TAGGED(li); /* Previous instruction. */
                        poly_stack->p_sp = sp-1; /* Include the closure address. */
                        return uu;
                    }
                } /* End of system calls. */
                else {
                    sp--;
                    *sp = sp[1];      /* Move closure up. */
                    sp[1] = PolyWord::FromCodePtr(pc); /* Save return address. */
                    pc = u.AsCodePtr();    /* Get entry point. */
                }
            }
            break;

        case INSTR_return_w:
            returnCount = arg1; /* Get no. of args to remove. */

            RETURN: /* Common code for return. */
            {
                PolyWord result = *sp++; /* Result */
                sp++; /* Remove the link/closure */
                pc = (*sp++).AsCodePtr(); /* Return address */
                sp += returnCount; /* Add on number of args. */
                if (pc == TAGGED(0).AsCodePtr())
                    kill_selfc(); /* Exit */
                else if (pc == TAGGED(1).AsCodePtr())
                {
                    /* Return from a call to exception_trace when an exception<commit_msg>Change to InitStackFrame to use a handle.  Handle thread exit correctly.<commit_after>/*
    Title:  An interpreter for a compact instruction set.
    Author:     <NAME>, Cambridge University Computer Laboratory

    Copyright (c) 2000
        Cambridge University Technical Services Limited

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#ifdef _WIN32_WCE
#include "winceconfig.h"
#include "wincelib.h"
#else
#ifdef WIN32
#include "winconfig.h"
#else
#include "config.h"
#endif
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x) 0
#endif

#include "globals.h"
#include "int_opcodes.h"
#include "machine_dep.h"
#include "sys.h"
#include "profiling.h"
#include "arb.h"
#include "processes.h"
#include "run_time.h"
#include "mpoly.h"
#include "gc.h"
#include "basicio.h"
#include "timing.h"
#include "arb.h"
#include "reals.h"
#include "objsize.h"
#include "xwindows.h"
#include "foreign.h"
#include "process_env.h"
#include "network.h"
#include "basicio.h"
#include "sighandler.h"
#include "os_specific.h"
#include "diagnostics.h"
#include "polystring.h"
#include "save_vec.h"
#include "memmgr.h"

#define VERSION_NUMBER  POLY_version_number

#define arg1    (pc[0] + pc[1]*256)
#define arg2    (pc[2] + pc[3]*256)
#define arg3    (pc[4] + pc[5]*256)
#define arg4    (pc[6] + pc[7]*256)

#define True    TAGGED(1)
#define False   TAGGED(0)

#define CHECKED_REGS 2
#define UNCHECKED_REGS 0

#define EXTRA_STACK 0 // Don't need any extra - signals aren't handled on the Poly stack.

/* the amount of ML stack space to reserve for registers,
   C exception handling etc. The compiler requires us to
   reserve 2 stack-frames worth (2 * 20 words) plus whatever
   we require for the register save area. We actually reserve
   slightly more than this. SPF 3/3/97
*/
#define OVERFLOW_STACK_SIZE \
  (50 + \
   sizeof(StackObject)/sizeof(PolyWord) + \
   CHECKED_REGS + \
   UNCHECKED_REGS + \
   EXTRA_STACK)

extern StackObject *poly_stack;

class Interpreter : public MachineDependent {
public:
    Interpreter(): allocSpace(0) {}

    virtual void InitStackFrame(Handle stack, Handle proc, Handle arg);
    // Switch to Poly and return with the io function to call.
    virtual int SwitchToPoly(void);
    virtual void SetForRetry(int ioCall) {} // Nothing to do
    virtual void InitInterfaceVector(void);
    virtual void SetException(StackObject *stack,poly_exn *exc);
    virtual void InterruptCode(void);
    virtual int  GetIOFunctionRegisterMask(int ioCall) { raise_syscall("No register masks", 0); return 0; }
    virtual bool GetPCandSPFromContext(SIGNALCONTEXT *context, PolyWord * &sp,  POLYCODEPTR &pc)
        { return false; /* Not relevant */}
    virtual bool InRunTimeSystem(void) { return true; } // Always
    virtual void CallIO0(Handle(*ioFun)(void));
    virtual void CallIO1(Handle(*ioFun)(Handle));
    virtual void CallIO2(Handle(*ioFun)(Handle, Handle));
    virtual void CallIO3(Handle(*ioFun)(Handle, Handle, Handle));
    virtual void CallIO4(Handle(*ioFun)(Handle, Handle, Handle, Handle));
    virtual void CallIO5(Handle(*ioFun)(Handle, Handle, Handle, Handle, Handle));
    virtual Handle CallBackResult(void);
    virtual Architectures MachineArchitecture(void) { return MA_Interpreted; }

    // These next two have to be handled as special cases.  They need to jump
    // to CALL_CLOSURE to handle the cases where the functions we are tracing or
    // calling are actually IO functions and don't have code addresses.  Actually
    // we could instead make the interpreter handle small tagged integers as
    // code addresses specially.
    virtual void SetExceptionTrace(void) { ASSERT(false); }
    virtual void CallCodeTupled(void) { ASSERT(false); }

    void storetrace(POLYUNSIGNED wordsNeeded);
    LocalMemSpace *allocSpace;
};

// Do a garbage collection.
void Interpreter::storetrace(POLYUNSIGNED wordsNeeded)
{
    allocSpace = gMem.GetLargestSpace(wordsNeeded);
    if (allocSpace)
        return;
    if (! QuickGC(wordsNeeded))
    {
        fprintf(stderr,"Run out of store - interrupting console processes\n");
        processes->interrupt_console_processes();
    }
    allocSpace = gMem.GetLargestSpace(wordsNeeded);
    ASSERT(allocSpace != 0);
}

void Interpreter::InitStackFrame(Handle stackh, Handle proc, Handle arg)
/* Initialise stack frame. */
{
    StackObject *stack = (StackObject *)DEREFWORDHANDLE(stackh);
    PolyObject *closure = DEREFWORDHANDLE(proc);
    POLYUNSIGNED stack_size = stack->Length();
    stack->p_space = OVERFLOW_STACK_SIZE;
    stack->p_pc = *(byte**)(closure);
    stack->p_sp  = (PolyWord*)stack + stack_size-3; /* sp */
    stack->p_nreg = CHECKED_REGS; /* exception arg and last instruction. */
    stack->p_reg[CHECKED_REGS] = PolyWord::FromUnsigned(UNCHECKED_REGS);
    stack->p_reg[0] = TAGGED(0); /* Used for exception argument. */
    stack->p_reg[1] = TAGGED(256); /* No instruction. */
    stack->p_sp  = (PolyWord*)stack + stack_size;

    /* Set up exception handler */
    /* No previous handler so point it at itself. */
    stack->p_sp--;
    *(stack->p_sp) = PolyWord::FromStackAddr(stack->p_sp);
    *(--stack->p_sp) = TAGGED(0); /* Default return address. */
    *(--stack->p_sp) = TAGGED(0); /* Default handler. */
    stack->p_hr = stack->p_sp;

    /* If this function takes an argument store it on the stack. */
    if (arg != 0) *(--stack->p_sp) = DEREFWORD(arg);

    *(--stack->p_sp) = TAGGED(0); /* Return address. */
    *(--stack->p_sp) = closure; /* Closure address */
}

int interrupt_requested = 0;
int profile_count_wanted = 0;

void Interpreter::InterruptCode(void)
/* Stop the Poly code at a suitable place. */
/* We may get an asynchronous interrupt at any time. */
{
    interrupt_requested = 1;
}


void Interpreter::SetException(StackObject *stack, poly_exn *exc)
/* Set up the stack of a process to raise an exception. */
{
    stack->p_reg[1] = TAGGED(INSTR_raise_ex);
    *(--stack->p_sp) = (PolyWord)exc; /* push exception data */
}

int Interpreter::SwitchToPoly(void)
/* (Re)-enter the Poly code from C. */
{
    register PolyWord *sp; /* Stack pointer. */
    register byte *pc; /* Program counter. */
    register PolyWord *sl; /* Stack limit register. */
    register int  li;  /* Last instruction. */
    POLYUNSIGNED tailCount;
    PolyWord *tailPtr;
    POLYUNSIGNED returnCount;
    POLYUNSIGNED storeWords;
    int instrBytes;

    RESTART: /* Load or reload the registers and run the code. */
    sp = poly_stack->p_sp; /* Reload these. */
    pc = poly_stack->p_pc;
    li = UNTAGGED(poly_stack->p_reg[1]);
    sl = (PolyWord*)poly_stack+OVERFLOW_STACK_SIZE;
    // Get the largest space available.  If we have just called storetrace because we
    // were trying to allocate but the current space wouldn't satisfy it we will now
    // have a space and the space we get here will be at least large enough so we won't loop.
    allocSpace = gMem.GetLargestSpace();
    ASSERT(allocSpace);
    if (li != 256) goto RETRY; /* Re-execute instruction if necessary. */

    for(;;){ /* Each instruction */

//        char buff[100];
        li = *pc++; /* Get next instruction. */

        RETRY:
//      sprintf(buff, "PC=%x, i=%x\n", pc, li);
//      OutputDebugString(buff);
        /* Check for stack overflow and interrupts. These can be done less
           frequently than every instruction. */
        if (sp < sl) {
            poly_stack->p_sp = sp;
            poly_stack->p_pc = pc;
            poly_stack->p_reg[1] = TAGGED(li);
            check_current_stack_size(sp);
            goto RESTART;
        }

        if (interrupt_requested) {
            interrupt_requested = 0;
            poly_stack->p_sp = sp;
            poly_stack->p_pc = pc;
            poly_stack->p_reg[1] = TAGGED(li);
            execute_pending_interrupts();
            goto RESTART;
        }

        if (profile_count_wanted) {
            add_count(pc, sp, profile_count_wanted);
            profile_count_wanted = 0;
        }

        switch(li) {

        case INSTR_enter_int: pc++; /* Skip the argument. */ break;

        case INSTR_jump_false:
            {
                PolyWord u = *sp++; /* Pop argument */
                if (u == True) { pc += 1; break; }
                /* else - false - take the jump */
            }

        case INSTR_jump: pc += *pc + 1; break;

        case INSTR_push_handler: /* Save the old handler value. */
            *(--sp) = PolyWord::FromStackAddr(poly_stack->p_hr); /* Push old handler */
            break;

        case INSTR_set_handler: /* Set up a handler */
            *(--sp) = PolyWord::FromCodePtr(pc + *pc + 1); /* Address of handler */
            poly_stack->p_hr = sp-1; /*Point to identifier about to be pushed*/
            pc += 1;
            break;

        case INSTR_del_handler: /* Delete handler retaining the result. */
            {
                PolyWord u = *sp++;
                sp = poly_stack->p_hr;
                PolyWord *t;
                while ((t = (*sp).AsStackAddr()) < sp || t > end_of_stack) sp++;
                poly_stack->p_hr = t;
                *sp = u;
                pc += *pc + 1; /* Skip the handler */
                break;
            }

        case INSTR_jump_i_false:
            if (*sp++ == True) { pc += 1; break; }
            /* else - false - take the jump */

        case INSTR_jump_i: /* Indirect jump */
            {
                pc += *pc + 1;
                /* This may jump backwards. */
                int u = arg1;
                if (u > 32767) u -= 65536;
                pc += u + 2;
                break;
            }

        case INSTR_set_handler_i: /* Set up a handler */
            {
                byte *u = pc + *pc + 1;
                *(--sp) = /* Address of handler */
                    PolyWord::FromCodePtr(u + u[0] + u[1]*256 + 2);
                poly_stack->p_hr = sp-1;
                pc += 1;
                break;
            }

        case INSTR_del_handler_i: /* Delete handler retaining the result. */
            {
                PolyWord u = *sp++;
                PolyWord *t;
                sp = poly_stack->p_hr;
                while((t = (*sp).AsStackAddr()) < sp || t > end_of_stack) sp++;
                poly_stack->p_hr = t;
                *sp = u;
                pc += *pc + 1; /* Skip the handler */
                pc += arg1 + 2;
                break;
            }

        case INSTR_case:
            {
                POLYSIGNED u = UNTAGGED(*sp++); /* Get the value */
                if (u > arg1 || u < 0) pc += (arg1+2)*2; /* Out of range */
                else {
                    pc += 2;
                    pc += /* Index */pc[u*2]+pc[u*2 + 1]*256; }
                break;
            }

        case INSTR_call_sl: /* Static link call */
            {
                /* Get static link value. */
                PolyWord *t = sp+arg2;
                for(int i = 1; i <= arg3; i++) t = (t[-1]).AsStackAddr();
                PolyWord *constAddr = (PolyWord*)(pc+arg1+2); /* Get entry point. */
                *(--sp) = PolyWord::FromCodePtr(pc+6); /* Push return address to point after instruction. */
                *(--sp) = PolyWord::FromStackAddr(t); /* Push static link */
                pc = (*constAddr).AsCodePtr();
                break;
            }

        case INSTR_call_sl_X:
            {
                /* Get static link value. */
                PolyWord *t = sp+arg3;

                for(int u = 1; u <= arg4; u++) t = (t[-1]).AsStackAddr();

                PolyWord *constAddr = (PolyWord*)(pc+arg2+(arg1+4)*sizeof(PolyWord)+4); /* Get entry point. */
                *(--sp) = PolyWord::FromCodePtr(pc+8); /* Push return address to point after instruction. */
                *(--sp) = PolyWord::FromStackAddr(t); /* Push static link */
                pc = (*constAddr).AsCodePtr();
                break;
            }

        case INSTR_tail_3_b:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + *pc;
           goto TAIL_CALL;

        case INSTR_tail_3_2:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + 2;
           goto TAIL_CALL;

        case INSTR_tail_3_3:
           tailCount = 3;
           tailPtr = sp + tailCount;
           sp = tailPtr + 3;
           goto TAIL_CALL;

        case INSTR_tail_4_b:
           tailCount = 4;
           tailPtr = sp + tailCount;
           sp = tailPtr + *pc;
           goto TAIL_CALL;

        case INSTR_tail_b_b:
           tailCount = *pc;
           tailPtr = sp + tailCount;
           sp = tailPtr + pc[1];
           goto TAIL_CALL;

        case INSTR_tail:
           /* Tail recursive call. */
           /* Move items up the stack. */
           /* There may be an overlap if the function we are calling
              has more args than this one. */
           tailCount = arg1;
           tailPtr = sp + tailCount;
           sp = tailPtr + arg2;
           TAIL_CALL: /* For general case. */
           if (tailCount < 2) Crash("Invalid argument\n");
           for (; tailCount > 0; tailCount--) *(--sp) = *(--tailPtr);
           pc = (*sp++).AsCodePtr(); /* Pop the original return address. */
           li = INSTR_call_closure; /* If we have to re-execute. */
           /* And drop through. */

        case INSTR_call_closure: /* Closure call - may be machine code. */
        CALL_CLOSURE:  /* Jumped to from POLY_SYS_callcode */
            {
                PolyWord *t = (*sp).AsStackAddr(); /* Closure */
                PolyWord u = *t;   /* Get code address. (1st word of closure) */

                if (IS_INT(u)) { /* Closure address is io vector */
                    sp++; /* Remove closure. */
                    POLYSIGNED uu = UNTAGGED(u);
                    switch(uu) {

                    case POLY_SYS_callcode_tupled:
                        {
                            t = (*sp++).AsStackAddr();
                            PolyWord v = t[1]; /* Arguments. */
                            if (v != TAGGED(0)) /* No args. */
                            {
                                PolyWord *vv = v.AsStackAddr();
                                POLYUNSIGNED u = v.AsObjPtr()->Length(); /* No. of args. */
                                for (; u > 0; u--) *(--sp) = *(vv++);
                            }
                            *(--sp) = t[0]; /* Push closure. */
                            goto CALL_CLOSURE;
                        }
 
                    case POLY_SYS_int_eq: u = *sp++; *sp = (u == *sp)?True:False; break;

                    case POLY_SYS_int_neq: u = *sp++; *sp = (u != *sp)?True:False; break;

                    case POLY_SYS_word_eq: 
                       u = *sp++;
                       *sp = u == *sp ? True : False;
                       break;

                    case POLY_SYS_word_neq:
                       u = *sp++;
                       *sp = u == *sp ? False : True;
                       break;

                    case POLY_SYS_word_geq:
                        u = *sp++; *sp = ((*sp).AsUnsigned() >= u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_leq:
                        u = *sp++; *sp = ((*sp).AsUnsigned() <= u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_gtr:
                        u = *sp++; *sp = ((*sp).AsUnsigned() > u.AsUnsigned())?True:False; break;

                    case POLY_SYS_word_lss:
                        u = *sp++; *sp = ((*sp).AsUnsigned() < u.AsUnsigned())?True:False; break;

                    case POLY_SYS_or_word:
                        u = *sp++; *sp = TAGGED(UNTAGGED(*sp) | UNTAGGED(u)); break; 

                    case POLY_SYS_and_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED(*sp) & UNTAGGED(u)); break; 

                    case POLY_SYS_not_bool:  *sp = (*sp == True) ? False : True; break; 

                    case POLY_SYS_string_length: 
                        /* Length is first word of string unless it is a
                           single character. */
                        if (IS_INT(*sp)) *sp = TAGGED(1);
                        else *sp = TAGGED(((PolyStringObject*)(*sp).AsObjPtr())->length);
                        break; 

                    case POLY_SYS_set_string_length: 
                        {
                            /* Store the length word of a string. */
                            POLYUNSIGNED len = UNTAGGED(*sp++);
                            ((PolyStringObject*)(*sp).AsObjPtr())->length = len;
                            *sp = TAGGED(0);
                            break; 
                        }

                    case POLY_SYS_mul_word:
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) * UNTAGGED_UNSIGNED(u)); break;

                    case POLY_SYS_plus_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) + UNTAGGED_UNSIGNED(u)); break;

                    case POLY_SYS_minus_word: 
                        u = *sp++; *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) - UNTAGGED_UNSIGNED(u)); break; 

                    case POLY_SYS_div_word:
                        {
                            POLYUNSIGNED u = UNTAGGED_UNSIGNED(*sp++);
                            if (u == 0)
                                raise_exception0(EXC_divide);
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) / u); break;
                        }

                    case POLY_SYS_mod_word:
                        {
                            POLYUNSIGNED u = UNTAGGED_UNSIGNED(*sp++);
                            if (u == 0)
                                raise_exception0(EXC_divide);
                            // It's essential to use UNTAGGED_UNSIGNED here.
                            // The old version used UNTAGGED which uses an arithmetic shift
                            // and produces the wrong answer.
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) % u);
                            break;
                        }

                    case POLY_SYS_xor_word:
                        {
                            PolyWord u = *sp++;
                            *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) ^ UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_left_word: 
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                                *sp = TAGGED(0);
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) << UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_right_word:
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                                *sp = TAGGED(0);
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) >> UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_shift_right_arith_word:
                        {
                            PolyWord u = *sp++;
                            if (UNTAGGED_UNSIGNED(u) > sizeof(PolyWord)*8)
                            {
                                if (UNTAGGED_UNSIGNED(*sp) < 0)
                                    *sp = TAGGED(-1);
                                else *sp = TAGGED(0);
                            }
                            else
                                *sp = TAGGED(UNTAGGED_UNSIGNED(*sp) >> UNTAGGED_UNSIGNED(u));
                            break;
                        }

                    case POLY_SYS_load_byte:
                        {
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            *sp = TAGGED((*sp).AsCodePtr()[u]);
                            break; 
                        }

                    case POLY_SYS_load_word: 
                        {
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            *sp = (*sp).AsObjPtr()->Get(u);
                            break;
                        }

                    case POLY_SYS_assign_byte: 
                        {
                            POLYUNSIGNED t = UNTAGGED(*sp++);
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            (*sp).AsCodePtr()[u] = (byte)t;
                            *sp = TAGGED(0);
                            break; 
                        }

                    case POLY_SYS_assign_word: 
                        {
                            PolyWord t = *sp++;
                            POLYUNSIGNED u = UNTAGGED(*sp++);
                            (*sp).AsStackAddr()[u] = t;
                            *sp = TAGGED(0);
                            break;
                        }

                    case POLY_SYS_lockseg:
                        {
                            PolyObject *obj = (*sp).AsObjPtr();
                            POLYUNSIGNED lengthW = obj->LengthWord();
                            /* Clear the mutable bit. */
                            obj->SetLengthWord(lengthW & ~_OBJ_MUTABLE_BIT);
                            *sp = TAGGED(0);
                            break;
                        }

                    case POLY_SYS_get_length: 
                        /* Return the length word. */
                        *sp = TAGGED((*sp).AsObjPtr()->Length());
                        break;

                    case POLY_SYS_is_short:
                        *sp = IS_INT(*sp) ? TAGGED(1) : TAGGED(0); break;

                    case POLY_SYS_io_operation:
                        /* The io_operation call has changed between the old Poly
                           version and the new ML version.  In Poly it took two
                           parameters, the first always being an empty type.
                           In ML it takes just one parameter. */
                        if (*sp == TAGGED(0)) sp++;
                        *sp = (PolyObject*)IoEntry(UNTAGGED(*sp));
                        break;

                    case POLY_SYS_exception_trace:
                        u = *sp; /* Procedure to call. */
                        *(--sp) = PolyWord::FromCodePtr(pc); /* Push a return address. */
                        *(--sp) = PolyWord::FromStackAddr(poly_stack->p_hr); /* Push old handler */
                        *(--sp) = TAGGED(0); /* Marks exception trace. */
                        *(--sp) = TAGGED(0); /* Catch everything. */
                        poly_stack->p_hr = sp; /* Handler is here. */
                        pc = TAGGED(1).AsCodePtr(); /* Special return address. */
                        *(--sp) = TAGGED(0); /* Unit argument to the function. */
                        *(--sp) = u; /* Push the procedure. */
                        goto CALL_CLOSURE;

                    case POLY_SYS_is_big_endian: {
                        union { unsigned long wrd; char chrs[sizeof(unsigned long)]; } endian;
                        endian.wrd = 1;
                        *(--sp) = endian.chrs[0] == 0 ? TAGGED(1) : TAGGED(0);
                        break;
                    }

                    case POLY_SYS_bytes_per_word:
                        *(--sp) = TAGGED(sizeof(PolyWord)); break;
 
                    default:
                        // For all the calls that aren't built in ...
                        /* Save the state so that the instruction can be retried if necessary. */
                        poly_stack->p_pc = pc; /* Pc value after instruction. */
                        poly_stack->p_reg[1] = TAGGED(li); /* Previous instruction. */
                        poly_stack->p_sp = sp-1; /* Include the closure address. */
                        return uu;
                    }
                } /* End of system calls. */
                else {
                    sp--;
                    *sp = sp[1];      /* Move closure up. */
                    sp[1] = PolyWord::FromCodePtr(pc); /* Save return address. */
                    pc = u.AsCodePtr();    /* Get entry point. */
                }
            }
            break;

        case INSTR_return_w:
            returnCount = arg1; /* Get no. of args to remove. */

            RETURN: /* Common code for return. */
            {
                PolyWord result = *sp++; /* Result */
                sp++; /* Remove the link/closure */
                pc = (*sp++).AsCodePtr(); /* Return address */
                sp += returnCount; /* Add on number of args. */
                if (pc == TAGGED(0).AsCodePtr())
                {
                    try
                    {
                        kill_selfc(); // This thread is exiting.
                        // kill_selfc throws an exception because it can't
                        // return normally - the thread is no longer there.
                    }
                    catch (IOException)
                    {
                    }
                    goto RESTART;
                }
                else if (pc == TAGGED(1).AsCodePtr())
                {
                    /* Return from a call to exception_trace when an exception
{'fraction_non_alphanumeric': 0.11283814940055334, 'fraction_numerical': 0.008261604672609899, 'mean_word_length': 1.3512219361250395, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 139, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5594980', 'n_tokens_mistral': 15508, 'n_tokens_neox': 14460, 'n_words': 3890}