object.c

ldmud-3.4.1/src/object.c · 244.8 KB

From the archive ldmud-3.4.1.tar.gz

Download the archive   « Back to the archive contents

/*---------------------------------------------------------------------------
 * Object handling.
 *
 *---------------------------------------------------------------------------
 * Objects are the core of LPMud: everything a players sees, handles and
 * is, is an object. Unfortunately this also means that a lot of object
 * related functions are scattered all over the driver, so this file is
 * actually quite short.
 *
 * The first part deals with the creation and deallocation of objects
 * and programs. The second parts implements a pointer table which can
 * be used to sequentialize the set of arrays and mappings, detecting
 * cycles and shared usages while doing this. The last and largest part
 * are the functions to save an object into a save file, and restoring
 * it from there.
 *
 * -- object_t --
 *
 *   object_t {
 *       unsigned short  flags;
 *       p_int           ref;
#ifdef USE_SET_LIGHT
 *       short           total_light;
#endif
 *       mp_int          time_reset;
 *       mp_int          time_of_ref;
 *       mp_int          time_cleanup;
 *       mp_int          load_time;
 *       p_int           load_id;
 *       p_int           extra_ref;            (ifdef DEBUG)
 *       program_t     * prog;
 *       string_t      * name;
 *       string_t      * load_name;
 *       object_t      * next_all;
 *       object_t      * prev_all;
 *       object_t      * next_hash;
 *       object_t      * next_inv;
 *       object_t      * contains;
 *       object_t      * super;
 * TODO: The environment members (plus light) could be put into a special
 * TODO:: sentence and thus concentrated in a separated source file.
 *       sentence_t    * sent;
 *       wiz_list_t    * user;
 *       wiz_list_t    * eff_user;
 *       int             extra_num_variables;  (ifdef DEBUG)
 *       svalue_t      * variables;
 *       unsigned long   ticks, gigaticks;
 *   }
 *
 * The .flags collect some vital information about the object:
 *     O_HEART_BEAT       : the object has a heartbeat
#ifdef USE_SET_IS_WIZARD
 *     O_IS_WIZARD        : the object is a 'wizard' - this bit is set with
 *                          the efun set_is_wizard()
#endif
 *     O_ENABLE_COMMANDS  : can execute commands ("is a living")
 *     O_CLONE            : is a clone, or uses a replaced program
 *     O_DESTRUCTED       : has actually been destructed
 *     O_SWAPPED          : program and/or variables have been swapped out
 *     O_ONCE_INTERACTIVE : is or was interactive
 *     O_RESET_STATE      : is in a virgin resetted state
 *     O_WILL_CLEAN_UP    : call clean_up() when time is due
 *     O_LAMBDA_REFERENCED: a reference to a lambda was taken; this may
 *                          inhibit a replace_program().
 *     O_SHADOW           : object is shadowed
 *     O_REPLACED         : program was replaced.
 *
 * .ref counts the number of references to this object: it is this count
 * which can keep a destructed object around. Destructed objects are
 * stripped of everything but the basic object_t, but this one
 * is kept until the last reference is gone.
 *
 * .time_of_ref is the time() of the last apply on this object. The swapper
 * uses this timestamp to decide whether to swap the object or not.
 *
 * .time_cleanup is the time() when the next variable cleanup is due.
 *
 * Similar, .time_reset is the time() when the object should be reset
 * again. A time of 0 means: never.
 * The timing is not strict: any time after the given time is
 * sufficient. A reset object has its O_RESET_STATE flag set, which is
 * reset in an apply. If the time of reset is reached, but the object
 * is still in a reset state, or it is swapped out, the backend simply
 * sets a new .time_reset time, but does not do any real action.
 * To reduce the lag caused by the reset calls, all objects are kept
 * in the reset_table sorted by their time_reset. The .next_reset pointer
 * is used to built the table.
 *
 * .load_time simply is the time when the object was created. .load_id
 * serves to determine the creation order of objects created at the
 * same .load_time - this is used mostly for efuns like clones().
 *
 * .prog is a pointer to the program_tm, the bunch of bytecode for
 * this object. The program is shared between the master object (the
 * blueprint) and its clones. It is possible to replace the program
 * of a single object with a different one, but special care has
 * to be taken if lambda closures have been created.
 *
 * .variables is the block of variables of this object. Obviously they
 * can't be shared between master and clones. The number of variables
 * implicitely known by the program.
 *
 * .name and .load_name are the two names of the object. .name (an untabled
 * string) is the objects 'real' name: something like "std/thing" for
 * a blueprint, and "std/thing#45" for a clone. This name never has
 * a leading '/'. However, this name can be changed with the efun
 * rename_object().
 *
 * The .load_name (a tabled string) is the name of the file from which
 * the object was created. It is identical in both blueprint and clones
 * (in our example "/std/thing") and can't be changed. In compat mode,
 * this name has no leading '/'. However, for virtual objects .load_name
 * is the virtual name - the real program name is .prog->name.
 *
 * Both .name and .load_name never contain a '\0' as part of the name.
 *
 * .sent is the list of annotations to the object. Primary use is to
 * hold the list of commands ("sentences") defined by this object. Just
 * the first entry in this list has a special role: if the object is
 * shadowed, interactive, or using the editor, it is a "shadow_t"
 * and keeps the list of shadows resp. the other information.
 *
 * .user points to the wizlist entry of the wizard who 'owns' this
 * object. The entry is used to collect several stats for this user.
 * .eff_user describes the rights of this object. .eff_user can be
 * NULL, while .user can't.
 *
 * .ticks and .gigaticks count how much time the interpreter spent
 * in this particular object. The number is kept in two variables
 * to prevent overflows, it can be computed as gigaticks * 1E9 + ticks.
 *
 * .next_all, .prev_all and .next_hash are used to store the object.
 * .next_all and .prev_all are the link pointers in the list of all
 * objects, .next_hash is the link pointer in the object table (see otable.c).
 *
 * The gamedriver implements an environment/inventory system. .super
 * points to an object's surrounding object (and can be NULL), .contains
 * is the head of the list of contained objects. This inventory list
 * is linked by the .next_inv pointer.
 *
 * Related to the environment system is .total_light, which gives
 * total light emitted by the object including all its inventory. The
 * system is very crude and hardly used anymore. There it is completely
 * deactivated if the efun set_light() is not defined.
 *
 * .extra_ref and .extra_num_variables are used by check_a_lot_of_refcounts().
 *
 *
 * A word about swapping: when an object is not in use for longer time,
 * the driver swaps out the program and/or the objects variables, and the
 * swapper assigns an even 'swapnum' each. If an object is swapped, the
 * O_SWAPPED flag is set and the affected pointer (.prog or .variables)
 * is replaced by the assigned swap_num _with the lowest bit set_. Since
 * pointers are assumed to always be even, this allows to distinguish
 * swapped programs/variables from unswapped ones.
 *
 * The exact structure of programs and variables is explained in exec.h .
 *---------------------------------------------------------------------------
 */

#include "driver.h"
#include "typedefs.h"

#include "my-alloca.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>

#include "object.h"

#include "actions.h"
#include "array.h"
#include "backend.h"
#include "closure.h"
#include "comm.h"
#include "filestat.h"
#include "interpret.h"
#include "instrs.h"
#include "lex.h"
#include "main.h"
#include "mapping.h"
#include "mempools.h"
#include "mstrings.h"
#include "otable.h"
#include "prolang.h"
#include "ptrtable.h"
#include "random.h"
#include "sent.h"
#include "simulate.h"
#include "simul_efun.h"
#include "stdstrings.h"
#include "strfuns.h"
#ifdef USE_STRUCTS
#include "structs.h"
#endif /* USE_STRUCTS */
#include "swap.h"
#include "svalue.h"
#include "wiz_list.h"
#include "xalloc.h"

#include "../mudlib/sys/driver_hook.h"
#include "../mudlib/sys/functionlist.h"
#include "../mudlib/sys/include_list.h"
#include "../mudlib/sys/inherit_list.h"

/*-------------------------------------------------------------------------*/

replace_ob_t *obj_list_replace = NULL;
  /* List of scheduled program replacements.
   */

long tot_alloc_object = 0;
long tot_alloc_object_size = 0;
  /* Total number of allocated object, and the sum of memory they use.
   */

object_t NULL_object = { 0 };
  /* static null object for initialisations. memset() is not sufficient
   * because some machines (e.g. Bull) have a (char*)0 which is not
   * binary zero. Structure assignment otoh works.
   */

Bool dest_last_ref_gone = MY_FALSE;
  /* This flag is set to TRUE if the second-to-last reference to
   * a destructed is removed, as this usually means that it can be removed
   * from the list of destructed objects and deallocated altogether.
   * The flag is used to avoid unnecessary scans of the list of destructed
   * objects by the backend in the meantime.
   */

/*-------------------------------------------------------------------------*/
#ifndef CHECK_OBJECT_REF
void
dealloc_object (object_t *ob)
#else
void
dealloc_object ( object_t *ob, const char * file, int line)
#endif

/* Deallocate/dereference all memory and structures held by <ob>.
 * At the time of call, the object must be have at no refcount left,
 * must be destructed and removed from the object table and lists.
 */

{
#ifdef DEBUG

    /* Check the reference count */

    if (ob->ref > 0)
        fatal("Object with %ld refs passed to _free_object()\n", ob->ref);

#if 0 && defined(CHECK_OBJECT_REF)
    if (strchr(get_txt(ob->name), '#') == NULL)
        printf("DEBUG: (%s:%d) free_object(%p '%s') ref %ld flags %x\n"
              , file, line, ob, get_txt(ob->name), ob->ref, ob->flags);
#elif defined(CHECK_OBJECT_REF)
#   ifdef __MWERKS__
#       pragma unused(file)
#       pragma unused(line)
#   endif
#endif
    if (d_flag)
        printf("%s free_object: %s.\n", time_stamp(), get_txt(ob->name));

    /* Freeing a non-destructed object should never happen */

    if (!(ob->flags & O_DESTRUCTED)) {
        fatal("Object 0x%lx %s ref count 0, but not destructed.\n"
             , (long)ob, get_txt(ob->name));
    }

#endif /* DEBUG */

    if (ob->sent)
        fatal("free_object: Object '%s' (ref %ld, flags %08x) "
              "still has sentences.\n"
             , get_txt(ob->name), ob->ref, ob->flags);

    /* If the program is freed, then we can also free the variable
     * declarations.
     */
    if (ob->prog)
    {
        program_t *prog = ob->prog;
#ifdef CHECK_OBJECT_STAT
        if (check_object_stat)
        {
            fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) free( %p '%s') with %d vars : %ld -> (%ld:%ld)\n"
                          , tot_alloc_object, tot_alloc_object_size, ob, ob->name ? get_txt(ob->name) : "<null>"
                          , prog->num_variables
                          , (long)(prog->num_variables * sizeof (svalue_t) + sizeof (object_t))
                          , (long)tot_alloc_object
                          , (long)(tot_alloc_object_size - (prog->num_variables * sizeof (svalue_t) + sizeof (object_t)))
                          );
        }
#endif
        tot_alloc_object_size -=
            prog->num_variables * sizeof (svalue_t) +
            sizeof (object_t);
        free_prog(prog, MY_TRUE);
        ob->prog = NULL;
    }
#ifdef CHECK_OBJECT_STAT
    else
    {
        if (check_object_stat)
        {
            fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) free( %p '%s') has no program\n"
                          , tot_alloc_object, tot_alloc_object_size, ob, ob->name ? get_txt(ob->name) : "<null>");
        }
    }
#endif

    /* Deallocate the name */
    if (ob->name)
    {
        if (d_flag > 1)
            debug_message("%s Free object %s\n", time_stamp(), get_txt(ob->name));
        if (lookup_object_hash(ob->name) == ob)
            fatal("Freeing object %s but name still in name table\n"
                 , get_txt(ob->name));
#ifdef CHECK_OBJECT_STAT
        if (check_object_stat)
        {
            fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) free( %p '%s') with name : %ld -> (%ld:%ld)\n"
                          , tot_alloc_object, tot_alloc_object_size, ob, get_txt(ob->name)
                          , mstrsize(ob->name)
                          , tot_alloc_object-1
                          , tot_alloc_object_size - (mstrsize(ob->name)+1)
                          );
        }
#endif
        tot_alloc_object_size -= mstrsize(ob->name);
        free_mstring(ob->name);
        ob->name = NULL;
    }
#ifdef CHECK_OBJECT_STAT
    else
    {
        if (check_object_stat)
        {
            fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) free( %p ) has no name -> (%ld:%ld)\n"
                          , tot_alloc_object, tot_alloc_object_size, ob
                          , tot_alloc_object-1
                          , tot_alloc_object_size);
        }
    }
#endif

    /* Dereference the load_name */
    if (ob->load_name)
    {
        free_mstring(ob->load_name);
        ob->load_name = NULL;
    }

    /* Free the object structure */
    tot_alloc_object--;
    xfree(ob);
} /* dealloc_object() */

/*-------------------------------------------------------------------------*/
object_t *
get_empty_object (int num_var)

/* Allocate a new, empty object with <numvar> variables (set to 0)
 * and return it.
 * Return NULL when out of memory.
 */

{
static mp_int last_time = 0;
static mp_int last_id = 0;

    object_t *ob;
    size_t size = sizeof (object_t);
    size_t size2 = num_var * sizeof (svalue_t);
    int i;
    svalue_t *ob_vars;

    /* Allocate the object structure */

    if ( !(ob = xalloc(size)) )
        return NULL;

    ob_vars = NULL;

    /* Allocated the variable block */

    if (size2 && !(ob_vars = xalloc(size2)) )
    {
        xfree(ob);
        return NULL;
    }

#ifdef CHECK_OBJECT_STAT
    if (check_object_stat)
    {
        fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) new( %p ) with %d vars : %ld -> (%ld:%ld)\n"
                      , tot_alloc_object, tot_alloc_object_size, ob
                      , num_var
                      , (long)(size2+size)
                      , tot_alloc_object+1
                      , tot_alloc_object_size + size + size2
                      );
    }
#endif
    tot_alloc_object++;
    tot_alloc_object_size += size + size2;

    /* Clear and initialise the object (no memset!) */

    *ob = NULL_object;
    ob->ref = 1;
    ob->load_time = current_time;
    if (last_time == current_time)
        ob->load_id = ++last_id;
    else
    {
        ob->load_id = last_id = 0;
        last_time = current_time;
    }
#ifdef DEBUG
    ob->extra_num_variables = num_var;
#endif
    ob->variables = ob_vars;

    ob->time_cleanup = current_time + ((time_to_cleanup > 0) ? time_to_cleanup
                                                             : 3600);

    /* Initialize the variables */

    for (i = num_var; --i >= 0; )
    {
        ob_vars[i] = const0;
    }

    /* That's it. */
    return ob;
}  /* get_empty_object() */

/*-------------------------------------------------------------------------*/
void
init_object_variables (object_t *ob)

/* The variables of object <ob> are initialized.
 * First, if <ob> is a clone, all variables marked as !VAR_INITIALIZED are
 * copied over from the blueprint.
 * 
 * Then, for all <ob>, __INIT() is called in <ob> which initializes all
 * the variables marked as VAR_INITIALIZED in clones, and all variables
 * in blueprints.
 */

{
    /* For clones, copy the shared variable values */
    if ((ob->flags & O_CLONE))
    {
        object_t *bp;
        int i;
        variable_t *p_vars;
        svalue_t *ob_vars, *bp_vars;

        bp = ob->prog->blueprint;
        if (!bp || bp->flags & O_DESTRUCTED)
        {
            if (bp) free_object(bp, "init_object_variables");
            ob->prog->blueprint = NULL;
            bp_vars = NULL;
        }
        else
            bp_vars = bp->variables;

        ob_vars = ob->variables;
        p_vars = ob->prog->variables;

        for (i = ob->prog->num_variables; --i >= 0; )
        {
            if (p_vars[i].type.typeflags & VAR_INITIALIZED)
                continue;
            if (!bp_vars)
                errorf("Can't initialize object '%s': no blueprint.\n"
                     , get_txt(ob->name));
            assign_svalue_no_free(&ob_vars[i], &bp_vars[i]);
        }
    }

    /* Initialized all other variables programmatically */
    sapply_ign_prot(STR_VARINIT, ob, 0);
} /* init_object_variables() */

/*-------------------------------------------------------------------------*/
#ifdef DEALLOCATE_MEMORY_AT_SHUTDOWN

void
remove_all_objects (void)

/* Call destruct_object() for every object on the object list, then
 * call remove_destructed_objects() to actually remove them.
 *
 * This function is called from simulate.c when the game is shut down.
 */

{
    object_t *ob;
    svalue_t v;

    v.type = T_OBJECT;
    for (ob = obj_list; ob; ob = ob->next_all)
    {
#ifdef DEBUG
        if (ob->flags & O_DESTRUCTED) /* TODO: Can't happen */
            continue;
#endif
        v.u.ob = ob;
        destruct_object(&v);
        if ( !(ob->flags & O_DESTRUCTED) )
            break;
    }
    remove_destructed_objects(MY_TRUE);
}

#endif

/*-------------------------------------------------------------------------*/
void
reference_prog (program_t *progp, char *from)

/* Increment the refcount of program <progp>, called from location <from>.
 */

{
    progp->ref++;
    if (d_flag)
        printf("%s reference_prog: %s ref %ld (%s)\n"
              , time_stamp(), get_txt(progp->name), progp->ref, from);
}

/*-------------------------------------------------------------------------*/
void
do_free_sub_strings (int num_strings,   string_t **strings
                    ,int num_variables, variable_t *variables
                    ,int num_includes,  include_t *includes
#ifdef USE_STRUCTS
                    ,int num_structs,  struct_def_t *struct_defs
#endif /* USE_STRUCTS */
                    )

/* Free a bunch of shared strings used in connection with an object:
 * the <num_strings> strings in the array <strings>,
 * the <num_variables> names and type objects of the vars in array <variables>, 
 * the <num_includes> names of the includes in array <includes>,
#ifdef USE_STRUCTS
 * the <num_structs> names of the struct defs in array <struct_defs>, and.
#endif
 *
 * The function is called from free_prog() and from the compiler epilog().
 */

{
    int i;

    /* Free all strings */
    for (i = 0; i < num_strings; i++)
        free_mstring(strings[i]);

    /* Free all variable names and types */
    for (i = num_variables; --i >= 0; )
    {
        free_mstring(variables[i].name);
        free_fulltype_data(&variables[i].type);
    }

    /* Free all include names */
    for (i = num_includes; --i >= 0; )
    {
        free_mstring(includes[i].name);
        free_mstring(includes[i].filename);
    }

#ifdef USE_STRUCTS
    /* Free all struct names */
    for  (i = num_structs; --i >= 0; )
    {
        free_struct_type(struct_defs[i].type);
    }
#endif /* USE_STRUCTS */
}

/*-------------------------------------------------------------------------*/
#ifndef CHECK_OBJECT_REF
void
free_prog (program_t *progp, Bool free_all)
#else
void
_free_prog (program_t *progp, Bool free_all, const char * file, int line
           )
#endif

/* Decrement the refcount for program <progp>. If it reaches 0, the program
 * is freed.
 *
 * If free_all is TRUE, all object strings and the blueprint reference are
 * freed, and free_prog() is called for all inherited programs.
 *
 * The only case when free_all is not true, is, when the swapper
 * swapped out the program and now attempts to free the memory.
 * This means that the string data is kept in memory all the time.
 * TODO: Swapping the strings is tricky, as they are all shared.
 * TODO:: Maybe swap them together with the variables - this is costly
 * TODO:: enough to make the lookup time needed when swapping in the
 * TODO:: strings look small.
 */

{
    /* Decrement the refcount */

    progp->ref--;
    if (progp->ref > 0)
        return;

#if 0 && defined(CHECK_OBJECT_REF)
    if (strchr(get_txt(progp->name), '#') == NULL)
        printf("DEBUG: (%s:%d) free_prog(%p '%s') ref %ld\n"
              , file, line, progp, get_txt(progp->name), progp->ref);
#endif
    if (d_flag)
        printf("%s free_prog: %s\n", time_stamp(), get_txt(progp->name));
    if (progp->ref < 0)
        fatal("Negative ref count for prog ref.\n");

    if (free_all && progp->blueprint)
    {
        object_t * blueprint = progp->blueprint;
        progp->blueprint = NULL;
        remove_prog_swap(progp, MY_TRUE);
#if 0 && defined(CHECK_OBJECT_REF)
    if (strchr(get_txt(blueprint->name), '#') == NULL)
        printf("DEBUG: (%s:%d) free_prog(%p '%s') ref %ld : blueprint (%p '%s') ref %ld, flags %x\n"
              , file, line, progp, get_txt(progp->name), progp->ref
              , blueprint, get_txt(blueprint->name), blueprint->ref, blueprint->flags);
#elif defined(CHECK_OBJECT_REF)
#   ifdef __MWERKS__
#       pragma unused(file)
#       pragma unused(line)
#   endif
#endif
        free_object(blueprint, "free_prog");
    }

    /* Update the statistics */
    total_prog_block_size -= progp->total_size;
    total_num_prog_blocks -= 1;

    /* Free the line numbers.
     *
     * This has to be done before the program is removed from the
     * swapper, else the following test would fail.
     */
    if (progp->line_numbers)
    {
        total_prog_block_size -= progp->line_numbers->size;
        xfree(progp->line_numbers);
        progp->line_numbers = NULL;
    }

    /* Is it a 'real' free? Then dereference all the
     * things held by the program, too.
     */
    if (free_all)
    {
        int i;
        bytecode_p program;
        funflag_t *functions;

        /* Remove the swap entry */
        remove_prog_swap(progp, MY_FALSE);

        program = progp->program;
        functions = progp->functions;

        /* Free all function names. */
        for (i = progp->num_functions; --i >= 0; )
        {
            if ( !(functions[i] & NAME_INHERITED) )
            {
                string_t *name;
                memcpy(
                  &name,
                  FUNCTION_NAMEP(program + (functions[i] & FUNSTART_MASK)),
                  sizeof name
                );
                free_mstring(name);
            }
        }

        /* Free the strings, variable names and include filenames. */
        do_free_sub_strings( progp->num_strings, progp->strings
                           , progp->num_variables, progp->variables
                           , progp->num_includes, progp->includes
#ifdef USE_STRUCTS
                           , progp->num_structs, progp->struct_defs
#endif /* USE_STRUCTS */
                           );

        /* Free all inherited objects */
        for (i = 0; i < progp->num_inherited; i++)
            free_prog(progp->inherit[i].prog, MY_TRUE);

        /* Free the program name */
        total_prog_block_size -= mstrsize(progp->name);
        free_mstring(progp->name);
    }

    /* Remove the program structure */
    xfree(progp);
} /* free_prog() */

/*-------------------------------------------------------------------------*/
static string_t *
function_exists (string_t *fun, object_t *ob, Bool show_hidden
                , string_t ** prog_name, uint32 * prog_line
                )

/* Search for the function <fun> in the object <ob>. If existing, return
 * the name of the program (without added reference), if not return NULL.
 *
 * If <prog_name> and <prog_line> are both non-NULL, they are set to
 * the name of the program _file_ and the line where the function is found.
 * The program file name will have one reference added.
 *
 * Visibility rules apply: static and protected functions can't be
 * found from the outside unless <show_hidden> is true.
 */

{
    string_t *shared_name;
    fun_hdr_p funstart;
    program_t *progp;
    int ix;
    funflag_t flags;

#ifdef DEBUG
    if (ob->flags & O_DESTRUCTED)
        fatal("function_exists() on destructed object\n");
#endif

    if (prog_name)
        *prog_name = NULL;

    /* Make the program resident */
    if (O_PROG_SWAPPED(ob))
    {
        ob->time_of_ref = current_time;
        if (load_ob_from_swap(ob) < 0)
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
    }

    shared_name = find_tabled(fun);
    progp = ob->prog;

    /* Check if the function exists at all */
    if ( (ix = find_function(shared_name, progp)) < 0)
        return NULL;

    /* Is it visible for the caller? */
    flags = progp->functions[ix];

    if (!show_hidden
     && (   flags & TYPE_MOD_PRIVATE
         || (flags & TYPE_MOD_STATIC && current_object != ob))
       )
        return NULL;

    /* Resolve inheritance */
    while (flags & NAME_INHERITED)
    {
        inherit_t *inheritp;

        inheritp = &progp->inherit[flags & INHERIT_MASK];
        ix -= inheritp->function_index_offset;
        progp = inheritp->prog;
        flags = progp->functions[ix];
    }

    funstart = progp->program  + (flags & FUNSTART_MASK);

    /* And after all this, the function may be undefined */
    if (is_undef_function(funstart))
    {
        return NULL;
    }

    if(prog_line && prog_name)
      *prog_line = get_line_number(funstart, progp, prog_name);

    /* We got it. */
    return progp->name;
} /* function_exists() */

/*-------------------------------------------------------------------------*/
void
reset_object (object_t *ob, int arg)

/* Depending on <arg>, call one of the initialisation functions in <ob>.
 * The actual function is given in <arg> through its hook index.
 * Accepted values are: H_RESET, H_CREATE_SUPER, H_CREATE_OB,
 *   H_CREATE_CLONE.
 *
 * The value of the hooks can be function names (strings) or closures.
 *
 * For strings, the name is the function called in <ob>. It gets passed
 * one argument: 0 for H_CREATE_*, 1 for H_RESET. If on a H_RESET call
 * the function can not be found, the object will never be reset again.
 *
 * For closures, the code distinguishes closures which take no arguments
 * (only for H_CREATE_* calls) from those which take at least one argument.
 * In the former case, the closure is bound to <ob> and called; in the
 * latter case, the closure is bound to the current object and gets <ob>
 * passed as argument. If the closure returns a numeric result, it is
 * used as the time delay before the next reset.
 *
 * If the delay to the next (resp. first) reset is not determined by
 * the called function, it is set to a random value between time_to_reset/2
 * and time_to_reset. Upon time of call, the object must not be
 * in the reset table; this function will enter it there.
 */

{
    /* Be sure to update time first ! */
    if (time_to_reset > 0)
        ob->time_reset = current_time + time_to_reset/2
                         + (mp_int)random_number((uint32)time_to_reset/2);

    if (driver_hook[arg].type == T_CLOSURE)
    {
        lambda_t *l;

        if (arg == H_RESET)
            previous_ob = current_object = ob;

        l = driver_hook[arg].u.lambda;
        free_object(l->ob, "reset_object");
        if (l->function.code[1] && arg != H_RESET)
        {
            /* closure accepts arguments, presumably one, so
             * give it the target object and bind to the current
             * object.
             */
            l->ob = ref_object(current_object, "reset_object");
            push_ref_object(inter_sp, ob, "reset");
            call_lambda(&driver_hook[arg], 1);
        }
        else
        {
            /* no arguments, just bind to target */
            l->ob = ref_object(ob, "reset_object");
            call_lambda(&driver_hook[arg], 0);
        }

        /* If the call returned a non-zero number, use it as the current
         * reset interval, overwriting the default set above.
         */
        if (inter_sp->type == T_NUMBER && inter_sp->u.number)
            ob->time_reset = (inter_sp->u.number > 0)
                             ? current_time + inter_sp->u.number
                             : 0;

        pop_stack();
    }
    else if (driver_hook[arg].type == T_STRING)
    {
        if (arg == H_RESET)
            previous_ob = current_object = ob;

        push_number(inter_sp, arg == H_RESET);
        if (!sapply_ign_prot(driver_hook[arg].u.str, ob, 1)
         && arg == H_RESET)
            ob->time_reset = 0;
    }

    /* Object is reset now */
    ob->flags |= O_RESET_STATE;
} /* reset_object() */

/*-------------------------------------------------------------------------*/
void
replace_programs (void)

/* Called from the backend loop, this function
 * performs all pending program replacements listed in obj_list_replace.
 *
 * If the function runs out of memory, the processing ends at that point
 * and will be retried in the next call.
 *
 * Sideeffects of this action are: the objects are marked as 'replaced',
 * and current shadows are removed.
 */

{
    replace_ob_t *r_ob, *r_next;  /* List pointers */
    svalue_t *svp;
    int i, j;

#ifdef DEBUG
    if (d_flag)
        debug_message("%s start of replace_programs\n", time_stamp());
#endif

    for (r_ob = obj_list_replace; r_ob; r_ob = r_next)
    {
        program_t *old_prog;

        /* Swap in the program. This can't fail when called during
         * a garbage collection because then the malloc privilege
         * is MALLOC_SYSTEM.
         */
        if (r_ob->ob->flags & O_SWAPPED && load_ob_from_swap(r_ob->ob) < 0)
        {
            obj_list_replace = r_ob;
            return; /* Hope for more memory next time... */
        }

        /* If the number of variables changes, allocate a new variables
         * block and copy the old values over as far as possible.
         * Note that the change can only be a reduction, and that
         * the new program may not have variables at all. However, if
         * 'i' is not 0, the old program is guaranteed to have vars.
         */
        i = r_ob->ob->prog->num_variables - r_ob->new_prog->num_variables;
        if (i)
        {
            svalue_t *new_vars;

            /* Get the memory */

            if (r_ob->new_prog->num_variables)
            {
                new_vars = xalloc(  r_ob->new_prog->num_variables
                                  * sizeof *new_vars);

                if (!new_vars)
                {
                    obj_list_replace = r_ob;
                    return; /* Hope for more memory next time... */
                }
            }
            else
                new_vars = NULL;
#ifdef DEBUG
            if (d_flag)
                debug_message("%s %d less variables\n", time_stamp(), i);
            r_ob->ob->extra_num_variables = r_ob->new_prog->num_variables;
#endif

            /* Adjust the statistics */
#ifdef CHECK_OBJECT_STAT
            if (check_object_stat)
            {
                fprintf(stderr, "DEBUG: OSTAT: (%ld:%ld) rprog( %p '%s') sub %d vars : %ld -> (%ld:%ld)\n"
                              , tot_alloc_object, tot_alloc_object_size, r_ob, r_ob->ob->name ? get_txt(r_ob->ob->name) : "<null>"
                              , i
                              , (long)(i * sizeof(svalue_t))
                              , tot_alloc_object, tot_alloc_object_size - (i * sizeof(svalue_t))
                              );
            }
#endif
            tot_alloc_object_size -= i * sizeof(svalue_t);

            svp = r_ob->ob->variables; /* the old variables */

            /* Deref those variables of ob which won't be copied */

            j = r_ob->var_offset;      /* number of unique vars of ob */
            i -= j;

#ifdef DEBUG
            if (d_flag)
                debug_message("%s freeing %d variables:\n", time_stamp(), j);
#endif
            while (--j >= 0) 
            {
                free_svalue(svp++);
            }
#ifdef DEBUG
            if (d_flag)
                debug_message("%s freed.\n", time_stamp());
#endif

            /* Copy the others */
            j = r_ob->new_prog->num_variables;
            if (j)
            {
                memcpy(
                    (char *)new_vars,
                    (char *)svp,
                    j * sizeof(svalue_t)
                );
                svp += j;
            }
#ifdef DEBUG
            if (d_flag)
                debug_message("%s freeing %d variables:\n", time_stamp(), i);
#endif

            /* Deref the remaining non-copied variables */
            while (--i >= 0)
            {
                free_svalue(svp++);
            }
#ifdef DEBUG
            if (d_flag)
                debug_message("%s freed.\n", time_stamp());
#endif

            /* Free the old variable block and set the new one */
            xfree(r_ob->ob->variables);
            r_ob->ob->variables = new_vars;
        } /* if (change in vars) */

        /* Replace the old program with the new one */
        old_prog = r_ob->ob->prog;
        r_ob->new_prog->ref++;
        r_ob->ob->prog = r_ob->new_prog;
        r_ob->ob->flags |= O_REPLACED;

        r_next = r_ob->next;  /* remove it from the list */

        /* Handle a possible lambda adjustment */
        if (r_ob->lambda_rpp)
        {
            obj_list_replace = r_next;
            replace_program_lambda_adjust(r_ob);
        }

        /* Remove current shadows */

        if (r_ob->ob->flags & O_SHADOW)
        {
            shadow_t *shadow_sent;

            if ((shadow_sent = O_GET_SHADOW(r_ob->ob))->shadowing)
            {
                /* The master couldn't decide if it's a legal shadowing
                 * before the program was actually replaced. It is possible
                 * that the blueprint to the replacing program is already
                 * destructed, and it's source changed.
                 * On the other hand, if we called the master now, all kind
                 * of volatile data structures could result, even new entries
                 * for obj_list_replace. This would eventually require to
                 * reference it, and all the lrpp's , in check_a_lot_ref_counts()
                 * and garbage_collection() . Being able to use replace_program()
                 * in shadows is hardly worth this effort. Thus, we simply
                 * stop the shadowing.
                 */
                O_GET_SHADOW(shadow_sent->shadowing)->shadowed_by =
                  shadow_sent->shadowed_by;
                if (shadow_sent->shadowed_by)
                {
                    O_GET_SHADOW(shadow_sent->shadowed_by)->shadowing =
                      shadow_sent->shadowing;
                    shadow_sent->shadowed_by = NULL;
                }
                shadow_sent->shadowing = NULL;
            }
        }
        xfree(r_ob);

        /* Free the old program, finally */
        free_prog(old_prog, MY_TRUE);

#ifdef DEBUG
        if (d_flag)
            debug_message("%s program freed.\n", time_stamp());
#endif
    }

    /* Done with the list */
    obj_list_replace = NULL;

#ifdef DEBUG
    if (d_flag)
        debug_message("%s end of replace_programs\n", time_stamp());
#endif

}  /* replace_programs() */

/*-------------------------------------------------------------------------*/
static replace_ob_t *
retrieve_replace_program_entry (void)

/* Auxiliary function to efun replace_program(): test if a program
 * replacement is already scheduled for the current object. If yes,
 * return the pointer to the replace_ob struct, else return NULL.
 */

{
    replace_ob_t *r_ob;

    for (r_ob = obj_list_replace; r_ob; r_ob = r_ob->next)
    {
        if (r_ob->ob == current_object)
            return r_ob;
    }
    return NULL;
} /* retrieve_replace_program_entry() */

/*-------------------------------------------------------------------------*/
static program_t *
search_inherited (string_t *str, program_t *prg, int *offpnt)

/* Auxiliary function to efun replace_program(): check if program <str>
 * is inherited by <prg>. If yes, return the originating program and
 * store the (accumulated) variable and function offsets in offpnt[0]
 * and offpnt[1] resp.
 *
 * If the program is not found, return NULL.
 *
 * Nested inherits are handled in a depth search, the function recurses
 * for this.
 */

{
    program_t *tmp;
    int i;
#ifdef DEBUG
    char *ts;
#endif

#ifdef DEBUG
    ts = NULL;
    if (d_flag)
    {
        ts = time_stamp();
        debug_message("%s search_inherited started\n", ts);
        debug_message("%s searching for PRG(%s) in PRG(%s)\n"
                     , ts, get_txt(str), get_txt(prg->name));
        debug_message("%s num_inherited=%d\n", ts, prg->num_inherited);
    }
#endif

    /* Loop through all inherited programs, returning directly when
     * the name program was found.
     */
    for ( i = 0; i < prg->num_inherited; i++)
    {
#ifdef DEBUG
        if (d_flag)
        {
            debug_message("%s index %d:\n", ts, i);
            debug_message("%s checking PRG(%s)\n"
                         , ts, get_txt(prg->inherit[i].prog->name));
        }
#endif
        /* Duplicate virtual inherits don't count */
        if ( prg->inherit[i].inherit_type & INHERIT_TYPE_DUPLICATE )
            continue;

        if (mstreq(str, prg->inherit[i].prog->name ))
        {
#ifdef DEBUG
            if (d_flag)
                debug_message("%s match found\n", ts);
#endif
            offpnt[0] = prg->inherit[i].variable_index_offset;
            offpnt[1] = prg->inherit[i].function_index_offset;
            return prg->inherit[i].prog;
        }
        else if ( NULL != (tmp = search_inherited(str, prg->inherit[i].prog,offpnt)) )
        {
#ifdef DEBUG
            if (d_flag)
                debug_message("%s deferred match found\n", ts);
#endif
            offpnt[0] += prg->inherit[i].variable_index_offset;
            offpnt[1] += prg->inherit[i].function_index_offset;
            return tmp;
        }
    }

#ifdef DEBUG
    if (d_flag)
        debug_message("%s search_inherited failed\n", ts);
#endif

    return NULL;
} /* search_inherited() */

/*-------------------------------------------------------------------------*/
void
tell_npc (object_t *ob, string_t *str)

/* Call the lfun 'catch_tell()' in object <ob> with <str> as argument.
 *
 * This function is used to talk to non-interactive commandgivers
 * (aka NPCs).
 */

{
    push_ref_string(inter_sp, str);
    (void)sapply(STR_CATCH_TELL, ob, 1);
}

/*-------------------------------------------------------------------------*/
void
tell_npc_str (object_t *ob, const char *str)

/* Call the lfun 'catch_tell()' in object <ob> with <str> as argument.
 *
 * This function is used to talk to non-interactive commandgivers
 * (aka NPCs).
 */

{
    push_c_string(inter_sp, str);
    (void)sapply(STR_CATCH_TELL, ob, 1);
}

/*-------------------------------------------------------------------------*/
void
tell_object (object_t *ob, string_t *str)

/* Send message <str> to object <ob>. If <ob> is an interactive player,
 * it will go to his screen (unless a shadow catches it - see shadow_catch_
 * message() ). If <ob> is not interactive, the message will go
 * to the lfun 'catch_tell()' via a call to tell_npc().
 */

{
    object_t *save_command_giver;
    interactive_t *ip;

    if (ob->flags & O_DESTRUCTED)
        return;

    if (O_SET_INTERACTIVE(ip, ob))
    {
        save_command_giver = command_giver;
        command_giver = ob;
        add_message("%s", get_txt(str));
        command_giver = save_command_giver;
        return;
    }
    tell_npc(ob, str);
}

/*-------------------------------------------------------------------------*/
void
tell_object_str (object_t *ob, const char *str)

/* Send message <str> to object <ob>. If <ob> is an interactive player,
 * it will go to his screen (unless a shadow catches it - see shadow_catch_
 * message() ). If <ob> is not interactive, the message will go
 * to the lfun 'catch_tell()' via a call to tell_npc().
 */

{
    object_t *save_command_giver;
    interactive_t *ip;

    if (ob->flags & O_DESTRUCTED)
        return;

    if (O_SET_INTERACTIVE(ip, ob))
    {
        save_command_giver = command_giver;
        command_giver = ob;
        add_message("%s", str);
        command_giver = save_command_giver;
        return;
    }
    tell_npc_str(ob, str);
}

/*-------------------------------------------------------------------------*/
Bool
shadow_catch_message (object_t *ob, const char *str)

/* Called by comm:add_message() to handle the case that messages <str> sent
 * to interactive objects <ob> are to be delivered to shadows of the
 * OR to a function in the interactive itself.
 *
 * This function checks all shadows of <ob> if they contain the lfun
 * catch_tell(), and calls the lfun in the first shadow where it exists
 * with message <str> as argument.
 *
 * Result is true if there is such a function, and false if not. In
 * the latter case, the flag ob->ip.catch_tell_activ is cleared to
 * speed up later calls.
 *
 * The function returns immediately with false, if ob->ip.catch_tell_activ
 * is cleared, or if ob is the current_object.
 *
 * Beware that one of the shadows may be the originator of the message,
 * which means that we must not send the message to that shadow, or any
 * shadows in the linked list before that shadow.
 *
 * If the interactive user itself contains the lfun catch_tell(), the
 * messages counts as caught, too.
 */

{
    interactive_t *ip;

    ip = O_GET_INTERACTIVE(ob);

    if (!ip || !ip->catch_tell_activ || ob == current_object)
        return MY_FALSE;

    trace_level |= ip->trace_level;
    push_c_string(inter_sp, str);
    if (sapply(STR_CATCH_TELL, ob, 1))
        return MY_TRUE;

    /* The call failed, thus, current_object wasn't changed
     * (e.g. destructed and set to 0 ) .
     * !current_object is true when a prompt is given.
     */
    if (!current_object
     || !(current_object->flags & O_SHADOW)
     || !O_GET_SHADOW(current_object)->shadowing)
    {
        ip->catch_tell_activ = MY_FALSE;
    }
    return MY_FALSE;
} /* shadow_catch_message() */

/*-------------------------------------------------------------------------*/
static void
clear_program_id (program_t *p)

/* Clear the id_number of program <p> and all inherited programs.
 */

{
    int i;

    if (!p->id_number)
        return;

    p->id_number = 0;
    for (i = 0; i< p->num_inherited; i++)
    {
        clear_program_id(p->inherit[i].prog);
    }
}

/*-------------------------------------------------------------------------*/
static void
renumber_program (program_t *p)

/* Renumber program <p> and all inherited programs.
 * Assumes that all id_numbers have been cleared before.
 */

{
    int i;

    if (p->id_number)
        return;
    p->id_number = ++current_id_number;
    for (i=0; i< p->num_inherited; i++) {
        renumber_program(p->inherit[i].prog);
    }
}

/*-------------------------------------------------------------------------*/
int32
renumber_programs (void)

/* Renumber all programs in the game, recycling number from old
 * objects. Return the first free new id_number and modifies
 * the global current_id_number.
 *
 * The function is called by swap.c and lang.c when current_id_number
 * overflows.
 */

{
    object_t *ob;

    current_id_number = 0;
    for (ob = obj_list; ob; ob = ob->next_all)
    {
#ifdef DEBUG
        if (ob->flags & O_DESTRUCTED) /* TODO: Can't happen */
            continue;
#endif
        if ( !O_PROG_SWAPPED(ob) )
            clear_program_id(ob->prog);
    }

    for (ob = obj_list; ob; ob = ob->next_all)
    {
#ifdef DEBUG
        if (ob->flags & O_DESTRUCTED)  /* TODO: Can't happen */
            continue;
#endif
        if ( !O_PROG_SWAPPED(ob) )
            renumber_program(ob->prog);
    }
    invalidate_apply_low_cache();
    return ++current_id_number;
}

/*=========================================================================*/
/*                                EFUNS                                    */

/*-------------------------------------------------------------------------*/
svalue_t *
v_function_exists (svalue_t *sp, int num_arg)

/* EXEC function_exists()
 *
 *   mixed function_exists (string str [, int flags])
 *   mixed function_exists (string str , object ob, [, int flags])
 *
 * Look up a function <str> in the current object, respectively
 * in the object <ob>. Depending on the value of <flags>, one
 * of the following informations is returned:
 *
 * <flags> == FEXISTS_PROGNAME (0, default):
 *   Return the name of the program the function is defined in.
 *   This can be either object_name(ob), or the name of an inherited
 *   program. If !compat mode, the returned name always begins
 *   with a '/'.
 *
 * <flags> == FEXISTS_FILENAME (1):
 *   Return the name of the file the function is defined in (this
 *   may be an include file). If !compat mode, the returned name
 *   always begins with a '/'.
 *
 * <flags> == FEXISTS_LINENO (2):
 *   Return the line number within the source file.
 *
 * <flags> == FEXISTS_ALL (3):
 *   Return an array with all the above information. The above
 *   flag values are the indices into that array.
 *
 * The <flags> value can be or-ed to NAME_HIDDEN to return
 * information about static and protected functions in other objects.
 * It is not possible to return information about private functions.
 *
 * If the function cannot be found (because it doesn't exist or
 * it is not visible to the caller), the result is 0.
 */

{
    string_t *str, *prog_name;
    uint32 prog_line = 0;
    uint32 flags;
    svalue_t *argp;
    object_t *ob;

    /* Evaluate arguments */
    argp = sp - num_arg + 1;

    ob = NULL;
    flags = 0;

    if (num_arg < 2)
    {
        ob = current_object;
        flags = 0;
    }

    if (num_arg >= 2)
    {
        if (argp[1].type == T_NUMBER)
        {
            ob = current_object;
            flags = argp[1].u.number;

            if ((flags & ~NAME_HIDDEN) < 0
             || (flags & ~NAME_HIDDEN) > FEXISTS_ALL
               )
            {
                errorf("Bad argument 2 to function_exists(): value %ld (%ld sans NAME_HIDDEN) out of range %d..%d .\n"
                     , (long)flags, (long)(flags & ~NAME_HIDDEN)
                     , FEXISTS_ALL, FEXISTS_LINENO);
                /* NOTREACHED */
                return sp;
            }
        }
        else if (argp[1].type == T_OBJECT)
        {
            ob = argp[1].u.ob;
            flags = 0;
        }
    }

    if (num_arg >= 3)
    {
        /* The last argument must be a number. On the other
         * side, we can't have two numbers at once.
         */
        if (argp[1].type != T_OBJECT)
        {
            errorf("Bad argument 2 to function_exists(): got %s, expected object.\n", typename(argp[1].type));
            /* NOTREACHED */
            return sp;
        }

        flags = argp[2].u.number;

        if (((flags & ~NAME_HIDDEN) < 0)
         || ((flags & ~NAME_HIDDEN) > FEXISTS_ALL)
           )
        {
            errorf("Bad argument 3 to function_exists(): eff. value %ld (sans NAME_HIDDEN) out of range %d..%d .\n"
                 , (long)(flags & ~NAME_HIDDEN)
                 , FEXISTS_PROGNAME, FEXISTS_ALL);
            /* NOTREACHED */
            return sp;
        }
    }

    if (ob->flags & O_DESTRUCTED)
    {
        errorf("Bad argument to function_exists(): Object is destructed.\n");
        /* NOTREACHED */
        return sp;
    }

    /* Get the information */
    prog_name = NULL;
    str = function_exists(argp->u.str, ob, (flags & NAME_HIDDEN)
                         , &prog_name, &prog_line);
    sp = pop_n_elems(num_arg, sp);

    if (str)
    {
        switch (flags & ~NAME_HIDDEN)
        {
        case FEXISTS_ALL:
          {
            string_t *res;
            vector_t *vec;

            res = cvt_progname(str);
            if (!res)
            {
                errorf("Out of memory\n");
            }
            vec = allocate_uninit_array(FEXISTS_LINENO+1);
            put_string(vec->item+FEXISTS_PROGNAME, res);
            if (prog_name)
            {
                res = add_slash(prog_name);
                if (!res)
                {
                    errorf("Out of memory\n");
                }
                put_string(vec->item+FEXISTS_FILENAME, res);
            }
            else
                put_number(vec->item+FEXISTS_FILENAME, 0);
            put_number(vec->item+FEXISTS_LINENO, prog_line);

            push_array(sp, vec);
            break;
          }
        case FEXISTS_PROGNAME:
          {
            string_t *res;

            res = cvt_progname(str);
            if (!res)
            {
                errorf("Out of memory\n");
            }
            push_string(sp, res);
            break;
          }

        case FEXISTS_FILENAME:
            if (prog_name)
            {
                string_t *res;

                res = add_slash(prog_name);
                if (!res)
                {
                    errorf("Out of memory\n");
                }
                push_string(sp, res);
            }
            else
                push_number(sp, 0);
            break;

        case FEXISTS_LINENO:
            push_number(sp, prog_line);
            break;

        default:
            fatal("function_exists(): flags value %ld (from %ld) not implemented.\n"
                 , (long)(flags & ~NAME_HIDDEN), (long)flags);
            /* NOTREACHED */
        }
    }
    else
    {
        push_number(sp, 0);
    }

    /* Clean up */
    if (prog_name)
        free_mstring(prog_name);
    /* str had no ref on its own */

    return sp;
} /* v_function_exists() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_functionlist (svalue_t *sp)

/* EFUN functionlist()
 *
 *   mixed *functionlist (object ob, int flags = RETURN_FUNCTION_NAME)
 *
 * Return an array with information about <ob>s lfunctions. For every
 * function, 1 to 4 values (depending on <flags>) are stored in
 * the result array conveying in this order:
 *   - the name of the function
 *   - the function flags (see below)
 *   - the return type (listed in mudlib/sys/lpctypes.h)
 *   - the number of accepted argumens
 *
 * <ob> may be given as true object or as a filename. In the latter
 * case, the efun does not try to load the object before proceeding.
 *
 * <flags> determines both which information is returned for every
 * function, and which functions should be considered at all.
 * Its value is created by bin-or'ing together following flags from
 * mudlib/sys/functionlist.h:
 *
 *   Control of returned information:
 *     RETURN_FUNCTION_NAME    include the function name
 *     RETURN_FUNCTION_FLAGS   include the function flags
 *     RETURN_FUNCTION_TYPE    include the return type
 *     RETURN_FUNCTION_NUMARG  include the number of arguments.
 *
 *     The name RETURN_FUNCTION_ARGTYPE is defined but not implemented.
 *
 *   Control of listed functions:
 *     NAME_INHERITED      don't list if defined by inheritance
 *     TYPE_MOD_STATIC     don't list if static function
 *     TYPE_MOD_PRIVATE    don't list if private
 *     TYPE_MOD_PROTECTED  don't list if protected
 *     NAME_HIDDEN         don't list if not visible through inheritance
 *
 * The 'flags' information consists of the bin-or of the list control
 * flags given above, plus the following:
 *
 *     TYPE_MOD_VARARGS    function takes varargs
 *     NAME_UNDEFINED      function not defined yet, but referenced.
 *     NAME_CROSS_DEFINED  function is defined to be in a different program
 *     TYPE_MOD_NO_MASK    function is nomask
 *     TYPE_MOD_PUBLIC     function is public
 *
 * All these flags are defined in mudlib/sys/functionlist.h, which
 * should be copied into an accessible place in the mudlib. The
 * return types are defined in mudlib/sys/lpctypes.h which also
 * should be copied into the mudlib.
 *
 * TODO: All these defs are in mudlib/sys/functionlist.h and mudlib/sys/lpctypes.h
 * TODO:: as well as in exec.h and this file. This should be centralized.
 * TODO:: Maybe write the files on mud startup?
 * TODO:: Include mudlib/sys/functionlist.h doesn't help because then
 * TODO:: mkdepend stumbles over the embedded include <sys/lpctypes.h>.
 */

{
    object_t *ob;         /* <ob> argument to list */
    mp_int mode_flags;    /* <flags> argument */
    program_t *prog;      /* <ob>'s program */
    unsigned short num_functions;  /* Number of functions to list */
    char *vis_tags;
      /* Bitflag array describing the visibility of every function in prog
       * in relation to the passed <flags>: */
#define VISTAG_INVIS '\0'  /* Function should not be listed */
#define VISTAG_VIS   '\1'  /* Function matches the <flags> list criterium */
#define VISTAG_ALL   '\2'  /* Function should be listed, no list restrictions */
#define VISTAG_NAMED '\4'  /* Function is neither hidden nor private */

    vector_t *list;       /* Result vector */
    svalue_t *svp;        /* Last element in list which was filled in. */
    uint32 *fun;          /* Current function under examination */
    program_t *defprog;   /* Program which actually defines *fun */
    uint32 flags;
    unsigned short *ixp;
    long i, j;

#define FILTERFLAGS (NAME_HIDDEN|TYPE_MOD_PRIVATE|TYPE_MOD_STATIC|TYPE_MOD_PROTECTED|NAME_INHERITED)


    inter_sp = sp; /* In case of errors leave a clean stack */

    /* Extract the arguments from the vm stack.
     */
    if (sp[-1].type != T_OBJECT)
    {
        if (!(ob = find_object(sp[-1].u.str)))
            errorf("Object '%s' not found.\n", get_txt(sp[-1].u.str));
    }
    else
        ob = sp[-1].u.ob;

    mode_flags = sp->u.number;

    if (O_PROG_SWAPPED(ob))
        if (load_ob_from_swap(ob) < 0)
        {
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
            /* NOTREACHED */
            return NULL;
        }

    prog = ob->prog;

    /* Initialize the vistag[] flag array.
     */
    num_functions = prog->num_functions;
    vis_tags = alloca(num_functions);
    if (!vis_tags)
    {
        errorf("Stack overflow in functionlist()");
        /* NOTREACHED */
        return NULL;
    }

    /* Preset the visibility. By default, if there is any listing
     * modifier, the functions are not visible. If there is none, the functions
     * are visible.
     */
    memset( vis_tags, (mode_flags & FILTERFLAGS) ? VISTAG_INVIS : VISTAG_ALL
          , num_functions);

    /* Count how many named functions need to be listed in the result.
     * Flag every function to list in vistag[].
     */
    num_functions = 0;

    /* First, check all functions for which we have a name */
    flags = mode_flags & (FILTERFLAGS ^ NAME_HIDDEN);
    fun = prog->functions;
    j = prog->num_function_names;
    for (ixp = prog->function_names + j; --j >= 0; ) {
        i = *--ixp;
        if (!(fun[i] & flags) )
        {
            vis_tags[i] = VISTAG_NAMED|VISTAG_VIS;
            num_functions++;
        }
        else
        {
            vis_tags[i] |= VISTAG_NAMED;
        }
    }

    /* If the user wants to see the hidden or private functions, we loop
     * through the full function table and check all functions not yet
     * touched by the previous 'named' scan.
     * TODO: Due to the dedicated 'find hidden name' loop, this shouldn't
     * TODO:: be necessary, nor the VISTAG_ALL at all.
     */
    if ((mode_flags & (TYPE_MOD_PRIVATE|NAME_HIDDEN)) == 0)
    {
        fun = prog->functions;
        for (i = prog->num_functions; --i >= 0; )
        {
            if (!(vis_tags[i] & VISTAG_NAMED)
             && !(fun[i] & flags)
               )
            {
                vis_tags[i] = VISTAG_VIS;
                num_functions++;
            }
        }
    }

    /* If <flags> accepts all functions, use the total number of functions
     * instead of the count computed above.
     */
    if ( !(mode_flags & FILTERFLAGS))
    {
        num_functions = prog->num_functions;
    }

    /* Compute the size of the result vector to
     *  2**(number of RETURN_FUNCTION_ bits set)
     */
    for (i = mode_flags & RETURN_FUNCTION_MASK, j = 0; i; i >>= 1) {
        if (i & 1)
            j += num_functions;
    }

    /* Allocate the result vector and set svp to its end
     */
    list = allocate_array(j);
    svp = list->item + j;

    /* Loop backwards through all functions, check their flags if
     * they are to be listed and store the requested data in
     * the result vector.
     */

    for (i = prog->num_functions, fun = prog->functions + i; --i >= 0; )
    {
        fun_hdr_p funstart; /* Pointer to function in the executable */
        uint32 active_flags;  /* A functions definition status flags */

        fun--;

        if ((vis_tags[i] & (VISTAG_ALL|VISTAG_VIS)) == VISTAG_INVIS)
            continue; /* Don't list this one */

        flags = *fun;

        active_flags = (flags & ~INHERIT_MASK);
        if (!(vis_tags[i] & VISTAG_NAMED))
            active_flags |= NAME_HIDDEN;

        defprog = prog;

        /* If its a cross-defined function, get the flags from
         * real definition and let j point to it.
         */
        if ( !~(flags | ~(NAME_INHERITED|NAME_CROSS_DEFINED) ) ) {
            active_flags |= NAME_CROSS_DEFINED;
            j = (long)CROSSDEF_NAME_OFFSET(flags);
            flags = fun[j];
            j += i;
        } else {
            j = i;
        }

        /* If the function is inherited, find the original definition.
         */
        while (flags & NAME_INHERITED) {
            inherit_t *ip = &defprog->inherit[flags & INHERIT_MASK];

            defprog = ip->prog;
            j -= ip->function_index_offset;
            flags = defprog->functions[j];
        }

        /* defprog now points to the program which really defines
         * the function fun.
         */

        funstart = defprog->program + (flags & FUNSTART_MASK);

        /* Add the data to the result vector as <flags> determines.
         */

        if (mode_flags & RETURN_FUNCTION_NUMARG) {
            svp--;
            svp->u.number = FUNCTION_NUM_ARGS(funstart) & 0x7f;
        }

        if (mode_flags & RETURN_FUNCTION_TYPE) {
            vartype_t rtype;

            memcpy(&rtype, FUNCTION_TYPEP(funstart), sizeof(rtype));
            svp--;
            svp->u.number = rtype.type;
        }

        if (mode_flags & RETURN_FUNCTION_FLAGS) {

            /* If the function starts with the bytecodes F_UNDEF,
             * it referenced but undefined. But you know that.
             */
            if (is_undef_function(funstart))
            {
                active_flags |= NAME_UNDEFINED;
            }
            svp--;
            svp->u.number = (p_int)active_flags;
        }

        if (mode_flags & RETURN_FUNCTION_NAME) {
            svp--;
            svp->type = T_STRING;
            memcpy( &svp->u.str, FUNCTION_NAMEP(funstart)
                  , sizeof svp->u.str);
            (void)ref_mstring(svp->u.str);
        }
    } /* for() */

    /* Cleanup and return */
    free_svalue(sp);
    sp--;
    free_svalue(sp);

    put_array(sp, list);
    return sp;

#undef VISTAG_INVIS
#undef VISTAG_VIS
#undef VISTAG_ALL
#undef VISTAG_NAMED

#undef FILTERFLAGS
} /* f_functionlist() */

/*-------------------------------------------------------------------------*/
svalue_t *
v_variable_exists (svalue_t *sp, int num_arg)

/* EXEC variable_exists()
 *
 *   string variable_exists (string str [, int flags])
 *   string variable_exists (string str , object ob, [, int flags])
 *
 * Look up a variable <str> in the current object, respectively
 * in the object <ob>.
 *
 * The result is the name of the program the variable is defined in. This can
 * be either object_name(ob), or the name of an inherited program. If !compat
 * mode, the returned name always begins with a '/'.
 *
 * If <flags> can be passed as NAME_HIDDEN to return information about static
 * and protected variables in other objects. It is not possible to return
 * information about private variables.
 *
 * If the variable cannot be found (because it doesn't exist or
 * it is not visible to the caller), the result is 0.
 */

{
    string_t *str;
    svalue_t *argp;
    object_t *ob;
    p_int mode_flags;

    /* Evaluate arguments */
    argp = sp - num_arg + 1;

    ob = NULL;
    mode_flags = 0;

    if (num_arg < 2)
    {
        ob = current_object;
        mode_flags = 0;
    }

    if (num_arg >= 2)
    {
        if (argp[1].type == T_NUMBER)
        {
            ob = current_object;
            mode_flags = argp[1].u.number;

            if (mode_flags != 0 && mode_flags != NAME_HIDDEN)
            {
                errorf("Bad argument 2 to variable_exists(): "
                      "value %ld, expected 0 or %d (NAME_HIDDEN).\n"
                     , (long)mode_flags, NAME_HIDDEN
                    );
                /* NOTREACHED */
                return sp;
            }
        }
        else if (argp[1].type == T_OBJECT)
        {
            ob = argp[1].u.ob;
            mode_flags = 0;
        }
    }

    if (num_arg >= 3)
    {
        /* The last argument must be a number. On the other
         * side, we can't have two numbers at once.
         */
        if (argp[1].type != T_OBJECT)
        {
            errorf("Bad argument 2 to variable_exists(): "
                  "got %s, expected object.\n", typename(argp[1].type));
            /* NOTREACHED */
            return sp;
        }

        mode_flags = argp[2].u.number;

        if (mode_flags != 0 && mode_flags != NAME_HIDDEN)
        {
            errorf("Bad argument 3 to variable_exists(): "
                  "value %ld, expected 0 or %d (NAME_HIDDEN).\n"
                 , (long)mode_flags, NAME_HIDDEN
                );
            /* NOTREACHED */
            return sp;
        }
    }


    if (ob->flags & O_DESTRUCTED)
    {
        errorf("Bad argument to variable_exists(): Object is destructed.\n");
        /* NOTREACHED */
        return sp;
    }
 
    /* Make the program resident */
    if (O_PROG_SWAPPED(ob))
    {
        ob->time_of_ref = current_time;
        if (load_ob_from_swap(ob) < 0)
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
    }

    /* Get the information */
    str = NULL;

    do
    {
        string_t *shared_name;
        program_t *progp;
        int ix;
        typeflags_t flags;

        shared_name = find_tabled(argp->u.str);
        if (!shared_name)
            break;

        progp = ob->prog;

        /* Check if the function exists at all */
        for (ix = 0; ix < progp->num_variables; ix++)
        {
            if (mstreq(shared_name, progp->variables[ix].name))
                break;
        }

        if (ix >= progp->num_variables)
            break;

        /* Is it visible for the caller? */
        flags = progp->variables[ix].type.typeflags;

        if (!(mode_flags & NAME_HIDDEN)
         && (   (flags & TYPE_MOD_PRIVATE)
             || ((flags & TYPE_MOD_PROTECTED) && current_object != ob))
           )
            break;

        /* Resolve inheritance */
        while (flags & NAME_INHERITED)
        {
            int ic;

            for (ic = 0; ic < progp->num_inherited; ic++)
            {
                inherit_t *ip = &progp->inherit[ic];

                if (ix >= ip->variable_index_offset + ip->prog->num_variables
                 || ix < ip->variable_index_offset
                   )
                    continue;
                ix -= ip->variable_index_offset;
                progp = ip->prog;
                flags = progp->variables[ix].type.typeflags;
            }
        }

        /* progp now points to the program which really defines
         * the variable var.
         */

        /* We got it. */
        str = progp->name;
    } while(0);

    /* Put the result onto the stack */
    sp = pop_n_elems(num_arg, sp);

    if (str)
    {
        string_t *res;

        res = cvt_progname(str);
        push_string(sp, res);
    }
    else
    {
        push_number(sp, 0);
    }

    /* str had no ref on its own */

    return sp;
} /* v_variable_exists() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_variable_list (svalue_t *sp)

/* EFUN variable_list()
 *
 *   mixed *variable_list (object ob, int flags = RETURN_FUNCTION_NAME)
 *
 * Return an array with information about <ob>s variables. For every
 * variable, 1 to 4 values (depending on <flags>) are stored in
 * the result array conveying in this order:
 *   - the name of the variable
 *   - the variable flags (see below)
 *   - the return type (listed in mudlib/sys/lpctypes.h)
 *   - the value of the variable
 *
 * <ob> may be given as true object or as a filename. In the latter
 * case, the efun does not try to load the object before proceeding.
 *
 * If <ob> is not the current object and the value of the variable is
 * requested, a privilege_violation ("variable_list", <ob>) occurs.
 *
 * <flags> determines both which information is returned for every
 * variable, and which variables should be considered at all.
 * Its value is created by bin-or'ing together following flags from
 * mudlib/sys/functionlist.h:
 *
 *   Control of returned information:
 *     RETURN_FUNCTION_NAME    include the variable name
 *     RETURN_FUNCTION_FLAGS   include the variable flags
 *     RETURN_FUNCTION_TYPE    include the return type
 *     RETURN_VARIABLE_VALUE   include the variable value
 *
 *   Control of listed variables:
 *     NAME_INHERITED      don't list if defined by inheritance
 *     TYPE_MOD_NOSAVE ==
 *     TYPE_MOD_STATIC     don't list if nosave ('static') variable
 *     TYPE_MOD_PRIVATE    don't list if private
 *     TYPE_MOD_PROTECTED  don't list if protected
 *     NAME_HIDDEN         don't list if not visible through inheritance
 *
 * The 'flags' information consists of the bin-or of the list control
 * flags given above, plus the following:
 *
 *     TYPE_MOD_VIRTUAL    variable is inherited virtually
 *     TYPE_MOD_NO_MASK    variable is nomask
 *     TYPE_MOD_PUBLIC     variable is public
 *
 * All these flags are defined in mudlib/sys/functionlist.h, which
 * should be copied into an accessible place in the mudlib. The
 * return types are defined in mudlib/sys/lpctypes.h which also
 * should be copied into the mudlib.
 *
 * TODO: All these defs are in mudlib/sys/functionlist.h and mudlib/sys/lpctypes.h
 * TODO:: as well as in exec.h and this file. This should be centralized.
 * TODO:: Maybe write the files on mud startup?
 * TODO:: Include mudlib/sys/functionlist.h doesn't help because then
 * TODO:: mkdepend stumbles over the embedded include <sys/lpctypes.h>.
 */

{
    object_t *ob;         /* <ob> argument to list */
    mp_int mode_flags;    /* <flags> argument */
    program_t *prog;      /* <ob>'s program */
    unsigned short num_variables;  /* Number of variables to list */
    char *vis_tags;
      /* Bitflag array describing the visibility of every variable in prog
       * in relation to the passed <flags>: */
#define VISTAG_INVIS '\0'  /* Variable should not be listed */
#define VISTAG_VIS   '\1'  /* Variable matches the <flags> list criterium */
#define VISTAG_ALL   '\2'  /* Variable should be listed, no list restrictions */
#define VISTAG_NAMED '\4'  /* Variable is neither hidden nor private */

#define FILTERFLAGS (NAME_HIDDEN|TYPE_MOD_PRIVATE|TYPE_MOD_STATIC|TYPE_MOD_PROTECTED|NAME_INHERITED)

    vector_t *list;       /* Result vector */
    svalue_t *svp;        /* Last element in list which was filled in. */
    variable_t *var;      /* Current variable under examination */
    uint32 flags;
    long i, j;

    inter_sp = sp; /* In case of errors leave a clean stack */

    /* Extract the arguments from the vm stack.
     */
    if (sp[-1].type != T_OBJECT)
    {
        if (!(ob = find_object(sp[-1].u.str)))
            errorf("Object '%s' not found.\n", get_txt(sp[-1].u.str));
    }
    else
        ob = sp[-1].u.ob;

    mode_flags = sp->u.number;

    if (ob != current_object && (mode_flags & RETURN_VARIABLE_VALUE))
    {
        assert_master_ob_loaded();
        if (privilege_violation(STR_VARIABLE_LIST, sp-1, sp) <= 0)
        {
            free_svalue(sp);
            sp--;
            free_svalue(sp);
            sp->type = T_NUMBER;
            sp->u.number = 0;
            return sp;
        }
    }

    if (O_PROG_SWAPPED(ob))
        if (load_ob_from_swap(ob) < 0)
        {
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
            /* NOTREACHED */
            return NULL;
        }

    prog = ob->prog;

    /* Initialize the vistag[] flag array.
     */
    num_variables = prog->num_variables;
    vis_tags = alloca(num_variables);
    if (!vis_tags)
    {
        errorf("Stack overflow in variable_list()");
        /* NOTREACHED */
        return NULL;
    }

    /* Preset the visibility. By default, if there is any listing
     * modifier, the variables are not visible. If there is none, the
     * variables are visible.
     */
    memset( vis_tags, (mode_flags & FILTERFLAGS) ? VISTAG_INVIS : VISTAG_ALL
          , num_variables);

    /* Count how many named variables need to be listed in the result.
     * Flag every variable to list in vistag[].
     */
    num_variables = 0;

    /* First, check all variables for which we have a name */
    flags = mode_flags & (FILTERFLAGS ^ NAME_HIDDEN);
    var = prog->variables;
    i = prog->num_variables;
    while ( --i >= 0 ) {
        if (!(var[i].type.typeflags & flags) )
        {
            vis_tags[i] = VISTAG_NAMED|VISTAG_VIS;
            num_variables++;
        }
        else
        {
            vis_tags[i] |= VISTAG_NAMED;
        }
    }

    /* If the user wants to see the hidden or private variables, we loop
     * through the full variable table and check all variables not yet
     * touched by the previous 'named' scan.
     * TODO: Due to the dedicated 'find hidden name' loop, this shouldn't
     * TODO:: be necessary, nor the VISTAG_ALL at all.
     */
    if ((mode_flags & (TYPE_MOD_PRIVATE|NAME_HIDDEN)) == 0)
    {
        var = prog->variables;
        for (i = prog->num_variables; --i >= 0; )
        {
            if (!(vis_tags[i] & VISTAG_NAMED)
             && !(var[i].type.typeflags & flags)
               )
            {
                vis_tags[i] = VISTAG_VIS;
                num_variables++;
            }
        }
    }

    /* If <flags> accepts all variables, use the total number of variables
     * instead of the count computed above.
     */
    if ( !(mode_flags & FILTERFLAGS))
    {
        num_variables = prog->num_variables;
    }

    /* Compute the size of the result vector to
     *  2**(number of RETURN_FUNCTION_ bits set)
     */
    for (i = mode_flags & RETURN_VARIABLE_MASK, j = 0; i; i >>= 1) {
        if (i & 1)
            j += num_variables;
    }

    /* Allocate the result vector and set svp to its end
     */
    list = allocate_array(j);
    svp = list->item + j;

    /* Loop backwards through all variables, check their flags if
     * they are to be listed and store the requested data in
     * the result vector.
     */

    for (i = prog->num_variables, var = prog->variables + i; --i >= 0; )
    {
        uint32 active_flags;  /* A variable's definition status flags */
        var--;

        if ((vis_tags[i] & (VISTAG_ALL|VISTAG_VIS)) == VISTAG_INVIS)
            continue; /* Don't list this one */

        flags = var->type.typeflags;

        active_flags = (flags & ~INHERIT_MASK);
        if (!(vis_tags[i] & VISTAG_NAMED))
            active_flags |= NAME_HIDDEN;

        /* Add the data to the result vector as <flags> determines.
         */

        if (mode_flags & RETURN_VARIABLE_VALUE)
        {
            svp--;
            assign_svalue_no_free(svp, &ob->variables[i]);
        }

        if (mode_flags & RETURN_FUNCTION_TYPE)
        {
            svp--;
            svp->u.number = var->type.typeflags & TYPE_MOD_MASK;
        }

        if (mode_flags & RETURN_FUNCTION_FLAGS)
        {
            svp--;
            svp->u.number = (p_int)active_flags;
        }

        if (mode_flags & RETURN_FUNCTION_NAME) {
            svp--;
            put_ref_string(svp, var->name);
        }
    } /* for() */

    /* Cleanup and return */
    free_svalue(sp);
    sp--;
    free_svalue(sp);

    put_array(sp, list);
    return sp;

#undef VISTAG_INVIS
#undef VISTAG_VIS
#undef VISTAG_ALL
#undef VISTAG_NAMED

#undef FILTERFLAGS
} /* f_variable_list() */

/*-------------------------------------------------------------------------*/
svalue_t *
v_include_list (svalue_t *sp, int num_arg)

/* EFUN include_list()
 *
 *   string* include_list ()
 *   string* include_list (object ob)
 *   string* include_list (object ob, int flags)
 *
 * Return a list with the names of all files included by the program
 * of object <ob>, including <ob>'s program file itself.
 */

{
    object_t  *ob;          /* Analyzed object */
    vector_t  *vec;         /* Result vector */
    int        count;       /* Total number of includes */
    svalue_t  *argp;        /* Arguments */
    include_t *includes;    /* Pointer to the include information */
    p_int     flags;

    /* Get the arguments */
    argp = sp - num_arg + 1;

    if (num_arg >= 1)
        ob = argp[0].u.ob;
    else
        ob = current_object;

    if (num_arg >= 2)
        flags = argp[1].u.number;
    else
        flags = 0;

    if (O_PROG_SWAPPED(ob))
        if (load_ob_from_swap(ob) < 0)
        {
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
            /* NOTREACHED */
            return NULL;
        }

    /* Create the result.
     * Depending on the flags value, this can be a flat list or a tree.
     */

    if (!(flags & INCLIST_TREE))
    {
        svalue_t *svp;

        /* Get the result array */
        vec = allocate_array((ob->prog->num_includes+1) * 3);
        svp = vec->item;

        /* Walk the includes information and copy it into the result vector
         */
        for (  svp = vec->item+3
             , count = ob->prog->num_includes
             , includes = ob->prog->includes
            ; count > 0
            ; count--, includes++, svp += 3
            )
        {
            int depth;

            put_ref_string(svp, includes->name);
            put_ref_string(svp+1, includes->filename);
            depth = includes->depth;
            if (depth > 0)
                put_number(svp+2, depth);
            else
                put_number(svp+2, -depth);
        }
    }
    else  /* Tree-type result */
    {
        /* Local structure to hold the found programs */
        struct iinfo {
            struct iinfo * next;     /* Next structure in flat list */
            int            depth;    /* Include depth */
            include_t    * inc;      /* The include information */
              /* The following members are used to recreate the inherit tree */
            int            count;    /* Number of direct includes */
            struct iinfo * parent;   /* Parent include, or NULL */
            struct iinfo * child;    /* First child include */
            struct iinfo * sibling;  /* Next include on same level */
              /* These members are used to create the result tree */
            size_t         index;    /* # of this include file in the parent
                                      * vector */
            vector_t     * vec;      /* Result vector for this include */
        } *begin, *end;         /* Flat list of all found includes */

        struct iinfo * last;    /* Last include found on this depth */
        struct iinfo * next;    /* Next include to work */
        Mempool   pool;         /* The memory pool to allocate from */

        /* Get the memory pool */
        memsafe(pool = new_mempool(size_mempool(sizeof(*begin)))
               , size_mempool(sizeof(*begin)), "memory pool");

        /* Walk the list of included files and build the tree from it.
         */

        begin = mempool_alloc(pool, sizeof(*begin));
        if (NULL == begin)
        {
            mempool_delete(pool);
            outofmem(sizeof(*begin), "allocation from mempool");
        }

        /* Root node for the object's program itself */
        begin->next = NULL;
        begin->child = NULL;
        begin->sibling = NULL;
        begin->inc = NULL;
        begin->depth = 0;
        begin->count = 0;
        begin->parent = NULL;
        begin->vec = NULL;
        begin->index = 0;

        end = begin;
        last = begin;

        includes = ob->prog->includes;
        count = ob->prog->num_includes;

        for ( ; count > 0; count--, includes++)
        {
            /* Get new node and put it into the flat list */
            end->next = mempool_alloc(pool, sizeof(*end));
            if (NULL == end->next)
            {
                mempool_delete(pool);
                outofmem(sizeof(*end), "allocation from mempool");
            }
            end = end->next;
            end->next = NULL;
            end->inc = includes;
            end->depth = includes->depth > 0 ? includes->depth : - includes->depth;

            /* Handle the tree-based information */
            end->child = NULL;
            end->sibling = NULL;

            if (last->depth > end->depth)
            {
                /* We reached a leaf with <last> - this new was included from
                 * some parent above.
                 */
                while (last->depth > end->depth)
                    last = last->parent;

                /* Got back up to the right sibling level, no go to the end
                 * of the sibling list (just in case - we should already
                 * be there).
                 */
                while (last->sibling)
                    last = last->sibling;
            }
            /* Now the new file is either a sibling or a child of <last> */

            if (last->depth == end->depth)
            {
                /* Sibling to <last> */
                last->sibling = end;
                end->parent = last->parent;
                last = end;
                end->parent->count++;
            }
            else /* last->depth < end->depth */
            {
                /* Included from <last> */
                last->child = end;
                last->count++;
                end->parent = last;
                last = end;
            }

            /* Init the rest */
            end->count = 0;
            end->index = end->parent->count;
            end->vec = NULL;
        }

        /* Get the top result array and keep a reference to it on the
         * stack so that it will be deallocated on an error.
         */
        vec = allocate_array((begin->count+1) * 3);
        begin->vec = vec;
        push_array(sp, vec); inter_sp = sp;

        /* Loop through all the include infos and copy them into
         * their result vector. We create the subvectors when
         * we encounter them.
         * Invariant: <next> points to the next iinfo to work.
         */
        for (next = begin->child; next != NULL; )
        {
            /* If this child has no includes, we just copy the
             * name into its proper place in the parent vector.
             *
             * Otherwise we create a vector for this include
             * and store the names in there.
             */
            if (next->child == NULL)
            {
                svalue_t *svp;

                svp = &next->parent->vec->item[next->index*3];
                put_ref_string(svp, next->inc->name);
                put_ref_string(svp+1, next->inc->filename);
                put_number(svp+2, next->depth);

                /* If we are in the last sibling, roll back up to
                 * the parents.
                 */
                while (next->sibling == NULL && next->parent != NULL)
                    next = next->parent;

                /* Advance to the next sibling. If by  */
                next = next->sibling;
            }
            else
            {
                svalue_t *svp;

                next->vec = allocate_array((next->count+1)*3);

                svp = &next->parent->vec->item[next->index*3];
                put_array(svp, next->vec);
                  /* svp[1] and svp[2] are already 0 */

                svp = next->vec->item;
                put_ref_string(svp, next->inc->name);
                put_ref_string(svp+1, next->inc->filename);
                put_number(svp+2, next->depth);

                /* Descend into the first child */
                next = next->child;
            }
        }

        mempool_delete(pool);
        sp--; /* Remove the temporary storage of vec on the stack */
    }

    /* Copy the information about the program file itself. */

    {
        string_t *str;
        size_t slen;  /* Also used for error reporting */

        slen = mstrsize(ob->prog->name);

        if (compat_mode)
            str = ref_mstring(ob->prog->name);
        else
            str = add_slash(ob->prog->name);

        if (!str)
        {
            free_array(vec);
            errorf("(include_list) Out of memory: (%lu bytes) for filename\n"
                 , (unsigned long)slen);
        }

        put_string(vec->item, str);
        /* vec->item[1] and vec->item[2] are already 0 */
    }

    /* Done */

    sp = pop_n_elems(num_arg, sp);

    sp++;
    put_array(sp, vec);
    return sp;
} /* v_include_list() */

/*-------------------------------------------------------------------------*/
svalue_t *
v_inherit_list (svalue_t *sp, int num_arg)

/* EFUN inherit_list()
 *
 *   string* inherit_list ()
 *   string* inherit_list (object ob)
 *   string* inherit_list (object ob, int flags)
 *
 * Return a list with the filenames of all programs inherited by <ob>, include
 * <ob>'s program itself.
 */

{
    /* Local structure to hold the found programs */
    struct iinfo {
        struct iinfo * next;     /* Next structure in flat list */
        SBool          virtual;  /* TRUE: Virtual inherit */
        program_t    * prog;     /* Program found */
          /* The following members are used to recreate the inherit tree */
        int            count;    /* Number of direct inherits */
        struct iinfo * parent;   /* Parent program, or NULL */
          /* These members are used to create the result tree */
        size_t         index;    /* # of this inherited program */
        vector_t     * vec;      /* Result vector for this program */
    } *begin, *end;         /* Flat list of all found inherits */
    struct iinfo * next;    /* Next program to analyze */

    Mempool   pool;         /* The memory pool to allocate from */
    object_t *ob;           /* Analyzed object */
    vector_t *vec;          /* Result vector */
    svalue_t *svp;          /* Pointer to next vec entry to fill in */
    int       count;        /* Total number of inherits found */
    svalue_t *argp;         /* Arguments */
    p_int     flags;

    /* Get the arguments */
    argp = sp - num_arg + 1;

    if (num_arg >= 1)
        ob = argp[0].u.ob;
    else
        ob = current_object;

    if (num_arg >= 2)
        flags = argp[1].u.number;
    else
        flags = 0;

    if (O_PROG_SWAPPED(ob))
        if (load_ob_from_swap(ob) < 0) {
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
            /* NOTREACHED */
            return NULL;
        }

    /* Get the memory pool */
    memsafe(pool = new_mempool(size_mempool(sizeof(*begin)))
           , size_mempool(sizeof(*begin)), "memory pool");

    /* Perform a breadth search on ob's inherit tree and append the
     * found programs to the iinfo list while counting them.
     */

    begin = mempool_alloc(pool, sizeof(*begin));
    if (NULL == begin)
    {
        mempool_delete(pool);
        outofmem(sizeof(*begin), "allocation from mempool");
    }

    /* Root node for the object's program itself */
    begin->next = NULL;
    begin->prog = ob->prog;
    begin->virtual = MY_FALSE;
    begin->count = 0;
    begin->parent = NULL;
    begin->vec = NULL;
    begin->index = 0;

    end = begin;

    count = 1;

    for (next = begin; next != NULL; next = next->next)
    {
        int cnt;
        inherit_t *inheritp;

        cnt = next->prog->num_inherited;

        /* Store the inherited programs in the list.
         */
        for (inheritp = &next->prog->inherit[0]; cnt--; inheritp++)
        {
            if (inheritp->inherit_type == INHERIT_TYPE_NORMAL
             || inheritp->inherit_type == INHERIT_TYPE_VIRTUAL
               )
            {
                count++;
                next->count++;

                end->next = mempool_alloc(pool, sizeof(*end));
                if (NULL == end->next)
                {
                    mempool_delete(pool);
                    outofmem(sizeof(*end), "allocation from mempool");
                }
                end = end->next;
                end->next = NULL;
                end->prog = inheritp->prog;
                end->virtual = (inheritp->inherit_type == INHERIT_TYPE_VIRTUAL);

                /* Handle the tree-based information */
                end->parent = next;
                end->count = 0;
                end->index = next->count;
                end->vec = NULL;
            }
        }
    }

    /* Create the result.
     * Depending on the flags value, this can be a flat list or a tree.
     */

    if (!(flags & INHLIST_TREE))
    {
        /* Get the result array */
        vec = allocate_array(count);

        /* Take the filenames of the programs and copy them into
         * the result vector.
         */
        for (svp = vec->item, next = begin; next != NULL; svp++, next = next->next)
        {
            string_t *str;
            size_t slen;  /* Also used for error reporting */

            slen = mstrsize(next->prog->name);

            if (compat_mode)
                str = ref_mstring(next->prog->name);
            else
                str = add_slash(next->prog->name);

            if (str && (flags & INHLIST_TAG_VIRTUAL))
            {
                string_t * str2;

                slen = mstrsize(str) + 2;

                if (next->virtual)
                    str2 = mstr_add_to_txt("v ", 2, str);
                else
                    str2 = mstr_add_to_txt("  ", 2, str);

                free_mstring(str);
                str = str2;
            }

            if (!str)
            {
                free_array(vec);
                mempool_delete(pool);
                errorf("(inherit_list) Out of memory: (%lu bytes) for filename\n"
                     , (unsigned long)slen);
            }
            put_string(svp, str);
        }
    }
    else
    {
        /* Get the top result array and keep a reference to it on the
         * stack so that it will be deallocated on an error.
         */
        vec = allocate_array(begin->count+1);
        begin->vec = vec;
        push_array(sp, vec); inter_sp = sp;

        /* Loop through all filenames and copy them into their result
         * vector. Since the list in breadth-order, we can create the
         * sub-vectors when we encounter them.
         */
        for (next = begin; next != NULL; next = next->next)
        {
            string_t *str;
            size_t slen;  /* Also used for error reporting */

            slen = mstrsize(next->prog->name);

            if (compat_mode)
                str = ref_mstring(next->prog->name);
            else
                str = add_slash(next->prog->name);

            if (str && (flags & INHLIST_TAG_VIRTUAL))
            {
                string_t * str2;

                slen = mstrsize(str) + 2;

                if (next->virtual)
                    str2 = mstr_add_to_txt("v ", 2, str);
                else
                    str2 = mstr_add_to_txt("  ", 2, str);

                free_mstring(str);
                str = str2;
            }

            if (!str)
            {
                mempool_delete(pool);
                errorf("(inherit_list) Out of memory: (%lu bytes) for filename\n"
                     , (unsigned long)slen);
            }

            /* If this child has no inherits, we just copy the
             * name into its proper place in the parent vector.
             * Same for the name of the top program.
             *
             * Otherwise we create a vector for this program
             * and store the name in there.
             */
            if (begin == next)
            {
                put_string(next->vec->item, str);
            }
            else if (next->count == 0)
            {
                put_string(&next->parent->vec->item[next->index], str);
            }
            else
            {
                next->vec = allocate_array(next->count+1);
                put_array(&next->parent->vec->item[next->index], next->vec);
                put_string(next->vec->item, str);
            }
        }

        sp--; /* Remove the temporary storage of vec on the stack */
    }

    mempool_delete(pool);

    sp = pop_n_elems(num_arg, sp);

    push_array(sp, vec);
    return sp;
} /* v_inherit_list() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_load_name (svalue_t *sp)

/* EFUN load_name()
 *
 *   string load_name()
 *   string load_name(object obj)
 *   string load_name(string obj)
 *
 * Return the load name for the object <obj> which may be given
 * directly or by its name.
 *
 * If <obj> is a clone, return the load_name() of <obj>'s blueprint.
 * If <obj> is a blueprint, return the filename from which the
 * blueprint was compiled.
 *
 * If <obj> is given by name but not/no longer existing, the
 * function synthesizes the load name as it should be and returns
 * that. If the given name is illegal, the function returns 0.
 *
 * For virtual objects this efun of course returns the virtual
 * filename.  If <obj> is omitted, the name for the current object is
 * returned.
 *
 * As a special case, if <obj> is 0, the function returns 0.
 *
 * In contrast to the object_name(), the load name can not be changed
 * by with rename_object(). However, if an object uses
 * replace_program() the load name no longer reflects the actual
 * behaviour of an object.
 *
 * The returned name starts with a '/', unless the driver is running
 * in COMPAT mode.
 */

{
    string_t *s;   /* String argument */
    char *name;    /* Result string, maybe 's' itself */
    char *hash;    /* Position of the hash in the name */
    char *mem;     /* Allocated memory blocks */
    object_t *ob;

    /* If the argument is 0, just return 0. */
    if (sp->type == T_NUMBER)
    {
        return sp;
    }

    /* If the argument is an object, we just need to read the name */
    if (sp->type == T_OBJECT)
    {
        s = sp->u.ob->load_name;
        free_object_svalue(sp);
        put_ref_string(sp, s);
        return sp;
    }

    /* Argument is a string: try to find the object for it */
    s = sp->u.str;
    ob = find_object(s);
    if (ob)
    {
        /* Got it */
        s = ob->load_name;
        free_string_svalue(sp);
        put_ref_string(sp, s);
        return sp;
    }

    /* There is no object for the string argument: just normalize
     * the string. First check if it ends in #<number>.
     */
    mem = NULL;
    hash = strchr(get_txt(s), '#');
    if (!hash)
    {
        /* No '#' at all: make the name sane directly */
        name = (char *)make_name_sane(get_txt(s), !compat_mode);
        if (!name)
            name = get_txt(s);
    }
    else
    {
        char *p;
        size_t len;

        /* All characters after the '#' must be digits */
        for (p = hash+1; '\0' != *p; p++)
            if (*p < '0' || *p > '9')
                /* Illegal name: break to return svalue 0 */
                break;

        if ('\0' != *p)
        {
            /* Illegal name: break to return svalue 0 */
            free_string_svalue(sp);
            put_number(sp, 0);
            return sp;
        }

        /* Good, we can slash off the '#<number>' */
        len = (size_t)(hash - get_txt(s));
        p = mem = xalloc(len+1);
        if (!p)
            errorf("(load_name) Out of memory (%lu bytes) for filename."
                 , (long)len+1);
        strncpy(p, get_txt(s), len);
        p[len] = '\0';

        /* Now make the name sane */
        name = (char *)make_name_sane(p, !compat_mode);
        if (!name)
            name = p;
    }

    /* name now points to the synthesized load_name and
     * may be the argument (== s), allocated (== mem), or
     * points to a static buffer otherwise.
     */

    /* '/.c' is a legal object name, so make sure that
     * the result will be '/' (in compat mode).
     */
    if (compat_mode && '\0' == *name)
        name = "/";

    /* Now return the result */
    if (get_txt(s) != name)
    {
        free_string_svalue(sp);
        put_c_string(sp, name);
    }

    if (mem)
        xfree(mem);

    return sp;
} /* f_load_name() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_object_name (svalue_t *sp)

/* EFUN object_name()
 *
 *   string object_name()
 *   string object_name(object ob)
 *
 * Get the name of an object <ob> or, if no argument is given, of
 * the current object.
 *
 * As a special case, if <obj> is 0, the function returns 0.
 *
 * This name is the name under which the object is stored in the
 * muds object table. It is initialised at the creation of the
 * object such that blueprints are named after the file they are
 * compiled from (without the trailing '.c'), and clones receive
 * the name of their blueprint, extended by '#' followed by
 * a unique non-negative number. These rules also apply to
 * virtual objects - the real name/type of virtual objects
 * is ignored.
 *
 * The name of an object can be changed with rename_object(), and
 * object_name() will reflect any of these changes.
 *
 * The returned name always begins with '/' (absolute path),
 * except when the parser runs in COMPAT mode.
 */

{
    string_t *name, *res;

    /* If the argument is 0, just return 0. */
    if (sp->type == T_NUMBER)
    {
        return sp;
    }

    name = sp->u.ob->name;
    if (compat_mode)
        res = ref_mstring(name);
    else
        res = add_slash(name);
    if (!res)
        errorf("Out of memory\n");
    free_object_svalue(sp);
    put_string(sp, res);

    return sp;
} /* f_object_name() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_object_time (svalue_t *sp)

/* EFUN object_time()
 *
 *   int object_time()
 *   int object_time(object ob)
 *
 * Returns the creation time of the object.
 * Default is this_object(), if no arg is given.
 */

{
    mp_int load_time;

    load_time = sp->u.ob->load_time;

    free_object_svalue(sp);
    put_number(sp, load_time);

    return sp;
} /* f_object_time() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_program_name (svalue_t *sp)

/* EFUN program_name()
 *
 *   string program_name()
 *   string program_name(object obj)
 *
 * Returns the name of the program of <obj>, resp. the name of the
 * program of the current object if <obj> is omitted.
 *
 * The returned name is usually the name from which the blueprint
 * of <obj> was compiled (the 'load name'), but changes if an
 * object replaces its programs with the efun replace_program().
 *
 * As a special case, if <ob> is 0, the function returns 0.
 *
 * The name always ends in '.c'. It starts with a '/' unless the
 * driver is running in COMPAT mode.
 */

{
    string_t *name, *res;
    object_t *ob;

    /* If the argument is 0, just return 0. */
    if (sp->type == T_NUMBER)
    {
        return sp;
    }

    ob = sp->u.ob;
    if (O_PROG_SWAPPED(ob))
    {
        ob->time_of_ref = current_time;
        if (load_ob_from_swap(ob) < 0)
        {
            errorf("Out of memory: unswap object '%s'\n", get_txt(ob->name));
        }
    }
    name = ob->prog->name;
    if (compat_mode)
        res = ref_mstring(name);
    else
        res = add_slash(name);
    if (!res)
        errorf("Out of memory\n");
    free_object_svalue(sp);
    put_string(sp, res);

    return sp;
} /* f_program_name() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_program_time (svalue_t *sp)

/* EFUN program_time()
 *
 *   int program_time()
 *   int program_time(object ob)
 *
 * Returns the creation (compilation) time of the object's
 * program. Default is this_object(), if no arg is given.
 */

{
    mp_int load_time;

    if (O_PROG_SWAPPED(sp->u.ob))
    {
        sp->u.ob->time_of_ref = current_time;
        if (load_ob_from_swap(sp->u.ob) < 0)
        {
            sp--;
            errorf("Out of memory: unswap object '%s'\n", get_txt(sp->u.ob->name));
        }
    }
    load_time = sp->u.ob->prog->load_time;

    free_object_svalue(sp);
    put_number(sp, load_time);

    return sp;
} /* f_program_time() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_query_once_interactive (svalue_t *sp)

/* EFUN query_once_interactive()
 *
 *   int query_once_interactive(object ob)
 *
 * True if the object is or once was interactive.
 */

{
    object_t *obj;

    obj = sp->u.ob;
    put_number(sp, obj->flags & O_ONCE_INTERACTIVE ? 1 : 0);
    deref_object(obj, "query_once_interactive");

    return sp;
} /* f_query_once_interactive() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_rename_object (svalue_t *sp)

/* EFUN rename_object()
 *
 *   void rename_object (object ob, string new_name);
 *
 * Give the object <ob> a new object name <new_name>. Causes a privilege
 * violation. The new name must not contain a # character, except
 * at the end, to avoid confusion with clone numbers.
 *
 * Raises a privilege violation ("rename_object", this_object(), ob, name).
 */

{
    object_t *ob;
    char     *name;
    string_t *m_name;
    mp_int length;

    inter_sp = sp; /* this is needed for assert_master_ob_loaded(), and for
                    * the possible errors before.
                    */
    ob = sp[-1].u.ob;
    name = get_txt(sp[0].u.str);

    /* Remove leading '/' if any. */
    while(name[0] == '/')
        name++;

    /* Truncate possible .c in the object name. */
    length = strlen(name);
    if (name[length-2] == '.' && name[length-1] == 'c') {
        /* A new writeable copy of the name is needed. */
        char *p;
        p = (char *)alloca(length+1);
        strcpy(p, name);
        name = p;
        name[length -= 2] = '\0';
    }

    {
        char c;
        char *p;
        mp_int i;

        i = length;
        p = name + length;
        while (--i > 0)
        {
            /* isdigit would need to check isascii first... */
            if ( (c = *--p) < '0' || c > '9' )
            {
                if (c == '#' && length - i > 1) {
                    errorf("Illegal name to rename_object: '%s'.\n", name);
                }
                break;
            }
        }
    }

    assert_master_ob_loaded();
    if (master_ob == ob)
        errorf("Attempt to rename the master object\n");

    m_name = new_mstring(name);
    if (!m_name)
        errorf("Out of memory for object name (%ld bytes)\n", (long)strlen(name));

    if (lookup_object_hash(m_name))
    {
        free_mstring(m_name);
        errorf("Attempt to rename to existing object '%s'\n", name);
    }

    if (privilege_violation4(STR_RENAME_OBJECT, ob, m_name, 0, sp)
     && check_object(ob)
       )
    {
        remove_object_hash(ob);
        free_mstring(ob->name);
        ob->name = m_name;
        enter_object_hash(ob);
    }
    else
        free_mstring(m_name);

    free_svalue(sp--);
    free_svalue(sp--);
    return sp;
} /* f_rename_object() */

/*-------------------------------------------------------------------------*/
svalue_t *
v_replace_program (svalue_t *sp, int num_arg)

/* EFUN replace_program()
 *
 *   void replace_program()
 *   void replace_program(string program)
 *
 * Substitutes a program with the inherited program <program>. If the object
 * inherits only one program, the argument may be omitted and the efun will
 * automatically select the one inherited program.
 *
 * This efun is useful if you consider the performance and memory consumption
 * of the driver. A program which doesn't need any additional variables and
 * functions (except during creation) can call replace_program() to increase
 * the function-cache hit-rate of the driver which decreases with the number
 * of programs in the system. Any object can call replace_program() but looses
 * all extra variables and functions which are not defined by the inherited
 * program.
 *
 * When replace_program() takes effect, shadowing is stopped on the object
 * since 3.2@166.
 *
 * It is not possible to replace the program of an object after (lambda)
 * closures have been bound to it. It is of course possible to first replace
 * the program and then bind lambda closures to it.
 *
 * The program replacement does not take place with the call to the efun, but
 * is merely scheduled to be carried out at the end of the backend cycle. This
 * may 

Showing the first 100 KB of 244.8 KB. Download the archive for the full file.

Site Stats

Snippets: 1791
Codebases: 571