interpret.c
ldmud-3.4.1/src/interpret.c · 629.0 KB
From the archive ldmud-3.4.1.tar.gz
Download the archive « Back to the archive contents
/*---------------------------------------------------------------------------
* Gamedriver: Bytecode Interpreter
*
*---------------------------------------------------------------------------
* This module implements the bytecode interpreter for the compiled LPC
* programs. The machine is implemented as a stackmachine with separate
* stacks for values and control.
*
* See also 'exec.h' for the details of program storage, and 'svalue.h'
* for the details of value storage.
*
* --- Evaluator Stack ---
*
* The evaluation stack is an array of 'svalue_t's (see datatypes.h
* for information about this type) with EVALUATOR_SIZE<<1 elements.
* <inter_sp> resp. <sp> points to the last (that is topmost) valid
* entry in the stack, the framepointer <inter_fp> resp. <fp> points
* to the bottom of the frame of one function. Single values in the
* frame are then accessed by indexing the frame pointer.
* A typical stack layout looks like this:
*
* ^
* (inter_)sp -> | Top stack value
* | ...
* | Temporary stack values
* | Break addresses for switch instructions
* break_sp -> | (forming a sub-stack growing _down_).
* | ...
* | Local variable number 1
* | Local variable number 0
* | ...
* | Argument number 1
* (inter_)fp -> | Argument number 0
* |
* |
* VALUE_STACK -----
*
* The interpreter assumes that there are no destructed objects
* on the stack - to aid in this, the functions remove_object_from_stack()
* and (in array.c) check_for_destr() replace destructed objects by
* value 0.
*
*
#ifdef USE_NEW_INLINES
* --- Context Variables ---
*
* In order to implement 'real' inline closures, lfun closure carry with
* them a set of svalue_t's, called the 'context'. When such a closure
* is created, the context is filled with values from selected local
* function variables.
*
* The interpreter keeps the pointer <inter_context> pointed to the
* currently value context, if there is one, or NULL if there is no
* context. The context variables are accessed with a set of instructions
* mirroring those to access object variables.
*
* TODO: In fact, these contexts could be implemented as light-weight
* TODO:: objects, removing the need for special cases.
*
*
#endif
* --- Control Stack ---
*
* During nested function calls, the return information to the higher
* functions are stored on the control stack.
*
* One particularity about the current implementation is that every
* inter-object call (ie. every 'extern_call') and every catch()
* constitutes in a recursive call to eval_instruction().
*
*
* --- Error Recovery Stack --- (implemented in backend.c)
*
* Error recovery in general is implemented using setjmp()/longjmp().
* The error recovery stack holds the (possibly nested) longjmp() contexts
* together with an indication where the jump will lead. Currently these
* context types are defined:
* ERROR_RECOVERY_NONE: No error recovery available
* (used by the top entry in the stack)
* ERROR_RECOVERY_BACKEND: Errors fall back to the backend,
* e.g. process_objects(), call_heart_beat()
* and others.
* ERROR_RECOVERY_APPLY: Errors fall back into the secure_apply()
* function used for sensitive applies.
* ERROR_RECOVERY_CATCH: Errors are caught by the catch() construct.
*
* The _CATCH contexts differs from the others in that it allows the
* continuing execution after the error. In order to achieve this, the
* stack entry holds the necessary additional information to re-init
* the interpreter.
* TODO: Elaborate on the details.
*
*
* --- Bytecode ---
*
* The machine instructions are stored as unsigned characters and read
* sequentially. A single machine instruction consists of one or two
* bytes defining the instruction, optionally followed by more bytes
* with parameters (e.g. number of arguments on the stack, branch offsets,
* etc).
*
* Apart from the usual machine instructions (branches, stack
* manipulation, summarily called 'codes'), the machine implements every
* efun by its own instruction code. Since this leads to more than
* 256 instructions, the most of the efuns are encoded using prefix
* bytes. The unprefixed opcodes in the range 0..255 are used for the
* internal machine instructions and LPC operators, and for the small
* and/or often used efuns. The prefix byte for the other efun
* instructions reflects the type of the efun:
*
* F_EFUN0: efuns taking no argument
* F_EFUN1: efuns taking one argument
* F_EFUN2: efuns taking two arguments
* F_EFUN3: efuns taking three arguments
* F_EFUN4: efuns taking four arguments
* F_EFUNV: efuns taking more than four or a variable number of arguments
*
* The implementation is such that the unprefixed instructions are
* implemented directly in the interpreter loop in a big switch()
* statement, whereas the prefixed instructions are implemented
* in separate functions and called via the lookup tables efun_table[]
* and vefun_table[].
*
* Every machine instruction, efun or else, is assigned a unique number
* and a preprocessor symbol F_<name>. The exact translation into
* the prefix/opcode bytecodes depends on the number of instructions
* in the various classes, but is linear and holds the following
* conditions:
*
* - all non-efun instructions do not need a prefix byte and start
* at instruction code 0.
* - selected efuns also don't need a prefix byte and directly follow
* the non-efun instructions.
* - the instruction codes for all tabled efuns are consecutive.
* - the instruction codes for all tabled varargs efuns are consecutive.
*
* All existing machine instructions are defined in the file func_spec,
* which during the compilation of the driver is evaluated by make_func.y
* to create the LPC compiler lang.y from prolang.y, the symbolic
* instruction names and numbers in instrs.h, and the definition of the
* tables efuns in efun_defs.c .
*
*
* --- Calling Convention ---
*
* All arguments for a function are evaluated and pushed to the value
* stack. The last argument is the last pushed. It is important that
* the called function gets exactly as many arguments as it wants; for
* LPC functions ('lfuns') this means that the actual function call will
* remove excessive arguments or push '0's for missing arguments. The
* number of arguments will be stored in the control stack, so that
* the return instruction not needs to know it explicitely.
*
* If the function called is an lfun (inherited or not), the number
* of arguments passed to the call is encoded in the bytecode stream,
* and the number of arguments expected can be determined from the
* functions 'struct function' entry.
*
* Efuns, operators and internal bytecode usually operate on a fixed
* number of arguments and the compiler makes sure that the right
* number is given. If an efun takes a variable number of arguments,
* the actual number is stored in the byte following the efun's opcode.
*
* The called function must ensure that exactly one value remains on the
* stack when returning. The caller is responsible of deallocating the
* returned value. This includes 'void' lfuns, which just push the
* value 0 as return value.
*
* When a LPC function returns, it will use the instruction F_RETURN, which
* will deallocate all arguments and local variables, and only let the
* top of stack entry remain. The number of arguments and local variables
* are stored in the control stack, so that the evaluator knows how much
* to deallocate.
*
* If flag 'extern_call' is set, then the evaluator should return from
* eval_instruction(). Otherwise, the evaluator will continue to execute
* the instruction at the returned address. In the current implementation,
* every inter-object call (call_other) receives its own (recursive)
* call to eval_instruction().
*
*---------------------------------------------------------------------------
* TODO: The virtual machine should be reconsidered, using the DGD and MudOS
* TODO:: machines for inspiration. This applies to implementation as well
* TODO:: as to the instruction set.
* TODO: Let all assign_ and transfer_ functions check for destruct objects.
* TODO:: The speed difference to assign_checked_ and transfer_checked_ is
* TODO:: not big enough to justify the extra set of functions.
*/
/*-------------------------------------------------------------------------*/
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <setjmp.h>
#include <ctype.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef MARK
#include "profile.h"
#endif
#include "interpret.h"
#include "actions.h"
#include "array.h"
#include "backend.h"
#include "call_out.h"
#include "closure.h"
#include "comm.h"
#include "ed.h"
#include "efuns.h"
#include "exec.h"
#include "filestat.h"
#include "gcollect.h"
#include "heartbeat.h"
#include "instrs.h"
#include "lex.h"
#include "mapping.h"
#include "mstrings.h"
#include "object.h"
#include "otable.h"
#include "parse.h"
#include "prolang.h"
#include "simulate.h"
#include "simul_efun.h"
#include "stdstrings.h"
#ifdef USE_STRUCTS
#include "structs.h"
#endif /* USE_STRUCTS */
#include "svalue.h"
#include "swap.h"
#include "switch.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "../mudlib/sys/driver_hook.h"
#include "../mudlib/sys/debug_info.h"
#include "../mudlib/sys/trace.h"
/*-------------------------------------------------------------------------*/
/* Types */
/* --- struct catch_context: error_recovery subclass for catch() ---
*
* This extension of the struct error_recovery_info (see backend.h)
* stores the additional information needed to reinitialize the global
* variables when bailing out of a catch(). The type is always
* ERROR_RECOVERY_CATCH.
*
* It is handled by the functions push_, pop_ and pull_error_context().
*/
struct catch_context
{
struct error_recovery_info recovery_info;
/* The subclassed recovery info.
*/
struct control_stack * save_csp;
object_t * save_command_giver;
svalue_t * save_sp;
/* The saved global values
*/
};
/* --- struct cache: one entry of the apply cache
*
* Every entry in the apply cache holds information about a function
* call, both for functions found and not found.
*/
struct cache
{
string_t *name;
/* The name of the cached function, shared for existing functions,
* allocated if the object does not have the function.
* This pointer counts as reference.
*/
program_t *progp;
/* The pointer to the program code of the function, or NULL if the
* object does not implement the function.
*/
int id;
/* The id_number of the program. */
funflag_t flags;
/* Copy of the _MOD_STATIC and _MOD_PROTECTED flags of the function.
*/
fun_hdr_p funstart;
/* Pointer to the function.
*/
int function_index_offset;
int variable_index_offset;
/* Function and variable index offset.
*/
};
/*-------------------------------------------------------------------------*/
/* Macros */
#define ERRORF(s) do{inter_pc = pc; inter_sp = sp; errorf s ;}while(0)
#define ERROR(s) ERRORF((s))
/* ERRORF((...)) acts like errorf(...), except that first the local pc and sp
* are copied into the global variables.
* ERROR() is an easier to type form of ERRORF() when your error message
* is just one string. It will be redefined below for the tabled
* efuns.
*/
#define WARNF(s) do{inter_pc = pc; inter_sp = sp; warnf s ;}while(0)
#define WARN(s) WARNF((s))
#define FATALF(s) do{inter_pc = pc; inter_sp = sp; fatal s ;}while(0)
#define FATAL(s) FATALF((s))
/* Analogue.
*/
#if APPLY_CACHE_BITS < 1
# error APPLY_CACHE_BITS must be at least 1.
#else
# define CACHE_SIZE (1 << APPLY_CACHE_BITS)
#endif
/* Number of entries in the apply cache.
*/
/*-------------------------------------------------------------------------*/
/* Tracing */
int tracedepth;
/* Current depth of traced functions.
*/
int trace_level;
/* Current set of active trace options.
* This set can be different from interactive->trace_level if several
* nested trace() calls occur.
*/
static int traceing_recursion = -1;
/* Kind of mutex, used to turn off tracing while doing trace output.
* Necessary because output with add_message() might result result
* in further code to be executed.
*/
static Bool trace_exec_active = MY_FALSE;
/* TRUE whenever TRACE_EXEC is not just requested, but actually
* active. This distinction is necessary as tracing might be limited
* to one object only, and testing the object name for every instruction
* would be too expensive. Hence, the tracing condition is checked
* only on object changes and this variable is updated accordingly.
* See macros SET_TRACE_EXEC and TRACE_EXEC_P.
*/
#ifdef TRACE_CODE
/* The buffers for the traced code:
*/
static int previous_instruction[TOTAL_TRACE_LENGTH];
static ptrdiff_t stack_size[TOTAL_TRACE_LENGTH];
static ptrdiff_t abs_stack_size[TOTAL_TRACE_LENGTH];
static bytecode_p previous_pc[TOTAL_TRACE_LENGTH];
static program_t * previous_programs[TOTAL_TRACE_LENGTH];
static object_t * previous_objects[TOTAL_TRACE_LENGTH];
/* These arrays, organized as ring buffers, hold the vitals of the
* last TOTAL_TRACE_LENGTH instructions executed. Yet unused entries
* are 0 resp. NULL.
*/
static int last = TOTAL_TRACE_LENGTH - 1;
/* Index to the last used entry in the ringbuffers above.
*/
#endif
/* --- Macros --- */
#define TRACE_IS_INTERACTIVE() (command_giver && O_IS_INTERACTIVE(command_giver))
/* Return TRUE if the current command_giver is interactive.
* TODO: Instead of disabling all traceoutput whenever the command_giver
* TODO:: turns non-interactive, output should be redirected (with a
* TODO:: special mark) to the current_interactive.
*/
#define TRACETST(b) (TRACE_IS_INTERACTIVE() && (O_GET_INTERACTIVE(command_giver)->trace_level & (b)))
/* Return TRUE if the any of the tracing options <b> are requested
* by the interactive user.
*/
#define TRACEP(b) (trace_level & (b) && trace_test(b))
/* Return TRUE if tracing options <b> are both active in trace_level
* and requested by the interactive user.
*/
#define TRACEHB \
( current_heart_beat == NULL || TRACETST(TRACE_HEART_BEAT))
/* Return TRUE if either the current execution is not caused
* by a heart beat call, or if heartbeat tracing is allowed.
*/
#define SET_TRACE_EXEC MACRO( \
if (trace_level & TRACE_EXEC) \
trace_exec_active = MY_TRUE;\
)
/* If TRACE_EXEC is requested, (re)activate it.
* See trace_exec_active for the background.
*/
#define TRACE_EXEC_P ( TRACEP(TRACE_EXEC) \
|| (trace_exec_active = MY_FALSE, MY_FALSE))
/* If TRACE_EXEC is still requested, return TRUE, otherwise deactivate
* it and return FALSE.
* See trace_exec_active for the background.
*/
/*-------------------------------------------------------------------------*/
/* The names for the svalue types */
static const char * svalue_typename[]
= { /* T_INVALID */ "invalid"
, /* T_LVALUE */ "lvalue"
, /* T_NUMBER */ "number"
, /* T_STRING */ "string"
, /* T_POINTER */ "array"
, /* T_OBJECT */ "object"
, /* T_MAPPING */ "mapping"
, /* T_FLOAT */ "float"
, /* T_CLOSURE */ "closure"
, /* T_SYMBOL */ "symbol"
, /* T_QUOTED_ARRAY */ "quoted-array"
, /* T_STRUCT */ "struct"
, /* T_CHAR_LVALUE */ "char-lvalue"
, /* T_STRING_RANGE_LVALUE */ "string-range-lvalue"
, /* T_POINTER_RANGE_LVALUE */ "array-range-lvalue"
, /* T_PROTECTED_CHAR_LVALUE */ "prot-char-lvalue"
, /* T_PROTECTED_STRING_RANGE_LVALUE */ "prot-string-range-lvalue"
, /* T_PROTECTED_POINTER_RANGE_LVALUE */ "prot-array-range-lvalue"
, /* T_PROTECTED_LVALUE */ "prot-lvalue"
, /* T_PROTECTOR_MAPPING */ "protector-mapping"
, /* T_CALLBACK */ "callback-mapping"
, /* T_ERROR_HANDLER */ "error-handler"
, /* T_NULL */ "null"
};
/*-------------------------------------------------------------------------*/
/* Variables */
/* The virtual machine's registers.
*
* While the interpreter is in eval_instruction(), some of the values are
* kept in local variables for greater speed, with the globals being updated
* only when necessary.
* The affected variables are: inter_pc, inter_sp, TODO: which else?
*/
svalue_t *inter_sp;
/* Points to last valid value on the value stack.
*/
bytecode_p inter_pc;
/* Next bytecode to interpret.
*/
static svalue_t *inter_fp;
/* Framepointer: pointer to first argument.
*/
#ifdef USE_NEW_INLINES
static svalue_t *inter_context;
/* Contextpointer: pointer to first context variable.
* May be NULL if no context is available.
*/
#endif /* USE_NEW_INLINES */
static bytecode_p *break_sp;
/* Points to address to branch to at next F_BREAK from within a switch().
* This is actually a stack of addresses with break_sp pointing to the
* bottom with the most recent entry. This break stack is stored on
* the evaluator stack, one address per svalue_t (which incidentally
* stored in the u.string field), between the functions temporary values
* and its local variables.
* TODO: Since this stores an opcode* in a svalue, it should get its
* TODO:: own union type, and break_sp should be an svalue_t *.
*/
program_t *current_prog;
/* The current program. This is usually current_object->prog, but can
* differ when executing an inherited program.
*/
static svalue_t current_lambda;
/* If the VM is executing a lambda, this variable holds a counted
* reference to it to make sure that it isn't destructed while it is
* still executing.
*/
static string_t **current_strings;
/* Pointer to the string literal block of the current program for
* faster access.
*/
int function_index_offset;
/* Index of current program's function block within the functions of
* the current objects program (needed for inheritance).
*/
static int variable_index_offset;
/* Index of current program's variable block within the variables
* of the current object (needed for inheritance).
*/
svalue_t *current_variables;
/* Pointer to begin of the current variable block.
* This is current_object->variables + variable_index_offset for
* faster access.
*/
/* Other Variables */
int32 eval_cost;
/* The amount of eval cost used in the current execution thread.
*/
int32 assigned_eval_cost;
/* Auxiliary variable used to account eval costs to single objects and
* their user's wizlist entry.
* Whenver the execution thread enters a different object,
* assigned_eval_cost is set to the current value of eval_cost. When the
* thread leaves the object again, the difference between the actual
* eval_cost value and the older assigned_eval_cost is accounted to
* the current object.
* The implementation combines both actions in one function
* assign_eval_cost().
*/
svalue_t apply_return_value = { T_NUMBER };
/* This variable holds the result from a call to apply(), transferred
* properly from the interpreter stack where the called function
* left it.
* push_ and pop_apply_value() handle this particular transfer.
* Note: The process_string() helper function process_value() takes
* direct advantage of this variable.
*/
#define SIZEOF_STACK (EVALUATOR_STACK_SIZE<<1)
static svalue_t value_stack_array[SIZEOF_STACK+1];
#define VALUE_STACK (value_stack_array+1)
/* The evaluator stack, sized with (hopefully) enough fudge to handle
* function arguments and overflows.
* The stack grows upwards, and <inter_sp> points to last valid entry.
*
* The first entry of value_stack_array[] is not used and serves as
* dummy so that underflows can be detected in a portable way
* (Standard C disallows indexing before an array). Instead, VALUE_STACK
* is the real bottom of the stack.
*/
svalue_t catch_value = { T_INVALID } ;
/* Holds the value throw()n from within a catch() while the throw
* is executed.
*/
#if MAX_USER_TRACE >= MAX_TRACE
#error MAX_USER_TRACE value must be smaller than MAX_TRACE!
#endif
/* Sanity check for the control stack definition.
*/
static struct control_stack control_stack_array[MAX_TRACE+2];
#define CONTROL_STACK (control_stack_array+2)
struct control_stack *csp;
/* The control stack holds copies of the machine registers for previous
* function call levels, with <csp> pointing to the last valid
* entry, describing the last context.
* This also means that CONTROL_STACK[0] (== control_stack_array[2]) will
* have almost no interesting values as it will terminate execution.
* Especially CONTROL_STACK[0].prog is NULL to mark the bottom.
*
* The first two entries of control_stack_array[] are not used and
* serve as dummies so that underflows can be detected in a portable
* way (Standard C disallows indexing before an array).
*/
static Bool runtime_no_warn_deprecated = MY_FALSE;
/* Set to TRUE if the current instruction is not to warn about usage
* of deprecated features; reset at the end of the instruction.
* This flag is set by the NO_WARN_DEPRECATED instruction, generated
* by the bytecode compiler in response to the warn-deprecated pragma.
*/
static Bool runtime_array_range_check = MY_FALSE;
/* Set to TRUE if the current instruction is to warn about using
* an illegal range.
* This flag is set by the ARRAY_RANGE_CHECK instruction, generated
* by the bytecode compiler in response to the range-check pragma.
*/
#ifdef APPLY_CACHE_STAT
p_int apply_cache_hit = 0;
p_int apply_cache_miss = 0;
/* Number of hits and misses in the apply cache.
*/
#endif
static struct cache cache[CACHE_SIZE];
/* The apply cache.
*/
static struct
{
svalue_t v;
/* The target value:
* .v.type: T_CHAR_LVALUE
* .v.u.charp: the char to modify
* or
* .v.type: T_{POINTER,STRING}_RANGE_LVALUE
* .v.u.{vec,string}: the target value holding the range
* .index1, .index2, .size: see below
*/
mp_int index1; /* First index of the range */
mp_int index2; /* Last index of the range plus 1 */
mp_int size; /* Current(?) size of the value */
}
special_lvalue;
/* When assigning to vector and string ranges or elements, the
* target information is stored in this structure.
* TODO: Having one global structure counts as 'ugly'.
* Used knowingly by: (r)index_lvalue(), transfer_pointer_range(),
* assign_string_range().
* Used unknowingly by: assign_svalue(), transfer_svalue(),
* add_number_to_lvalue(), F_VOID_ASSIGN.
*/
static svalue_t indexing_quickfix = { T_NUMBER };
/* When indexing arrays and mappings with just one ref, especially
* for the purpose of getting a lvalue, the indexed item is copied
* into this variable and indexed from here.
* Used by operators: push_(r)indexed_lvalue, push_indexed_map_lvalue.
* TODO: Rename this variable, or better: devise a nice solution.
* TODO:: Use the protected_lvalues instead?
* TODO:: To quote Marion:
* TODO:: marion says: but this is crude too
* TODO:: marion blushes.
* TODO: Is it made sure that this var will be vacated before the
* TODO:: next use? Otoh, if not it's no problem as the value is
* TODO:: by definition volatile.
*/
svalue_t last_indexing_protector = { T_NUMBER };
/* When indexing a protected non-string-lvalue, this variable receives
* the protecting svalue for the duration of the operation (actually
* until the next indexing operation (TODO: not nice)).
* This is necessary because the indexing operation necessarily destroys
* the protector structure, even though the protection is still needed.
* Used by: protected_index_lvalue().
*/
#ifdef OPCPROF
#define MAXOPC (LAST_INSTRUCTION_CODE)
/* Number of different instructions to trace.
*/
static int opcount[MAXOPC];
/* Counter array for instruction profiling: each entry counts the
* usages of one instruction. The full instruction code (not the
* opcode) is used as index.
*/
#endif
#ifdef DEBUG
static program_t *check_a_lot_ref_counts_search_prog;
/* Program you developer are especially interested in.
*/
static struct pointer_table *ptable;
/* check_a_lot_of_ref_counts: the table of structures already
* visited.
*/
#endif
unsigned long total_evalcost;
static struct timeval eval_begin;
/* Current total evalcost counter, and start of the evaluation.
*/
unsigned long last_total_evalcost = 0;
struct timeval last_eval_duration = { 0 };
/* Last total evaluation cost and duration.
*/
statistic_t stat_total_evalcost = { 0 };
statistic_t stat_eval_duration = { 0 };
/* Weighted statistics of evaluation cost and duration.
*/
/*-------------------------------------------------------------------------*/
/* Forward declarations */
enum { APPLY_NOT_FOUND = 0, APPLY_FOUND, APPLY_DEFAULT_FOUND };
static int int_apply(string_t *, object_t *, int, Bool, Bool);
static void call_simul_efun(int code, object_t *ob, int num_arg);
#ifdef DEBUG
static void check_extra_ref_in_vector(svalue_t *svp, size_t num);
#endif
/*-------------------------------------------------------------------------*/
/* Assign the evaluation cost elapsed since the last call to the
* current_object and it's user's wizlist entry. Then set assigned_eval_cost
* to the current eval_cost so that later calls can do the same.
*
* This function must be called at least whenever the execution leaves
* one object for another one.
*/
#define ASSIGN_EVAL_COST \
if (current_object->user)\
{\
unsigned long carry;\
current_object->user->cost += eval_cost - assigned_eval_cost;\
carry = current_object->user->cost / 1000000000;\
if (carry)\
{\
current_object->user->gigacost += carry;\
current_object->user->cost %= 1000000000;\
}\
current_object->user->total_cost += eval_cost - assigned_eval_cost;\
carry = current_object->user->total_cost / 1000000000;\
if (carry)\
{\
current_object->user->total_gigacost += carry;\
current_object->user->total_cost %= 1000000000;\
}\
}\
current_object->ticks += eval_cost - assigned_eval_cost;\
{\
unsigned long carry = current_object->ticks / 1000000000;\
if (carry)\
{\
current_object->gigaticks += carry;\
current_object->ticks %= 1000000000;\
}\
}\
assigned_eval_cost = eval_cost;
void assign_eval_cost(void) { ASSIGN_EVAL_COST }
/*-------------------------------------------------------------------------*/
void
mark_start_evaluation (void)
/* Called before a new evaluation; resets the current evaluation statistics.
*/
{
total_evalcost = 0;
if (gettimeofday(&eval_begin, NULL))
{
eval_begin.tv_sec = eval_begin.tv_usec = 0;
}
} /* mark_start_evaluation() */
/*-------------------------------------------------------------------------*/
void
mark_end_evaluation (void)
/* Called after an evaluation; updates the evaluation statistics.
*/
{
if (total_evalcost == 0)
return;
last_total_evalcost = total_evalcost;
if (eval_begin.tv_sec == 0
|| gettimeofday(&last_eval_duration, NULL))
{
last_eval_duration.tv_sec = last_eval_duration.tv_usec = 0;
}
else
{
last_eval_duration.tv_sec -= eval_begin.tv_sec;
last_eval_duration.tv_usec -= eval_begin.tv_usec;
if (last_eval_duration.tv_usec < 0)
{
last_eval_duration.tv_sec--;
last_eval_duration.tv_usec += 1000000;
}
update_statistic_avg( &stat_eval_duration
, last_eval_duration.tv_sec * 1000000L
+ last_eval_duration.tv_usec
);
}
update_statistic_avg(&stat_total_evalcost, last_total_evalcost);
} /* mark_end_evaluation() */
/*-------------------------------------------------------------------------*/
void
init_interpret (void)
/* Initialize the interpreter data structures, especially the apply cache.
*/
{
struct cache invalid_entry;
int i;
/* The cache is inited to hold entries for 'functions' in a non-existing
* program (id 0). The first real apply calls will thus see a (virtual)
* collision with 'older' cache entries.
*/
invalid_entry.id = 0;
invalid_entry.progp = (program_t *)1;
invalid_entry.name = NULL;
for (i = 0; i < CACHE_SIZE; i++)
cache[i] = invalid_entry;
} /* init_interpret()*/
/*-------------------------------------------------------------------------*/
static INLINE Bool
is_sto_context (void)
/* Return TRUE if the current call context has a set_this_object()
* in effect.
*/
{
struct control_stack *p;
for (p = csp; !p->extern_call; p--) NOOP;
return (p->extern_call & CS_PRETEND) != 0;
} /* is_sto_context() */
/*=========================================================================*/
/* S V A L U E S */
/*-------------------------------------------------------------------------*/
/* The following functions handle svalues, ie. the data referenced
* by the svalue_ts. 'Freeing' in this context therefore never means
* a svalue_t, only the data referenced by it.
*
* destructed_object_ref(v): test if <v> references a destructed object.
* object_ref(v,o): test if <v> references object <o>
* free_string_svalue(v): free string svalue <v>.
* free_object_svalue(v): free object svalue <v>.
* zero_object_svalue(v): replace the object in svalue <v> by number 0.
* free_svalue(v): free the svalue <v>.
* assign_svalue_no_free(to,from): put a copy of <from> into <to>; <to>
* is considered empty.
* copy_svalue_no_free(to,from): put a shallow value copy of <from> into <to>;
* <to> is considered empty.
* assign_checked_svalue_no_free(to,from): put a copy of <from> into <to>;
* <to> is considered empty, <from> may be destructed
* object.
* assign_local_svalue_no_free(to,from): put a copy of local var <from>
* into <to>; <to> is considered empty, <from> may
* be destructed object.
* static assign_lrvalue_no_free(to,from): like assign_svalue_no_free(),
* but lvalues and strings are handled differently.
* assign_svalue(dest,v): assign <v> to <dest>, freeing <dest> first.
* Also handles assigns to lvalues.
* transfer_svalue_no_free(dest,v): move <v> into <dest>; <dest> is
* considered empty.
* transfer_svalue(dest,v): move <v> into <dest>; freeing <dest> first.
* Also handles transfers to lvalues.
* static add_number_to_lvalue(dest,i,pre,post): add <i> to lvalue <dest>.
*
* In addition there are some helper functions.
*
* TODO: All these functions and vars should go into a separate module.
*/
/*-------------------------------------------------------------------------*/
/* --- Protector structures ---
*
* Whenever an assignment is made to a single value, or to a range in
* a string, vector or mapping, the interpreter generates protector
* structures in place of the usual LVALUE-svalues, which hold:
* - a svalue structure referring to the svalue into which the assignment
* is done (this structure is always first so that the protector
* structures can be used instead of normal svalues),
* - the necessary information to store the assigned svalue into its
* place in the target holding the value,
* - a protective reference to the holding value.
*
* All this just to keep LPC statements like 'a = ({ 1 }); a[0] = (a = 0);'
* from crashing.
*
* TODO: A simpler way would be to compute the lhs of an assignment
* TODO:: after evaluating the rhs - not vice versa as it is now.
* TODO:: However, passing lvalues and ranges as ref-parameters to functions
* TODO:: would still be a potential problem.
*/
/* --- struct protected_lvalue: protect a single value
*/
struct protected_lvalue
{
svalue_t v;
/* .v.type: T_PROTECTED_LVALUE
* .v.u.lvalue: the protected value
*/
svalue_t protector; /* protects .v.u.lvalue (or its holder) */
};
/* --- struct protected_char_lvalue: protect a char in a string
*/
struct protected_char_lvalue
{
svalue_t v;
/* .v.type: T_PROTECTED_CHAR_LVALUE
* .v.u.charp: points to the char to access
*/
svalue_t protector; /* protects .lvalue */
svalue_t *lvalue; /* the string containing the char */
char *start;
/* must be == get_txt(lvalue->u.str), otherwise the string has been
* changed and this lvalue is invalid
*/
};
/* --- struct protected_range_lvalue: protect a range in a string or vector
*/
struct protected_range_lvalue {
svalue_t v;
/* .v.type: T_PROTECTED_{POINTER,STRING}_RANGE_LVALUE
* .v.u.{str,vec}: the target value holding the range
*/
svalue_t protector; /* protects .lvalue */
svalue_t *lvalue; /* the original svalue holding the range */
int index1, index2; /* first and last index of the range */
int size; /* original size of .lvalue */
/* On creation, .v.u.{vec,str} == .lvalue->u.{vec,str}.
* If that condition no longer holds, the target has been changed and
* the range information (index, size) is no longer valid.
*/
};
/*-------------------------------------------------------------------------*/
/* Forward declarations */
static void transfer_pointer_range(svalue_t *source);
static void transfer_protected_pointer_range(
struct protected_range_lvalue *dest, svalue_t *source);
static void assign_string_range(svalue_t *source, Bool do_free);
static void assign_protected_string_range(
struct protected_range_lvalue *dest,svalue_t *source, Bool do_free);
/*-------------------------------------------------------------------------*/
void
free_string_svalue (svalue_t *v)
/* Free the string svalue <v>; <v> must be of type T_STRING.
*/
{
#ifdef DEBUG
if (v->type != T_STRING)
{
fatal("free_string_svalue(): Expected string, "
"received svalue type (%d:%hd)\n"
, v->type, v->x.generic);
/* NOTREACHED */
return;
}
#endif
free_mstring(v->u.str);
}
#define free_string_svalue(v) free_mstring((v)->u.str)
/*-------------------------------------------------------------------------*/
void
free_object_svalue (svalue_t *v)
/* Free the object svalue <v>; <v> must be of type T_OBJECT.
*/
{
object_t *ob = v->u.ob;
#ifdef DEBUG
if (v->type != T_OBJECT)
{
fatal("free_object_svalue(): Expected object, "
"received svalue type (%d:%hd)\n"
, v->type, v->x.generic);
/* NOTREACHED */
return;
}
#endif
free_object(ob, "free_object_svalue");
}
/*-------------------------------------------------------------------------*/
void
zero_object_svalue (svalue_t *v)
/* Change <v> from an object svalue to the svalue-number 0.
*/
{
object_t *ob = v->u.ob;
free_object(ob, "zero_object_svalue");
put_number(v, 0);
}
/*-------------------------------------------------------------------------*/
static void
free_protector_svalue (svalue_t *v)
/* Free the svalue <v> which contains a protective reference to a vector
* or to a mapping.
*/
{
switch (v->type)
{
#ifdef USE_STRUCTS
case T_STRUCT:
free_struct(v->u.strct);
break;
#endif /* USE_STRUCTS */
case T_POINTER:
free_array(v->u.vec);
break;
case T_MAPPING:
free_mapping(v->u.map);
break;
case T_PROTECTOR_MAPPING:
free_protector_mapping(v->u.map);
break;
}
}
/*-------------------------------------------------------------------------*/
static void
int_free_svalue (svalue_t *v)
/* Free the svalue <v>, which may be of any type.
* Afterwards, the content of <v> is undefined.
*/
{
ph_int type = v->type;
v->type = T_INVALID;
/* If freeing the value throws an error, it is most likely that
* we ran out of stack. To avoid the error handling running
* out of stack on the same value again, we mask it before we free
* it - at the risk of leaking memory.
*/
assert_stack_gap();
switch (type)
{
default:
fatal("(free_svalue) Illegal svalue %p type %d\n", v, type);
/* NOTREACHED */
break;
case T_INVALID:
case T_NUMBER:
case T_FLOAT:
NOOP;
break;
case T_STRING:
{
string_t *str = v->u.str;
free_mstring(str);
break;
}
case T_OBJECT:
{
object_t *ob = v->u.ob;
free_object(ob, "free_svalue");
break;
}
case T_QUOTED_ARRAY:
case T_POINTER:
free_array(v->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
free_struct(v->u.strct);
break;
#endif /* USE_STRUCTS */
case T_MAPPING:
free_mapping(v->u.map);
break;
case T_SYMBOL:
free_mstring(v->u.str);
break;
case T_CLOSURE:
free_closure(v);
break;
case T_CALLBACK:
free_callback(v->u.cb);
break;
case T_LVALUE:
switch (v->u.lvalue->type)
{
case T_PROTECTED_LVALUE:
{
struct protected_lvalue *p;
p = v->u.protected_lvalue;
free_protector_svalue(&p->protector);
xfree(p);
break;
}
case T_PROTECTED_CHAR_LVALUE:
{
struct protected_char_lvalue *p;
p = v->u.protected_char_lvalue;
if (p->lvalue->type == T_STRING)
{
free_mstring(p->lvalue->u.str);
}
free_protector_svalue(&p->protector);
xfree(p);
break;
}
case T_PROTECTED_STRING_RANGE_LVALUE:
{
struct protected_range_lvalue *p;
/* TODO: Are these checks necessary? See RANGE_LVALUE below */
p = v->u.protected_range_lvalue;
if (p->lvalue->type != T_STRING
|| get_txt(p->lvalue->u.str) == get_txt(p->v.u.str))
{
free_mstring(p->v.u.str);
}
if (p->lvalue->type == T_STRING)
free_mstring(p->lvalue->u.str);
free_protector_svalue(&p->protector);
xfree(p);
break;
}
case T_PROTECTED_POINTER_RANGE_LVALUE:
{
struct protected_range_lvalue *p;
p = v->u.protected_range_lvalue;
free_array(p->v.u.vec);
free_protector_svalue(&p->protector);
xfree(p);
break;
}
case T_ERROR_HANDLER:
{
svalue_t *p;
p = v->u.lvalue;
(*p->u.error_handler)(p);
break;
}
} /* switch (v->u.lvalue->type) */
break; /* case T_LVALUE */
}
} /* int_free_svalue() */
/*-------------------------------------------------------------------------*/
/* Queue element to deserialize the freeing of complex svalues. */
struct fs_queue_s {
struct fs_queue_s * next;
svalue_t value;
};
typedef struct fs_queue_s fs_queue_t;
static fs_queue_t fs_queue_base;
/* Static fs_queue_t variable to avoid xallocs for the simple cases.
*/
static fs_queue_t * fs_queue_head = NULL;
static fs_queue_t * fs_queue_tail = NULL;
/* Double-ended list of deserialized svalues to free.
*/
void
free_svalue (svalue_t *v)
/* Free the svalue <v>, which may be of any type, while making sure that
* complex nested structures are deserialized (to avoid stack overflows).
* Afterwards, the content of <v> is undefined.
*/
{
Bool needs_deserializing = MY_FALSE;
switch (v->type)
{
case T_QUOTED_ARRAY:
case T_POINTER:
needs_deserializing = (v->u.vec->ref == 1);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
needs_deserializing = (struct_ref(v->u.strct) == 1);
break;
#endif /* USE_STRUCTS */
case T_MAPPING:
needs_deserializing = (v->u.map->ref == 1);
break;
}
/* If the value doesn't need de-serializing, it can be
* be freed immediately.
*/
if (!needs_deserializing)
{
int_free_svalue(v);
return;
}
/* If there are elements in the queue, we are inside the freeing of a
* complex structure, and this element just needs to be queued up.
* When out of memory, however, just free it.
*/
if (fs_queue_head != NULL)
{
fs_queue_t * tmp = xalloc(sizeof(*tmp));
if (NULL == tmp)
{
int_free_svalue(v);
return;
}
/* Copy the value over, invalidating this one. */
tmp->next = NULL;
tmp->value = *v;
v->type = T_INVALID;
/* Insert the element into the queue. */
fs_queue_tail->next = tmp;
fs_queue_tail = tmp;
return;
}
/* This is the first complex value to be freed - start the queue.
*/
fs_queue_base.next = NULL;
fs_queue_base.value = *v;
v->type = T_INVALID;
fs_queue_head = fs_queue_tail = &fs_queue_base;
/* Now loop over the queue, successively freeing the values.
* If one of the values freed contains complex freeable structures
* itself, they will be added to the end of the queue and eventually
* picked up by this loop.
*/
while (fs_queue_head != NULL)
{
fs_queue_t * current = fs_queue_head;
int_free_svalue(&(fs_queue_head->value));
fs_queue_head = fs_queue_head->next;
if (fs_queue_head == NULL)
fs_queue_tail = NULL;
if (current != &fs_queue_base)
xfree(current);
}
} /* free_svalue() */
/*-------------------------------------------------------------------------*/
static INLINE Bool
_destructed_object_ref (svalue_t *svp)
/* Return TRUE if the svalue in <svp> references a destructed object.
*/
{
lambda_t *l;
int type;
if (svp->type != T_OBJECT && svp->type != T_CLOSURE)
return MY_FALSE;
if (svp->type == T_OBJECT || !CLOSURE_MALLOCED(type = svp->x.closure_type))
return (svp->u.ob->flags & O_DESTRUCTED) ? MY_TRUE : MY_FALSE;
/* Lambda closure */
l = svp->u.lambda;
if (CLOSURE_HAS_CODE(type) && type == CLOSURE_UNBOUND_LAMBDA)
return MY_FALSE;
if (type == CLOSURE_LFUN
&& (l->function.lfun.ob->flags & O_DESTRUCTED))
return MY_TRUE;
return (l->ob->flags & O_DESTRUCTED) ? MY_TRUE : MY_FALSE;
} /* _destructed_object_ref() */
Bool destructed_object_ref (svalue_t *v) { return _destructed_object_ref(v); }
#define destructed_object_ref(v) _destructed_object_ref(v)
/*-------------------------------------------------------------------------*/
static INLINE Bool
int_object_ref (svalue_t *svp, object_t *obj)
/* Return TRUE if <svp> references object <obj> (destructed or alive),
* return FALSE if it doesn't.
*/
{
lambda_t *l;
int type;
if (svp->type != T_OBJECT && svp->type != T_CLOSURE)
return MY_FALSE;
if (svp->type == T_OBJECT || !CLOSURE_MALLOCED(type = svp->x.closure_type))
return svp->u.ob == obj;
/* Lambda closure */
l = svp->u.lambda;
if (CLOSURE_HAS_CODE(type) && type == CLOSURE_UNBOUND_LAMBDA)
return MY_FALSE;
if (type == CLOSURE_LFUN && l->function.lfun.ob == obj)
return MY_TRUE;
return l->ob == obj;
} /* int_object_ref() */
#define object_ref(v,o) int_object_ref(v,o)
/*-------------------------------------------------------------------------*/
static INLINE void
check_for_ref_loop (svalue_t * dest)
/* <dest> has just been assigned to - check if this created a reference loop.
* If yes, free <dest> and throw an error.
*/
{
if (dest->type == T_LVALUE || dest->type == T_PROTECTED_LVALUE)
{
/* rover1 will scan the lvalue chain in two-steps, rover2 will
* scan it step by step. If there is a loop, the two will eventually
* meet again.
*/
svalue_t * rover1, * rover2;
rover1 = rover2 = dest;
do {
if (rover1->type == T_LVALUE || rover1->type == T_PROTECTED_LVALUE)
rover1 = rover1->u.lvalue;
else
break;
if (rover1->type == T_LVALUE || rover1->type == T_PROTECTED_LVALUE)
rover1 = rover1->u.lvalue;
else
break;
if (rover2->type == T_LVALUE || rover2->type == T_PROTECTED_LVALUE)
rover2 = rover2->u.lvalue;
else
break;
if (rover1 == rover2)
{
free_svalue(dest);
errorf("Assignment would create reference loop.\n");
}
} while (rover1
&& (rover1->type == T_LVALUE || rover1->type == T_PROTECTED_LVALUE)
&& rover2
&& (rover2->type == T_LVALUE || rover2->type == T_PROTECTED_LVALUE)
);
}
} /* check_for_ref_loop() */
/*-------------------------------------------------------------------------*/
static INLINE void
inl_assign_svalue_no_free (svalue_t *to, svalue_t *from)
/* Put a duplicate of svalue <from> into svalue <to>, meaning that the original
* value is either copied when appropriate, or its refcount is increased.
* <to> is considered empty at the time of call.
*
* If <from> is a destructed object, <to> is set to the number 0 but
* <from> is left unchanged.
*/
{
#ifdef DEBUG
if (from == 0)
fatal("Null pointer to assign_svalue().\n");
#endif
/* Copy all the data */
*to = *from;
/* Now create duplicates resp. increment refcounts where necessary */
switch(from->type)
{
case T_STRING:
(void)ref_mstring(from->u.str);
break;
case T_OBJECT:
{
object_t *ob = to->u.ob;
if ( !(ob->flags & O_DESTRUCTED) )
(void)ref_object(ob, "ass to var");
else
put_number(to, 0);
break;
}
break;
case T_QUOTED_ARRAY:
case T_POINTER:
(void)ref_array(to->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
(void)ref_struct(to->u.strct);
break;
#endif /* USE_STRUCTS */
case T_SYMBOL:
(void)ref_mstring(to->u.str);
break;
case T_CLOSURE:
addref_closure(to, "ass to var");
break;
case T_MAPPING:
(void)ref_mapping(to->u.map);
break;
}
/* Protection against endless reference loops */
if (to->type == T_LVALUE || to->type == T_PROTECTED_LVALUE)
{
check_for_ref_loop(to);
}
} /* inl_assign_svalue_no_free() */
void assign_svalue_no_free (svalue_t *to, svalue_t *from)
{ inl_assign_svalue_no_free(to,from); }
#define assign_svalue_no_free(to,from) inl_assign_svalue_no_free(to,from)
/*-------------------------------------------------------------------------*/
static INLINE void
inl_copy_svalue_no_free (svalue_t *to, svalue_t *from)
/* Put a duplicate of svalue <from> into svalue <to>, meaning that the original
* value is either copied when appropriate, or its refcount is increased.
* In particular, if <from> is a mapping (which must not contain destructed
* objects!) or array, a shallow copy is created.
* <to> is considered empty at the time of call.
*
* If <from> is a destructed object, <to> is set to the number 0 but
* <from> is left unchanged.
*/
{
assign_svalue_no_free(to, from);
/* For arrays and mappings, create a shallow copy */
if (from->type == T_MAPPING)
{
mapping_t *old, *new;
old = to->u.map;
if (old->ref != 1)
{
DYN_MAPPING_COST(MAP_SIZE(old));
new = copy_mapping(old);
if (!new)
errorf("Out of memory: mapping[%lu] for copy.\n"
, MAP_SIZE(old));
free_mapping(old);
to->u.map = new;
}
}
else if (from->type == T_POINTER
|| from->type == T_QUOTED_ARRAY)
{
vector_t *old, *new;
size_t size, i;
old = to->u.vec;
size = VEC_SIZE(old);
if (old->ref != 1 && old != &null_vector)
{
DYN_ARRAY_COST(size);
new = allocate_uninit_array((int)size);
if (!new)
errorf("Out of memory: array[%lu] for copy.\n"
, (unsigned long) size);
for (i = 0; i < size; i++)
assign_svalue_no_free( &new->item[i]
, &old->item[i]);
free_array(old);
to->u.vec = new;
}
}
} /* inl_copy_svalue_no_free() */
void copy_svalue_no_free (svalue_t *to, svalue_t *from)
{ inl_copy_svalue_no_free(to,from); }
#define copy_svalue_no_free(to,from) inl_copy_svalue_no_free(to,from)
/*-------------------------------------------------------------------------*/
static INLINE void
assign_checked_svalue_no_free (svalue_t *to, svalue_t *from)
/* Put a duplicate of svalue <from> into svalue <to>, meaning that the original
* value is either copied when appropriate, or its refcount is increased.
* <to> is considered empty at the time of call.
* <from> may point to a variable or vector element, so it might contain
* a destructed object. In that case, <from> and <to> are set to
* svalue-number 0.
*/
{
switch (from->type)
{
case T_STRING:
(void)ref_mstring(from->u.str);
break;
case T_OBJECT:
{
object_t *ob = from->u.ob;
if ( !(ob->flags & O_DESTRUCTED) ) {
ref_object(ob, "ass to var");
break;
}
zero_object_svalue(from);
break;
}
case T_QUOTED_ARRAY:
case T_POINTER:
(void)ref_array(from->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
(void)ref_struct(from->u.strct);
break;
#endif /* USE_STRUCTS */
case T_SYMBOL:
(void)ref_mstring(from->u.str);
break;
case T_CLOSURE:
if (!destructed_object_ref(from))
addref_closure(from, "ass to var");
else
assign_svalue(from, &const0);
break;
case T_MAPPING:
(void)ref_mapping(from->u.map);
break;
}
*to = *from;
/* Protection against endless reference loops */
if (to->type == T_LVALUE || to->type == T_PROTECTED_LVALUE)
{
check_for_ref_loop(to);
}
} /* assign_checked_svalue_no_free() */
/*-------------------------------------------------------------------------*/
static INLINE void
assign_local_svalue_no_free ( svalue_t *to, svalue_t *from )
/* Put a duplicate of svalue <from> into svalue <to>, meaning that the original
* value is either copied when appropriate, or its refcount is increased.
* <to> is considered empty at the time of call.
*
* <from> is meant to point to a local variable, which might be an arg
* to the current lfun.
* If <from> is a lvalue, the chain is unraveled and the final non-lvalue
* is assigned. If that value is a destructed object, 0 is assigned.
*/
{
assign_from_lvalue:
switch (from->type)
{
case T_STRING:
(void)ref_mstring(from->u.str);
break;
case T_OBJECT:
(void)ref_object(from->u.ob, "assign_local_lvalue_no_free");
break;
case T_QUOTED_ARRAY:
case T_POINTER:
(void)ref_array(from->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
(void)ref_struct(from->u.strct);
break;
#endif /* USE_STRUCTS */
case T_SYMBOL:
(void)ref_mstring(from->u.str);
break;
case T_CLOSURE:
addref_closure(from, "ass to var");
break;
case T_MAPPING:
(void)ref_mapping(from->u.map);
break;
case T_LVALUE:
case T_PROTECTED_LVALUE:
from = from->u.lvalue;
if (destructed_object_ref(from)) {
assign_svalue(from, &const0);
break;
}
goto assign_from_lvalue;
case T_PROTECTED_CHAR_LVALUE:
put_number(to, *from->u.charp);
return;
}
*to = *from;
/* Protection against endless reference loops */
if (to->type == T_LVALUE || to->type == T_PROTECTED_LVALUE)
{
check_for_ref_loop(to);
}
} /* assign_local_svalue_no_free() */
/*-------------------------------------------------------------------------*/
static INLINE
void assign_lrvalue_no_free (svalue_t *to, svalue_t *from)
/* Put a duplicate of svalue <from> into svalue <to>, meaning that the original
* value is either copied when appropriate, or its refcount is increased.
* <to> is considered empty at the time of call.
*
* This function differs from assign_svalue_no_free() in the handling of
* two types:
* - if <from> is an unshared string, the string is made shared and
* both <to> and <from> are changed to use the shared string.
* - if <from> is a lvalue, <to>.u.lvalue is set to point to <from>.
* This is necessary when pushing references onto the stack - if
* assign_svalue_no_free() were used, the first free_svalue() would undo
* the whole lvalue indirection, even though there were still other lvalue
* entries in the stack for the same svalue.
* TODO: An alternative would be use a special struct lvalue {} with a
* refcount.
*/
{
#ifdef DEBUG
if (from == 0)
fatal("Null pointer to assign_lrvalue_no_free().\n");
#endif
/* Copy the data */
*to = *from;
/* Now adapt the refcounts or similar */
switch(from->type)
{
case T_STRING:
(void)ref_mstring(to->u.str);
break;
case T_OBJECT:
(void)ref_object(to->u.ob, "ass to var");
break;
case T_QUOTED_ARRAY:
case T_POINTER:
(void)ref_array(to->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
(void)ref_struct(to->u.strct);
break;
#endif /* USE_STRUCTS */
case T_SYMBOL:
(void)ref_mstring(to->u.str);
break;
case T_CLOSURE:
if (!destructed_object_ref(to))
addref_closure(to, "ass to var");
else
put_number(to, 0);
break;
case T_MAPPING:
(void)ref_mapping(to->u.map);
break;
case T_LVALUE:
to->u.lvalue = from;
break;
}
/* Protection against endless reference loops */
if (to->type == T_LVALUE || to->type == T_PROTECTED_LVALUE)
{
check_for_ref_loop(to);
}
} /* assign_lrvalue_no_free() */
/*-------------------------------------------------------------------------*/
void
assign_svalue (svalue_t *dest, svalue_t *v)
/* Put a duplicate of svalue <v> into svalue <dest>, meaning that the
* original value is either copied when appropriate, or its refcount is
* increased.
*
* <dest> is considered a valid svalue and therefore freed before the
* assignment. Structured values will necessiate doing the assignment before
* the actual deallocation, otherwise recursive structures could cause crashs.
* One nasty example is
* a = ( ({((a=({0})),(a[0]=a)),(a=0)})[0] = query_verb() );
* which used to corrupt the shared string table, namely the entry for
* the verb in variable a if its length uses a memory block of
* the same length as an array of size 2.
*
* If <dest> is a lvalue, <v> will be assigned to the svalue referenced
* to by <dest>.
*/
{
/* Free the <dest> svalue.
* If <dest> is a lvalue, the loop will traverse the lvalue chain until
* the actual svalue is found.
* If a T_xxx_LVALUE is found, the assignment will be done here
* immediately.
*/
for (;;) {
switch(dest->type)
{
case T_LVALUE:
case T_PROTECTED_LVALUE:
dest = dest->u.lvalue;
continue;
case T_STRING:
free_mstring(dest->u.str);
break;
case T_OBJECT:
{
object_t *ob = dest->u.ob;
free_object(ob, "assign_svalue");
break;
}
case T_QUOTED_ARRAY:
case T_POINTER:
{
vector_t *vec = dest->u.vec;
assign_svalue_no_free(dest, v);
/* TODO: leaks vec if out of memory */
free_array(vec);
return;
}
#ifdef USE_STRUCTS
case T_STRUCT:
{
struct_t *strct = dest->u.strct;
assign_svalue_no_free(dest, v);
/* TODO: leaks strct if out of memory */
free_struct(strct);
return;
}
#endif /* USE_STRUCTS */
case T_MAPPING:
{
mapping_t *map = dest->u.map;
assign_svalue_no_free(dest, v); /* leaks map if out of memory */
free_mapping(map);
return;
}
case T_SYMBOL:
free_mstring(dest->u.str);
break;
case T_CLOSURE:
free_closure(dest);
break;
/* If the final svalue in dest is one of these lvalues,
* the assignment is done right here and now.
* Note that 'dest' in some cases points to a protector structure.
*/
case T_CHAR_LVALUE:
if (v->type == T_NUMBER)
*dest->u.charp = (char)v->u.number;
return;
case T_PROTECTED_CHAR_LVALUE:
{
struct protected_char_lvalue *p;
p = (struct protected_char_lvalue *)dest;
if (p->lvalue->type == T_STRING
&& get_txt(p->lvalue->u.str) == p->start)
{
if (v->type == T_NUMBER)
*p->v.u.charp = (char)v->u.number;
}
return;
}
case T_POINTER_RANGE_LVALUE:
if (v->type == T_POINTER)
{
(void)ref_array(v->u.vec); /* transfer_...() will free it once */
transfer_pointer_range(v);
}
return;
case T_PROTECTED_POINTER_RANGE_LVALUE:
if (v->type == T_POINTER)
{
(void)ref_array(v->u.vec); /* transfer_...() will free it once */
transfer_protected_pointer_range(
(struct protected_range_lvalue *)dest, v
);
}
return;
case T_STRING_RANGE_LVALUE:
assign_string_range(v, MY_FALSE);
return;
case T_PROTECTED_STRING_RANGE_LVALUE:
assign_protected_string_range(
(struct protected_range_lvalue *)dest, v, MY_FALSE
);
return;
} /* switch() */
/* No more lvalues to follow, old value freed: do the assign next */
break;
} /* end for */
/* Now assign the value to the now-invalid <dest> */
assign_svalue_no_free(dest, v);
} /* assign_svalue() */
/*-------------------------------------------------------------------------*/
static INLINE void
inl_transfer_svalue_no_free (svalue_t *dest, svalue_t *v)
/* Move the value <v> into <dest>.
*
* <dest> is assumed to be invalid before the call, <v> is invalid after.
*/
{
/* Copy the data */
*dest = *v;
/* Protection against endless reference loops */
if (dest->type == T_LVALUE || dest->type == T_PROTECTED_LVALUE)
{
v->type = T_INVALID;
check_for_ref_loop(dest);
}
} /* inl_transfer_svalue_no_free() */
void transfer_svalue_no_free (svalue_t *dest, svalue_t *v)
{ inl_transfer_svalue_no_free(dest,v); }
#define transfer_svalue_no_free(dest,v) inl_transfer_svalue_no_free(dest,v)
/*-------------------------------------------------------------------------*/
static INLINE void
inl_transfer_svalue (svalue_t *dest, svalue_t *v)
/* Move svalue <v> into svalue <dest>.
*
* <dest> is considered a valid svalue and therefore freed before the
* assignment. <v> will be invalid after the call.
*
* If <dest> is a lvalue, <v> will be moved into the svalue referenced
* to by <dest>.
*
* TODO: Test if copying this function into F_VOID_ASSIGN case speeds up
* TODO:: the interpreter.
*/
{
/* Unravel the T_LVALUE chain, if any. */
while (dest->type == T_LVALUE || dest->type == T_PROTECTED_LVALUE)
dest = dest->u.lvalue;
/* Free the <dest> svalue.
* If a T_xxx_LVALUE is found, the transfer will be done here
* immediately.
*/
for(;;)
{
switch (dest->type)
{
case T_STRING:
free_mstring(dest->u.str);
break;
case T_OBJECT:
{
object_t *ob = dest->u.ob;
free_object(ob, "transfer_svalue");
break;
}
case T_QUOTED_ARRAY:
case T_POINTER:
free_array(dest->u.vec);
break;
#ifdef USE_STRUCTS
case T_STRUCT:
free_struct(dest->u.strct);
break;
#endif /* USE_STRUCTS */
case T_SYMBOL:
free_mstring(dest->u.str);
break;
case T_CLOSURE:
free_closure(dest);
break;
case T_MAPPING:
free_mapping(dest->u.map);
break;
/* If the final svalue in dest is one of these lvalues,
* the assignment is done right here and now.
* Note that 'dest' in some cases points to a protector structure.
*/
case T_CHAR_LVALUE:
if (v->type == T_NUMBER)
{
*dest->u.charp = (char)v->u.number;
}
else
free_svalue(v);
return;
case T_PROTECTED_CHAR_LVALUE:
{
struct protected_char_lvalue *p;
p = (struct protected_char_lvalue *)dest;
if (p->lvalue->type == T_STRING
&& get_txt(p->lvalue->u.str) == p->start)
{
if (v->type == T_NUMBER)
{
*p->v.u.charp = (char)v->u.number;
return;
}
}
free_svalue(v);
return;
}
case T_POINTER_RANGE_LVALUE:
transfer_pointer_range(v);
return;
case T_PROTECTED_POINTER_RANGE_LVALUE:
transfer_protected_pointer_range(
(struct protected_range_lvalue *)dest, v
);
return;
case T_STRING_RANGE_LVALUE:
assign_string_range(v, MY_TRUE);
return;
case T_PROTECTED_STRING_RANGE_LVALUE:
assign_protected_string_range(
(struct protected_range_lvalue *)dest, v, MY_TRUE
);
return;
} /* end switch */
/* No more lvalues to follow, old value freed: do the assign next */
break;
} /* end for */
/* Transfer the value */
*dest = *v;
/* Protection against endless reference loops */
if (dest->type == T_LVALUE || dest->type == T_PROTECTED_LVALUE)
{
v->type = T_INVALID;
check_for_ref_loop(dest);
}
} /* inl_transfer_svalue() */
void transfer_svalue (svalue_t *dest, svalue_t *v)
{ inl_transfer_svalue(dest,v); }
#define transfer_svalue(dest,v) inl_transfer_svalue(dest,v)
/*-------------------------------------------------------------------------*/
static void
transfer_pointer_range (svalue_t *source)
/* Transfer the vector <source> to the vector range defined by
* <special_lvalue>, modifying the target vector in special_lvalue
* accordingly. <source> is freed once in the call.
*
* If <source> is not a vector, it is just freed.
*/
{
if (source->type == T_POINTER)
{
vector_t *sv; /* Source vector (from source) */
vector_t *dv; /* Destination vector (from special_lvalue) */
vector_t *rv; /* Result vector */
mp_int dsize; /* Size of destination vector */
mp_int ssize; /* Size of source vector */
mp_int index1, index2; /* First and last index of destination range */
mp_int i;
/* Setup the variables */
dsize = special_lvalue.size;
index1 = special_lvalue.index1;
index2 = special_lvalue.index2;
dv = special_lvalue.v.u.lvalue->u.vec;
sv = source->u.vec;
ssize = (mp_int)VEC_SIZE(sv);
#ifdef NO_NEGATIVE_RANGES
if (index1 > index2)
errorf("Illegal range [%ld..%ld] for assignment.\n"
, index1, index2-1
);
#endif /* NO_NEGATIVE_RANGES */
if (ssize + index1 - index2 == 0)
{
/* <source> fits exactly into the target range */
svalue_t *s, *d; /* Copy source and destination */
s = sv->item;
d = dv->item + index1;
ref_array(dv); /* protect against recursive refs during the copy */
/* If there is just one ref to the source, use the faster
* transfer instead of the slow assign for the copy.
*/
if (sv->ref == 1)
{
for (i = ssize; --i >= 0; )
{
transfer_svalue(d++, s++);
}
free_empty_vector(sv);
}
else /* sv->ref > 1 */
{
for (i = ssize; --i >= 0; )
{
assign_svalue(d++, s++);
}
free_array(sv);
/* deref_array() is not enough, because in situations
* where one d == sv, eg
* arr = ({ ({ 1 }) });
* arr[0..0] = arr[0];
* sv would be left behind with 0 refs but unfreed.
*/
}
free_array(dv); /* Undo the ref_array() above */
}
else
{
/* Create a new vector */
svalue_t *s, *d; /* Copy source and destination */
rv = allocate_array(dsize + ssize + index1 - index2);
special_lvalue.v.u.lvalue->u.vec = rv;
s = dv->item;
d = rv->item;
for (i = index1; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
s = sv->item;
for (i = ssize; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
free_array(sv);
s = dv->item + index2;
for (i = dsize - index2; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
free_array(dv); /* this can make the lvalue invalid to use */
}
}
else
/* Not a pointer: just free it */
free_svalue(source);
} /* transfer_pointer_range() */
/*-------------------------------------------------------------------------*/
static void
transfer_protected_pointer_range ( struct protected_range_lvalue *dest
, svalue_t *source)
/* Transfer the vector <source> to the vector range defined by
* <dest>, modifying the target vector in <dest>
* accordingly. <source> is freed once in the call.
*
* If <source> is not a vector, it is just freed.
*/
{
if (source->type == T_POINTER && dest->v.u.vec == dest->lvalue->u.vec)
{
vector_t *sv; /* Source vector (from source) */
vector_t *dv; /* Dest vector (from dest) */
vector_t *rv; /* Result vector */
mp_int dsize; /* Size of the dest vector */
mp_int ssize; /* Size of the source vector */
mp_int index1, index2; /* Target range indices */
mp_int i;
/* Setup the variables */
dsize = dest->size;
index1 = dest->index1;
index2 = dest->index2;
dv = dest->v.u.vec;
sv = source->u.vec;
ssize = (mp_int)VEC_SIZE(sv);
#ifdef NO_NEGATIVE_RANGES
if (index1 > index2)
errorf("Illegal range [%ld..%ld] for assignment.\n"
, index1, index2-1
);
#endif /* NO_NEGATIVE_RANGES */
if (ssize + index1 - index2 == 0)
{
/* <source> fits exactly into the target range */
svalue_t *s, *d; /* Copy source and destination */
s = sv->item;
d = dv->item + index1;
/* If there is just one ref to the source, use the faster
* transfer instead of the slow assign for the copy.
*/
if (sv->ref == 1)
{
for (i = ssize; --i >= 0; )
{
transfer_svalue(d++, s++);
}
free_empty_vector(sv);
}
else /* sv->ref > 1 */
{
for (i = ssize; --i >= 0; )
{
assign_svalue(d++, s++);
}
deref_array(sv);
/* The if() above effectively did the 'free_svalue(source)' */
}
}
else
{
/* Create a new vector */
svalue_t *s, *d; /* Copy source and destination */
rv = allocate_array(dsize + ssize + index1 - index2);
dest->lvalue->u.vec = rv;
s = dv->item;
d = rv->item;
for (i = index1; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
s = sv->item;
for (i = ssize; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
free_array(sv);
s = dv->item + index2;
for (i = dsize - index2; --i >= 0; )
{
assign_svalue_no_free(d++, s++);
}
free_array(dv); /* this can make the lvalue invalid to use */
}
}
else
{
/* Not a pointer: just free it */
free_svalue(source);
}
} /* transfer_protected_pointer_range() */
/*-------------------------------------------------------------------------*/
static void
assign_string_range (svalue_t *source, Bool do_free)
/* Transfer the string <source> to the string range defined by
* <special_lvalue>, modifying the target string in special_lvalue
* accordingly. If <do_free> is TRUE, <source> is freed once in the call.
*
* If <source> is not a string, it is just freed resp. ignored.
*/
{
if (source->type == T_STRING)
{
svalue_t *dsvp; /* destination svalue (from special_lvalue) */
string_t *ds; /* destination string (from dsvp) */
string_t *ss; /* source string (from source) */
string_t *rs; /* result string */
mp_int dsize; /* size of destination string */
mp_int ssize; /* size of source string */
mp_int index1, index2; /* range indices */
/* Set variables */
dsize = special_lvalue.size;
index1 = special_lvalue.index1;
index2 = special_lvalue.index2;
dsvp = special_lvalue.v.u.lvalue;
ds = dsvp->u.str;
ss = source->u.str;
ssize = (mp_int)mstrsize(ss);
#ifdef NO_NEGATIVE_RANGES
if (index1 > index2)
errorf("Illegal range [%ld..%ld] for assignment.\n"
, index1, index2-1
);
#endif /* NO_NEGATIVE_RANGES */
/* Create the new string */
rs = alloc_mstring((size_t)(dsize + ssize + index1 - index2));
if (!rs)
{
/* We don't pop the stack here --> don't free source */
outofmem((dsize + ssize + index1 - index2), "new string");
}
if (index1)
memcpy(get_txt(rs), get_txt(ds), (size_t)index1);
if (ssize)
memcpy(get_txt(rs) + index1, get_txt(ss), (size_t)ssize);
if (dsize > index2)
memcpy( get_txt(rs) + index1 + ssize, get_txt(ds) + index2
, (size_t)(dsize - index2));
/* Assign the new string in place of the old */
free_string_svalue(dsvp);
dsvp->u.str = rs;
if (do_free)
free_string_svalue(source);
}
else
{
/* Not a string: just free it */
if (do_free)
free_svalue(source);
}
} /* assign_string_range() */
/*-------------------------------------------------------------------------*/
static void
assign_protected_string_range ( struct protected_range_lvalue *dest
, svalue_t *source
, Bool do_free
)
/* Transfer the string <source> to the string range defined by
* <dest>, modifying the target string in dest
* accordingly.
*
* If <do_free> is TRUE, <source> and the protector <dest> are freed once
* in the call.
*
* If <source> is not a string, it is just freed resp. ignored.
*/
{
if (source->type == T_STRING)
{
svalue_t *dsvp; /* destination value (from dest) */
string_t *ds; /* destination string (from dsvp) */
string_t *ss; /* source string (from source) */
string_t *rs; /* result string */
mp_int dsize; /* size of destination string */
mp_int ssize; /* size of source string */
mp_int index1, index2; /* range indices */
/* Set variables */
dsize = dest->size;
index1 = dest->index1;
index2 = dest->index2;
dsvp = dest->lvalue;
ds = dest->v.u.str;
#ifdef NO_NEGATIVE_RANGES
if (index1 > index2)
errorf("Illegal range [%ld..%ld] for assignment.\n"
, index1, index2-1
);
#endif /* NO_NEGATIVE_RANGES */
/* If the lvalue is no longer valid, free it */
if (dsvp->u.str != ds)
{
if (do_free)
{
free_svalue(source);
free_mstring(dest->v.u.str);
xfree(dest);
}
return;
}
/* Create a new string */
ss = source->u.str;
ssize = (mp_int)mstrsize(ss);
rs = alloc_mstring((size_t)(dsize + ssize + index1 - index2));
if (!rs)
{
outofmem((dsize + ssize + index1 - index2), "new string");
}
if (index1)
memcpy(rs, ds, (size_t)index1);
if (ssize)
memcpy(rs + index1, ss, (size_t)ssize);
dest->index2 = (int)(index1 + ssize);
if (dsize > index2)
memcpy( get_txt(rs) + dest->index2, get_txt(ds) + index2
, (size_t)(dsize - index2));
xfree(ds);
dest->v.u.str = dsvp->u.str = rs;
if (do_free)
{
free_string_svalue(source);
free_protector_svalue(&dest->protector);
xfree(dest);
}
}
else
{
/* Not a string: just free it */
if (do_free)
{
free_svalue(source);
free_protector_svalue(&dest->protector);
xfree(dest);
}
}
} /* transfer_protected_string_range() */
/*-------------------------------------------------------------------------*/
static void
add_number_to_lvalue (svalue_t *dest, int i, svalue_t *pre, svalue_t *post)
/* Add the number <i> to the (PROTECTED_)LVALUE <dest>.
* If <pre> is not null, the <dest> value before the addition is copied
* into it.
* If <post> is not null, the <dest> value after the addition is copied
* into it.
* Both <pre> and <post> are supposed to be empty svalues when given.
*
* If <dest> is of the wrong type, an error is generated.
*/
{
/* Deref the T_(PROTECTED_)LVALUES */
do
dest = dest->u.lvalue;
while (dest->type == T_LVALUE || dest->type == T_PROTECTED_LVALUE);
/* Now increment the non-LVALUE */
switch (dest->type)
{
default:
errorf("Reference to bad type %s to ++/--\n", typename(dest->type));
break;
case T_NUMBER:
if (pre) put_number(pre, dest->u.number);
dest->u.number += i;
if (post) put_number(post, dest->u.number);
break;
case T_FLOAT:
{
STORE_DOUBLE_USED
double d;
d = READ_DOUBLE(dest);
if (pre)
{
pre->type = T_FLOAT;
STORE_DOUBLE(pre, d);
}
d += (double)i;
STORE_DOUBLE(dest, d);
if (post)
{
post->type = T_FLOAT;
STORE_DOUBLE(post, d);
}
break;
}
case T_PROTECTED_LVALUE:
add_number_to_lvalue(dest, i, pre, post);
break;
case T_CHAR_LVALUE:
if (pre) put_number(pre, (unsigned char)*dest->u.charp);
*(dest->u.charp) += i;
if (post) put_number(post, (unsigned char)*dest->u.charp);
break;
case T_PROTECTED_CHAR_LVALUE:
{
struct protected_char_lvalue *p;
p = (struct protected_char_lvalue *)dest;
if (p->lvalue->type == T_STRING
&& get_txt(p->lvalue->u.str) == p->start)
{
if (pre) put_number(pre, (unsigned char)*(p->v.u.charp));
i = (unsigned char)(*(p->v.u.charp) += i);
if (post) put_number(post, i);
}
break;
}
} /* switch() */
} /* add_number_to_lvalue() */
/*-------------------------------------------------------------------------*/
static vector_t *
inter_add_array (vector_t *q, vector_t **vpp)
/* Append array <q> to array *<vpp>. Both <q> and *<vpp> are freed,
* the result vector (just one ref) is assigned to *<vpp> and also returned.
*
* <inter_sp> is supposed to point at the two vectors and will be decremented
* by 2.
*/
{
vector_t *p; /* The second summand vector */
mp_int cnt;
vector_t *r; /* Result vector */
svalue_t *s, *d; /* Pointers for copying: src and dest */
size_t p_size, q_size; /* Sizes of p and q */
p = *vpp;
/* *vpp could be in the summands, thus don't free p / q before
* assigning.
* On the other hand, with an uninitialized array, we musn't assign
* before the copying is done.
*/
p_size = VEC_SIZE(p);
q_size = VEC_SIZE(q);
s = p->item;
/* Check the result size for legality - this leaves the code below
* to deal just with out of memory conditions.
*/
if (max_array_size && p_size + q_size > max_array_size)
{
errorf("Illegal array size: %ld.\n", (long)(p_size + q_size));
}
/* The optimized array-adding will transfer elements around, rendering
* the arrays on the stack inconsistent. Thus any out-of-memory
* error must not attempt to free them - leaking them is the lesser
* evil in this situation.
*/
inter_sp -= 2;
/* Out of memory might result in some memory leaks. Better that freeing
* arrays with 0 ref count, or indigestion in garbage_collection() .
* It will simply give some more debugging output...
*/
/* Allocate the result vector and copy p into it.
*/
if (!(p->ref-1))
{
/* p will be deallocated completely - try to optimize a bit */
/* We try to expand the existing memory for p (without moving)
* instead of allocating a completely new vector.
*/
d = malloc_increment_size(p, q_size * sizeof(svalue_t));
if ( NULL != d)
{
/* We got the additional memory */
r = p;
r->ref = 1;
r->size = p_size + q_size;
r->user->size_array -= p_size;
r->user = current_object->user;
r->user->size_array += p_size + q_size;
} else
/* Just allocate a new vector and memcopy p into it. */
{
r = allocate_uninit_array((p_int)(p_size + q_size));
deref_array(p);
d = r->item;
for (cnt = (mp_int)p_size; --cnt >= 0; )
{
*d++ = *s++;
}
}
}
else
{
/* p must survive: allocate a new vector and assign the values
* from p.
*/
r = allocate_uninit_array((p_int)(p_size + q_size));
deref_array(p);
d = r->item;
for (cnt = (mp_int)p_size; --cnt >= 0; ) {
assign_checked_svalue_no_free (d++, s++);
}
}
/* Here 'd' points to the first item to set */
/* Add the values from q. Again, try to optimize */
s = q->item;
if (q->ref == 1)
{
for (cnt = (mp_int)q_size; --cnt >= 0; )
{
if (destructed_object_ref(s))
{
assign_svalue(s, &const0);
}
*d++ = *s++;
}
*vpp = r;
free_empty_vector(q);
}
else /* q->ref > 1 */
{
for (cnt = (mp_int)q_size; --cnt >= 0; ) {
assign_checked_svalue_no_free (d++, s++);
}
*vpp = r;
deref_array(q);
}
if (!p->ref && p != q)
free_empty_vector(p);
return r;
} /* inter_add_array() */
/*=========================================================================*/
/* S T A C K */
/*-------------------------------------------------------------------------*/
/* The following functions handle the pushing and popping of the
* interpreter stack. Often functions appear in two versions: one version
* using the global variable <inter_sp>, the other version receiving and
* returning the old/new stack pointer as argument and result.
*
* Obviously, the former version can be easily called from outside the
* interpreter, while the latter allows better optimization.
*
* To make things even more complicated, some of the 'slower' functions
* are redefined with preprocessor macros to use the faster function - this
* is meant to make the code in this module faster, but relies on certain
* naming conventions (e.g. that 'sp' is always the local copy of the
* stack pointer).
*
* TODO: Streamline the functions, given them macros as fast alternative
* TODO:: publish them all in interpret.h and enforce their use.
*-------------------------------------------------------------------------
* The functions are:
*
* put_c_string (sp, p)
* Convert the C-String <p> into a mstring and put it into <sp>.
* push_svalue(v), push_svalue_block(num,v):
* Push one or more svalues onto the stack.
* pop_stack(), _drop_n_elems(n,sp):
* Pop (free) elements from the stack.
* stack_overflow(sp,fp,pc):
* Handle a stack overflow.
* push_referenced_mapping(m):
* Push a mapping onto the stack.
* push_error_handler(h)
* Push an errorhandler entry onto the stack.
*/
/*-------------------------------------------------------------------------*/
void
put_c_string (svalue_t *sp, const char *p)
/* Put a copy of the C string *<p> into <sp>.
*/
{
string_t * str;
memsafe(str = new_mstring(p), strlen(p), "string");
put_string(sp, str);
} /* put_c_string() */
/*-------------------------------------------------------------------------*/
void
put_c_n_string (svalue_t *sp, const char *p, size_t len)
/* Put a copy of first <len> characters of the C string *<p> into <sp>.
*/
{
string_t * str;
memsafe(str = new_n_mstring(p, len), len, "string");
put_string(sp, str);
} /* put_c_n_string() */
/*-------------------------------------------------------------------------*/
void
push_svalue (svalue_t *v)
/* Push the svalue <v> onto the stack as defined by <inter_sp>.
* Same semantic as assign_svalue_no_free().
*/
{
assign_svalue_no_free(++inter_sp, v);
}
/*-------------------------------------------------------------------------*/
void
push_svalue_block (int num, svalue_t *v)
/* Push all <num> svalues starting at <v> onto the stack as defined by
* <inter_sp>. Same semantic as assign_svalue_no_free().
*/
{
svalue_t *w;
for (w = inter_sp; --num >= 0; v++)
{
w++;
assign_lrvalue_no_free(w, v);
}
inter_sp = w;
}
/*-------------------------------------------------------------------------*/
static INLINE void
_pop_stack (void)
/* Pop the topmost element from the stack as defined by <inter_sp>,
* using free_svalue().
*/
{
#ifdef DEBUG
if (inter_sp < VALUE_STACK)
fatal("VM Stack underflow: %ld too low.\n", (long)(VALUE_STACK - inter_sp));
#endif
free_svalue(inter_sp--);
}
void pop_stack (void) { _pop_stack(); }
/*-------------------------------------------------------------------------*/
static INLINE svalue_t *
_pop_n_elems (int n, svalue_t *sp)
/* Pop the <n> topmost elements from the stack, currently ending at <sp>,
* and return the new stackpointer.
* The elements are freed using free_svalue().
*/
{
#ifdef DEBUG
if (n < 0)
fatal("pop_n_elems: %d elements.\n", n);
#endif
for (; --n >= 0; )
{
free_svalue(sp--);
}
return sp;
}
svalue_t * pop_n_elems (int n, svalue_t *sp)
{ return _pop_n_elems(n, sp); }
/*-------------------------------------------------------------------------*/
static void
stack_overflow (svalue_t *sp, svalue_t *fp, bytecode_p pc)
/* Recover from a stack overflow by popping all the elements between the
* current stack end <sp> and the begin of the frame <fp>.
* The function then assigns the new <sp> == <fp> and the <pc> to the
* corresponding inter_xx variables and generates an error.
*/
{
if (sp >= &VALUE_STACK[SIZEOF_STACK])
fatal("Fatal stack overflow: %ld too high.\n"
, (long)(sp - &VALUE_STACK[SIZEOF_STACK])
);
sp = _pop_n_elems(sp-fp, sp);
ERROR("stack overflow\n");
}
/*-------------------------------------------------------------------------*/
void
push_referenced_mapping (mapping_t *m)
/* Push mapping <m> onto the stack as defined by <inter_sp>.
* The refs of <m> are _not_ incremented.
*/
{
inter_sp++;
put_mapping(inter_sp, m);
}
/*-------------------------------------------------------------------------*/
void
push_error_handler(void (*errorhandler)(svalue_t *), svalue_t *arg)
/* Push the <errorhandler>() with the argument <arg> as error handler
* onto the stack.
* This means that a new T_LVALUE is created on the stack, pointing
* to <arg>. <arg> itself is setup to be a T_ERROR_HANDLER value.
*/
{
arg->type = T_ERROR_HANDLER;
arg->u.error_handler = errorhandler;
inter_sp++;
inter_sp->type = T_LVALUE;
inter_sp->u.lvalue = arg;
} /* push_error_handler() */
/*-------------------------------------------------------------------------*/
/* Fast version of several functions, must come last so to not disturb
* the actual definitions:
*/
#define pop_stack() free_svalue(sp--)
#define pop_n_elems(n) (sp = _pop_n_elems((n), sp))
/*=========================================================================*/
/* I N D E X I N G */
/*-------------------------------------------------------------------------*/
/* The following functions are concerned with the indexing of single
* elements and ranges of strings, vectors and mappings, both as rvalue
* and lvalue.
*
* Most of the functions are just the implementations of the corresponding
* machine operators and are called just from the interpreter switch().
* The actual arguments are pulled from the vm stack and the results pushed;
* the functions receive the current stackpointer and programcounter as
* function call parameters. The program counter is usally only used to
* update <inter_pc> in case of errors. Result of the call is the new
* stackpointer pointing to the result on the machine stack.
*
* Some typical layouts:
*
* (LVALUE) -> indexed svalue from vector/mapping
* (might be copied into indexing_quickfix)
*
* by: push_(r)indexed_lvalue()
* (r)index_lvalue()
*
*
* (LVALUE) -> (CHAR_LVALUE)
* special_lvalue.u.charp -> character in untabled string
*
* by: (r)index_lvalue() on string lvalues
*
*
* (LVALUE) -> (PROTECTED_LVALUE) -> indexed svalue in vector/mapping
* protector -> vector/mapping
* by: push_protected_(r)indexed_lvalue()
* push_protected_indexed_map_lvalue()
* protected_(r)index_lvalue()
*
*
* (LVALUE) -> (PROTECTED_CHAR_LVALUE)
* .lvalue -> untabled string svalue
* .charp -> indexed character in untabled string
* .start -> first character of actual string text
* .protector: T_INVALID or the string's .protector value
* if the string itself is result of a protected
* lvalue index.
*
* by: protected_(r)index_lvalue() on string lvalue
*
*
* (LVALUE) -> (T_{STRING,POINTER}_RANGE_LVALUE)
* special_lvalue.v -> indexed-on string/vector
* special_lvalue.size: size of the string/vector
* .ind1: lower index
* .ind2: upper index
*
* by: range_lvalue()
*
*
* (LVALUE) -> (T_PROTECTED_{STRING,POINTER}_RANGE_LVALUE)
* .v : indexed-on string/vector
* .lvalue -> svalue of indexed-on string/vector
* .size: size of the string/vector
* .ind1: lower index
* .ind2: upper index
* .protector: the protector of the initial lvalue, if any.
*
* by: protected_range_lvalue()
*
*
* TODO: A lot of the functions differ only in minute details - test how
* TODO:: much time merging the functions (and adding if()s for the
* TODO:: differences) really costs.
*-------------------------------------------------------------------------
* The functions (in a LPCish notation) are:
*
* push_indexed_lvalue(vector|mapping v, int|mixed i)
* Return &(v[i]), unprotected.
* push_rindexed_lvalue(vector v, int i)
* Return &(v[<i]), unprotected.
* push_aindexed_lvalue(vector v, int i)
* Return &(v[>i]), unprotected.
* push_protected_indexed_lvalue(vector|mapping v, int|mixed i)
* Return &(v[i]), protected.
* push_protected_rindexed_lvalue(vector v, int i)
* Return &(v[<i]), protected.
* push_protected_aindexed_lvalue(vector v, int i)
* Return &(v[>i]), protected.
* push_protected_indexed_map_lvalue(mapping m, mixed i, int j)
* Return &(m[i:j]), protected.
* index_lvalue(vector|mapping|string & v, int|mixed i)
* Return &(*v[i]), unprotected, using special_lvalue.
* rindex_lvalue(vector|string & v, int i)
* Return &(*v[<i]), unprotected, using special_lvalue.
* aindex_lvalue(vector|string & v, int i)
* Return &(*v[>i]), unprotected, using special_lvalue.
* protected_index_lvalue(vector|mapping|string & v, int|mixed i)
* Return &(*v[i]), protected.
* protected_rindex_lvalue(vector|string & v, int i)
* Return &(*v[<i]), protected.
* protected_aindex_lvalue(vector|string & v, int i)
* Return &(*v[>i]), protected.
* range_lvalue(vector|string & v, int i2, int i1)
* Return &(*v[i1..i2]), unprotected, using special_lvalue.
* protected_range_lvalue(vector|string & v, int i2, int i1)
* Return &(*v[i1..i2]), protected.
* push_indexed_value(string|vector|mapping|struct v, int|mixed i)
* Return v[i].
* push_rindexed_value(string|vector v, int i)
* Return v[<i].
* push_aindexed_value(string|vector v, int i)
* Return v[>i].
*/
/*-------------------------------------------------------------------------*/
static INLINE svalue_t *
get_vector_item (vector_t * vec, svalue_t * i, svalue_t *sp, bytecode_p pc)
/* Index vector <vec> with index <i> and return the pointer to the
* indexed item.
* If the index is invalid, throw an error.
*/
{
int ind;
svalue_t * item;
if (i->type != T_NUMBER)
{
ERRORF(("Illegal index for []: got %s, expected number.\n"
, typename(i->type)
));
return NULL;
}
else
{
ind = i->u.number;
if (ind < 0)
{
ERROR("Illegal index for []: not a positive number.\n");
/* NOTREACHED */
return NULL;
}
if (ind >= VEC_SIZE(vec))
{
ERRORF(("Index for [] out of bounds: %ld, vector size: %lu\n"
, (long)ind, VEC_SIZE(vec)));
/* NOTREACHED */
return NULL;
}
}
/* Compute the indexed element */
item = &vec->item[ind];
if (destructed_object_ref(item))
{
free_svalue(item);
put_number(item, 0);
}
return item;
} /* get_vector_item() */
/*-------------------------------------------------------------------------*/
static INLINE svalue_t *
get_vector_r_item (vector_t * vec, svalue_t * i, svalue_t *sp, bytecode_p pc)
/* Reverse-index vector <vec> with index <i> and return the pointer to the
* indexed item.
* If the index is invalid, throw an error.
*/
{
int ind;
svalue_t * item;
if (i->type != T_NUMBER)
{
ERRORF(("Illegal index for [<]: got %s, expected number.\n"
, typename(i->type)
));
return NULL;
}
if ((ind = i->u.number) < 0)
{
ERROR("Illegal index for [<]: not a positive number.\n");
return NULL;
}
if ( (ind = (mp_int)VEC_SIZE(vec) - ind) < 0
|| ind >= (mp_int)VEC_SIZE(vec)
)
{
ERRORF(("Index out of bounds for [<]: %ld, vector size: %lu.\n"
, (long)(i->u.number), VEC_SIZE(vec)));
return NULL;
}
/* Compute the indexed element */
item = &vec->item[ind];
if (destructed_object_ref(item))
{
free_svalue(item);
put_number(item, 0);
}
return item;
} /* get_vector_r_item() */
/*-------------------------------------------------------------------------*/
static INLINE svalue_t *
get_vector_a_item (vector_t * vec, svalue_t * i, svalue_t *sp, bytecode_p pc)
/* Arithmetic-index vector <vec> with index <i> and return the pointer to the
* indexed item.
* If the index is invalid, throw an error.
*/
{
int ind;
svalue_t * item;
if (i->type != T_NUMBER)
{
ERRORF(("Illegal index for [>]: got %s, expected number.\n"
, typename(i->type)
));
return NULL;
}
if (0 > (ind = i->u.number))
ind = (mp_int)VEC_SIZE(vec) + ind;
if (ind < 0 || ind >= (mp_int)VEC_SIZE(vec))
{
ERRORF(("Index out of bounds for [>]: %ld, vector size: %lu.\n"
, (long)(i->u.number), VEC_SIZE(vec)));
return NULL;
}
/* Compute the indexed element */
item = &vec->item[ind];
if (destructed_object_ref(item))
{
free_svalue(item);
put_number(item, 0);
}
return item;
} /* get_vector_a_item() */
/*-------------------------------------------------------------------------*/
static INLINE char *
get_string_item ( svalue_t * svp, svalue_t * i, Bool make_singular
, Bool allow_one_past
, svalue_t *sp, bytecode_p pc)
/* Index string <svp> with index <i> and return the pointer to the
* indexed item.
* If <make_singular> is TRUE, <svp> is made an untabled string
* with just one reference.
* If <allow_one_past> is TRUE, indexing one past the official end
* of the string for retrieval purposes is ok. TODO: Remove this.
* If the index is invalid, throw an error.
*/
{
mp_int ind;
if (i->type != T_NUMBER)
{
ERRORF(("Illegal index for []: got %s, expected number.\n"
, typename(i->type)
));
return NULL;
}
else
{
ind = i->u.number;
if (ind < 0)
{
ERROR("Illegal index for []: not a positive number.\n");
return NULL;
}
if (ind > (mp_int)mstrsize(svp->u.str) )
{
ERRORF(("Index out for [] of bounds: %ld, string length: %ld.\n"
, (long)ind, (long)mstrsize(svp->u.str)));
return NULL;
}
if (ind == (mp_int)mstrsize(svp->u.str))
{
if (!allow_one_past)
{
ERRORF(("Index out of bounds for []: %ld, string length: %ld.\n"
, (long)ind, (long)mstrsize(svp->u.str)));
return NULL;
}
else if (!runtime_no_warn_deprecated)
warnf( "Warning: Indexing past string end is deprecated: "
"index %ld, string length: %ld.\n"
, (long)ind, (long)mstrsize(svp->u.str)
);
}
}
/* The basic idea here was to to create a new copy of the string only
* if the string is not singular (aka !mstr_singular(svp->u.str)).
* Unfortunately local variable lvalues are pushed without counting
* the additional reference, so we now have to play it safe and
* duplicate the string whenever requested.
*/
if (make_singular)
{
string_t *p;
memsafe(p = unshare_mstring(svp->u.str), mstrsize(svp->u.str)
, "modifiable string");
svp->u.str = p;
}
return &(get_txt(svp->u.str)[ind]);
} /* get_string_item() */
/*-------------------------------------------------------------------------*/
static INLINE char *
get_string_r_item (svalue_t * svp, svalue_t * i, Bool make_singular
, Bool allow_one_past
, svalue_t *sp, bytecode_p pc)
/* Reverse-Index string <svp> with index <i> and return the pointer to the
* indexed item.
* If <allow_one_past> is TRUE, indexing one past the official end
* of the string for retrieval purposes is ok. TODO: Remove this.
* If <make_singular> is TRUE, <svp> is made an untabled string
* with just one reference.
* If the index is invalid, throw an error.
*/
{
mp_int ind;
if (i->type != T_NUMBER)
{
ERRORF(("Illegal index for [<]: got %s, expected number.\n"
, typename(i->type)
));
return NULL;
}
else
{
ind = i->u.number;
if ((ind = i->u.number) < 0)
{
ERROR("Illegal index for [<]: not a positive number.\n");
return NULL;
}
/* Compute the real index. Allow ""[<1]. */
ind = (mp_int)mstrsize(svp->u.str) - ind;
if (!mstrsize(svp->u.str) && ind == -1)
ind = 0;
if ( ind < 0
|| ind > (mp_int)mstrsize(svp->u.str)
)
{
ERRORF(("Index out of bounds for [<]: %ld, string length: %ld\n"
, (long) i->u.number, (long)mstrsize(svp->u.str)));
return NULL;
}
if (ind == (mp_int)mstrsize(svp->u.str))
{
if (!allow_one_past)
{
ERRORF(("Index out for [<] of bounds: %ld, string length: %ld.\n"
, (long)ind, (long)mstrsize(svp->u.str)));
return NULL;
}
else if (!runtime_no_warn_deprecated)
warnf( "Warning: Indexing past string end is deprecated: "
"index %ld, string length: %ld.\n"
, (long)ind, (long)mstrsize(svp->u.str)
);
}
}
/* The basic idea here was to to create a new copy of the string only
* if the string is not singular (aka !mstr_singular(svp->u.str)).
* Unfortunately local variable lvalues are pushed without counting
* the additional reference, so we now have to play it safe and
* duplicate the string whenever requested.
*/
if (make_singular)
{
string_t *p;
memsafe(p = unshare_mstring(svp->u.str), mstrsize(svp->u.str)
, "modifiable string");
svp->u.str = p;
}
return &(get_txt(svp->u.str)[ind]);
} /* get_string_r_item() */
/*-------------------------------------------------------------------------*/
static INLINE char *
get_string_a_item (svalue_t * svp, svalue_t * i, Bool make_singular
, Bool allow_one_past
, svalue_t *sp, bytecode_p pc)
/* Arithmetic-Index string <svp> with index <i> and return the pointer to the
* indexed item.
* If <allow_one_past> is TRUE, indexing one past the official end
* of the string for retrieval purposes is ok. Showing the first 100 KB of 629.0 KB. Download the archive for the full file.