efuns.c

ldmud-3.3.719/src/efuns.c · 271.0 KB

From the archive ldmud-3.3.719.tar.gz

Download the archive   « Back to the archive contents

/*---------------------------------------------------------------------------
 * Various Efuns.
 *
 *---------------------------------------------------------------------------
 * This file acts as a repository for various old and new efuns. Over the time
 * it will probably grow large enough to justify a split into several files.
 *
 * The implemented efuns, sorted by topic, are:
 *
 * Strings:
 *    TODO: Move into strfuns.c, rename the old strfuns to strutil.
 *    efun: capitalize()
 *    efun: crypt()
 *    efun: make_shared_string()
 *    efun: md5()
 *    efun: md5_crypt()
 *    efun: hash()
 *    efun: hmac()
 *    efun: regexp()
 *    efun: regexplode()
 *    efun: regreplace()
 *    efun: process_string() (optional)
 *    efun: sha()
 *    efun: sscanf()
 *    efun: strstr()
 *    efun: strrstr()
 *    efun: terminal_colour()
 *    efun: trim()
 *    efun: upper_case()
 *
 * Objects:
 *    TODO: Move into object.c.
 *    efun: blueprint()
 *    efun: clones()
 *    efun: object_info()
 *    efun: present_clone()
 *    efun: set_is_wizard() (optional)
 *
 * Values:
 *    efun: abs()
 *    efun: sin()
 *    efun: asin()
 *    efun: cos()
 *    efun: acos()
 *    efun: tan()
 *    efun: atan()
 *    efun: atan2()
 *    efun: log()
 *    efun: exp()
 *    efun: sqrt()
 *    efun: ceil()
 *    efun: floor()
 *    efun: pow()
 *    efun: to_int()
 *    efun: to_float()
 *    efun: to_string()
 *    efun: to_array()
#ifdef USE_STRUCTS
 *    efun: to_struct()
#endif
 *    efun: to_object()
 *    efun: copy()
 *    efun: deep_copy()
 *    efun: filter()
 *    efun: get_type_info()
 *    efun: map()
 *    efun: member()
 *    efun: min()
 *    efun: max()
 *    efun: reverse()
 *    efun: sgn()
 *    efun: quote()
 *
 * Others:
 *    efun: ctime()
 *    efun: debug_info()
 *    efun: rusage() (optional)
 *    efun: shutdown()
 *    efun: gmtime()
 *    efun: localtime()
 *    efun: time()
 *    efun: utime()
 *
 *---------------------------------------------------------------------------
 */

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

#include "my-alloca.h"
#include "my-rusage.h"
#include <ctype.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>

#include "efuns.h"

#include "actions.h"
#include "array.h"
#include "backend.h"
#include "call_out.h"
#include "closure.h"
#include "comm.h"
#include "dumpstat.h"
#include "exec.h"
#include "gcollect.h"
#include "heartbeat.h"
#include "interpret.h"
#include "lex.h"
#include "main.h"
#include "mapping.h"
#include "mempools.h"
#include "md5.h"
#include "mregex.h"
#include "mstrings.h"
#include "object.h"
#include "otable.h"
#include "ptrtable.h"
#include "random.h"
#include "sha1.h"
#include "stdstrings.h"
#include "simulate.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 "i-eval_cost.h"

#include "../mudlib/sys/debug_info.h"
#include "../mudlib/sys/driver_hook.h"
#include "../mudlib/sys/configuration.h"
#include "../mudlib/sys/objectinfo.h"
#include "../mudlib/sys/regexp.h"
#include "../mudlib/sys/strings.h"
#include "../mudlib/sys/time.h"
#include "../mudlib/sys/tls.h"

/* Variables */
string_t *last_ctime_result = NULL;
  /* points to the result of the last f_ctime() call. If the caller asks for 
   * the same timestamp, it will be returned. */

/* Forward declarations */
static void copy_svalue (svalue_t *dest, svalue_t *, struct pointer_table *, int);

/* Macros */

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

#ifdef USE_SET_IS_WIZARD
Bool is_wizard_used = MY_FALSE;
  /* TODO: This flag can go when the special commands are gone. */
#endif


/*=========================================================================*/
/*                              STRINGS                                    */

/*-------------------------------------------------------------------------*/
svalue_t *
f_capitalize(svalue_t *sp)

/* EFUN capitalize()
 *
 *     string capitalize(string str)
 *
 * Convert the first character in str to upper case, and return
 * the new string.
 */

{
    if (islower((unsigned char)(get_txt(sp->u.str)[0])))
    {
        string_t *new;
        memsafe(new = unshare_mstring(sp->u.str), mstrsize(sp->u.str), "result string");
        sp->u.str = new;
        get_txt(sp->u.str)[0] = toupper((unsigned char)get_txt(sp->u.str)[0]);
    }
    return sp;
} /* f_capitalize() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_crypt(svalue_t *sp)

/* EFUN crypt()
 *
 *   string crypt(string str, int seed)
 *   string crypt(string str, string seed)
 *
 * Crypt the string str using the integer seed or two characters
 * from the string seed as a seed. If seed is equal 0, then
 * a random seed is used.
 *
 * The result has the first two characters as the seed.
 */

{
    char *salt;
    char *res;
    char temp[3];
    static char choise[] =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";

    if (sp->type == T_STRING && mstrsize(sp->u.str) >= 2)
    {
        salt = get_txt(sp->u.str);
    }
    else if (sp->type == T_NUMBER)
    {
        temp[0] = choise[random_number((sizeof choise) - 1)];
        temp[1] = choise[random_number((sizeof choise) - 1)];
        temp[2] = '\0';
        salt = temp;
    }
    else /* it can't be anything but a too short string */
        errorf("Bad argument 2 to crypt(): string too short.\n");

    res = crypt(get_txt((sp-1)->u.str), salt);
    sp = pop_n_elems(2, sp);
    push_c_string(sp, res);

    return sp;
} /* f_crypt() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_explode (svalue_t * sp)

/* EFUN explode()
 *
 *   string *explode(string str, string del)
 *
 * Return an array of strings, created when the string str is
 * split into substrings as divided by del.
 */

{
    vector_t *v;

    v = explode_string((sp-1)->u.str, sp->u.str);
    free_string_svalue(sp);
    sp--;
    free_string_svalue(sp);
    put_array(sp,v);

    return sp;
} /* f_explode() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_implode (svalue_t * sp)

/* EFUN implode()
 *
 *   string implode(mixed *arr, string del)
 *
 * Concatenate all strings found in array arr, with the string
 * del between each element. Only strings are used from the array.
 */

{
    string_t *str;

    str = implode_string((sp-1)->u.vec, sp->u.str);
    if (!str)
        errorf("Out of memory for implode() result.\n");

    free_string_svalue(sp);
    sp--;
    free_array(sp->u.vec);

    if (str)
        put_string(sp, str);
    else
        put_number(sp, 0);
    return sp;
} /* f_implode() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_lower_case (svalue_t *sp)

/* EFUN lower_case()
 *
 *   string lower_case(string str)
 *
 * Convert all characters in str to lower case, and return the
 * new string.
 */

{
    char *s, c;
    size_t count, len;

    /* Find the first uppercase character */
    len = mstrsize(sp->u.str);
    for ( s = get_txt(sp->u.str), count = 0
        ; count < len && ('\0' == (c = *s) || !isupper((unsigned char)c))
        ; s++, count++) NOOP;

    if (count < len)
    {
        /* Yes, there is something to change... */

        string_t *new;
        memsafe(new = unshare_mstring(sp->u.str), mstrsize(sp->u.str), "result string");
        sp->u.str = new;

        for ( s = get_txt(sp->u.str)+count; count < len; s++, count++)
        {
            c = *s;
            if (c != '\0' && isupper((unsigned char)c))
                *s = (char)tolower((unsigned char)c);
        }
    }

    return sp;
} /* f_lower_case() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_make_shared_string (svalue_t *sp)

/* EFUN make_shared_string()
 *
 *    string make_shared_string(string s)
 *
 * If the passed string <s> is not shared, the efun enters it into
 * the shared string table and returns the shared version. Else the
 * passed string is returned.
 */

{
    sp->u.str = make_tabled(sp->u.str);

    return sp;
} /* f_make_shared_string() */

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

/* EFUN: md5()
 *
 *   string md5(string arg [, int iterations ] )
 *   string md5(int *  arg [, int iterations ] )
 *
 * Create and return a MD5 message digest from the string/array <arg>.
 * If iterations is specified to number > 0, the digest is calculated
 * using the given number of iterations.
 */

{
    M_MD5_CTX context;
    string_t *s_digest;
    unsigned char *digest, d[17];
    int i;
    p_int iterations;

    if (num_arg == 2)
    {
        iterations = sp->u.number;
        sp--;
    }
    else
        iterations = 1;

    if (iterations < 1)
    {
        errorf("Bad argument 2 to md5(): expected a number > 0, but got %"
               PRIdPINT"\n", iterations);
        /* NOTREACHED */
        return sp;
    }

    if (add_eval_cost_n(10, iterations))
    {
        free_svalue(sp);
        put_number(sp, 0);

        // The interpreter loop will catch the exceeded evaluation cost.
        return sp;
    }

    if (sp->type == T_POINTER)
    {
        string_t * arg;
        char * argp;

        memsafe(arg = alloc_mstring(VEC_SIZE(sp->u.vec)), VEC_SIZE(sp->u.vec)
               , "md5 argument string");
        argp = get_txt(arg);

        for (i = 0; i < VEC_SIZE(sp->u.vec); i++)
        {
            if (sp->u.vec->item[i].type != T_NUMBER)
            {
                free_mstring(arg);
                errorf("Bad argument 1 to md5(): got mixed*, expected string/int*.\n");
                /* NOTREACHED */
                return sp;
            }
            argp[i] = (char)sp->u.vec->item[i].u.number & 0xff;
        }

        free_svalue(sp);
        put_string(sp, arg);
    }

    MD5Init(&context);
    MD5Update(&context, (unsigned char *)get_txt(sp->u.str), mstrsize(sp->u.str));
    MD5Final(&context, d);

    while (--iterations > 0)
    {
        MD5Init(&context);
        MD5Update(&context, d, sizeof(d)-1);
        MD5Final(&context, d);
    }

    memsafe(s_digest = alloc_mstring(32), 32, "md5 encryption result");
    digest = (unsigned char *)get_txt(s_digest);

    d[16]='\0';

    for (i = 0; i < 16; i++)
        sprintf((char *)digest+2*i, "%02x", d[i]);

    free_svalue(sp);
    put_string(sp, s_digest);

    return sp;
} /* f_md5() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_md5_crypt(svalue_t *sp)

/* EFUN md5_crypt()
 *
 *   string md5_crypt(string str, null|int seed)
 *   string md5_crypt(string str, string seed)
 *
 * Crypt the string <str> using the first two characters
 * from the string <seed> as a seed. If <seed> is equal 0, then
 * a random seed is used.
 *
 * The result has the first two characters as the seed.
 *
 * The efun uses the MD5 algorithm for encryption, and is compatible
 * with the Apache webserver.
 */

{
    char *salt;
    char temp[10];
    char crypted [120];
    static char choise[] =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";

    if (sp->type == T_STRING && mstrsize(sp->u.str) >= 2)
    {
        salt = get_txt(sp->u.str);
    }
    else if (sp->type == T_NUMBER)
    {
        temp[0] = choise[random_number((sizeof choise) - 1)];
        temp[1] = choise[random_number((sizeof choise) - 1)];
        temp[2] = choise[random_number((sizeof choise) - 1)];
        temp[3] = choise[random_number((sizeof choise) - 1)];
        temp[4] = choise[random_number((sizeof choise) - 1)];
        temp[5] = choise[random_number((sizeof choise) - 1)];
        temp[6] = choise[random_number((sizeof choise) - 1)];
        temp[7] = choise[random_number((sizeof choise) - 1)];
        temp[8] = choise[random_number((sizeof choise) - 1)];
        temp[9] = '\0';
        salt = temp;
    }
    else /* it can't be anything but a too short string */
        errorf("Bad argument 2 to md5_crypt(): string too short.\n");

    MD5Encode((unsigned char *)get_txt((sp-1)->u.str)
             ,(unsigned char *)salt
             , crypted
             , sizeof(crypted));
    sp = pop_n_elems(2, sp);
    push_c_string(sp, crypted);

    return sp;
} /* f_md5_crypt() */

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

/* EFUN: sha1()
 *
 *   string sha1(string arg [, int iterations ] )
 *   string sha1(int *  arg [, int iterations ] )
 *
 * Create and return a SHA1 message digest from the string/array <arg>.
 * If iterations is specified to number > 0, the digest is calculated
 * using the given number of iterations.
 */

{
    SHA1Context context;
    string_t *s_digest;
    unsigned char *digest, d[SHA1HashSize];
    int i;
    p_int iterations;

    if (num_arg == 2)
    {
        iterations = sp->u.number;
        sp--;
    }
    else
        iterations = 1;

    if (iterations < 1)
    {
        errorf("Bad argument 2 to sha1(): expected a number > 0, but got %"
               PRIdPINT"\n", iterations);
        /* NOTREACHED */
        return sp;
    }

    if (add_eval_cost_n(10, iterations))
    {
        free_svalue(sp);
        put_number(sp, 0);

        /* The interpreter loop will catch the exceeded evaluation cost. */
        return sp;
    }

    if (sp->type == T_POINTER)
    {
        string_t * arg;
        char * argp;

        memsafe(arg = alloc_mstring(VEC_SIZE(sp->u.vec)), VEC_SIZE(sp->u.vec)
               , "sha1 argument string");
        argp = get_txt(arg);

        for (i = 0; i < VEC_SIZE(sp->u.vec); i++)
        {
            if (sp->u.vec->item[i].type != T_NUMBER)
            {
                free_mstring(arg);
                errorf("Bad argument 1 to sha1(): got mixed*, expected string/int*.\n");
                /* NOTREACHED */
            }
            argp[i] = (char)sp->u.vec->item[i].u.number & 0xff;
        }

        free_svalue(sp);
        put_string(sp, arg);
    }

    SHA1Reset(&context);
    SHA1Input(&context, (unsigned char *)get_txt(sp->u.str), mstrsize(sp->u.str));
    SHA1Result(&context, d);

    while (--iterations > 0)
    {
        SHA1Reset(&context);
        SHA1Input(&context, d, sizeof(d));
        SHA1Result(&context, d);
    }

    memsafe(s_digest = alloc_mstring(2 * SHA1HashSize)
           , 2 & SHA1HashSize, "sha1 encryption result");
    digest = (unsigned char *)get_txt(s_digest);

    for (i = 0; i < SHA1HashSize; i++)
        sprintf((char *)digest+2*i, "%02x", d[i]);

    free_svalue(sp);
    put_string(sp, s_digest);

    return sp;
} /* v_sha1() */

/*-------------------------------------------------------------------------*/
#if (!defined(USE_TLS) || !defined(HAS_OPENSSL)) && !defined(USE_GCRYPT) 
Bool
get_digest (int num, digest_t * md, size_t *len)

/* Determine the proper digest descriptor <*md> and length <*len>
 * from the designator <num>, which is one of the TLS_HASH_ constants.
 *
 * Return MY_FALSE if the desired digest isn't available.
 */

{
    switch(num)
    {
        case TLS_HASH_MD5:
            *md = num;
            *len = 16;
            break;

        case TLS_HASH_SHA1:
            *md = num;
            *len = SHA1HashSize;
            break;

        default:
            return MY_FALSE;
    }

    return MY_TRUE;
} /* get_digest() */

/*-------------------------------------------------------------------------*/
void
calc_digest (digest_t md, void *dest, size_t destlen, void *msg, size_t msglen, void *key, size_t keylen)

/* Calculates the hash or the HMAC if <key> != NULL from <msg> as determined
 * by method <md> as it was returned by get_digest().
 */
{
    if(key)
    {
        errorf("hmac() is not supported without OpenSSL or GCrypt.\n");
        /* NOTREACHED */
    }
    else
        switch(md)
        {
            case TLS_HASH_MD5:
            {
                M_MD5_CTX context;

                MD5Init(&context);
                MD5Update(&context, msg, msglen);
                MD5Final(&context, dest);
                break;
            }
            case TLS_HASH_SHA1:
            {
                SHA1Context context;

                SHA1Reset(&context);
                SHA1Input(&context, msg, msglen);
                SHA1Result(&context, dest);
                break;
            }
            break;
        }
}

#endif

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

/* EFUN hash()
 *
 *   string hash(int method, string arg [, int iterations ] )
 *   string hash(int method, int *  arg [, int iterations ] )
 *
 * Calculate the hash from <arg> as determined by <method>. The
 * hash is calculated with <iterations> iterations, default is 1 iteration.
 *
 * <method> is one of the TLS_HASH_ constants defined in tls.h; not
 * all recognized methods may be supported for a given driven.
 */

{
    string_t *digest;
    digest_t md;
    char *tmp;
    size_t hashlen;
    p_int iterations;
    int i;

    if (num_arg == 3)
    {
        iterations = sp->u.number;
        sp--;

        inter_sp = sp;
    }
    else
        iterations = 1;

    if (iterations < 1)
    {
        errorf("Bad argument 3 to hash(): expected a number > 0, but got %ld\n"
              , (long) iterations);
        /* NOTREACHED */
        return sp;
    }

    if (add_eval_cost_n(10, iterations))
    {
        free_svalue(sp--);
        free_svalue(sp);
        put_number(sp, 0);

        /* The interpreter loop will catch the exceeded evaluation cost. */
        return sp;
    }

    if (sp->type == T_POINTER)
    {
        string_t * arg;
        char * argp;

        memsafe(arg = alloc_mstring(VEC_SIZE(sp->u.vec)), VEC_SIZE(sp->u.vec)
               , "hash argument string");
        argp = get_txt(arg);

        for (i = 0; i < VEC_SIZE(sp->u.vec); i++)
        {
            if (sp->u.vec->item[i].type != T_NUMBER)
            {
                free_mstring(arg);
                errorf("Bad argument 2 to hash(): got mixed*, expected string/int*.\n");
                /* NOTREACHED */
            }
            argp[i] = (char)sp->u.vec->item[i].u.number & 0xff;
        }

        free_svalue(sp);
        put_string(sp, arg);
    }

    if (!get_digest(sp[-1].u.number, &md, &hashlen))
    {
        errorf("Bad argument 1 to hash(): hash function %d unknown or unsupported.\n", (int) sp[-1].u.number);
    }

    memsafe(tmp = xalloc_with_error_handler(hashlen), hashlen, "hash result");
    sp = inter_sp;

    calc_digest(md, tmp, hashlen, get_txt(sp[-1].u.str), mstrsize(sp[-1].u.str), NULL, 0);

    while (--iterations > 0)
        calc_digest(md, tmp, hashlen, tmp, hashlen, NULL, 0);

    memsafe(digest = alloc_mstring(2 * hashlen), 2 & hashlen, "hex hash result");
    for (i = 0; i < hashlen; i++)
        sprintf(get_txt(digest)+2*i, "%02x", tmp[i] & 0xff);

    free_svalue(sp--); /* The error handler. */
    free_svalue(sp--); /* The message. */
    free_svalue(sp);   /* The method. */
    put_string(sp, digest);

    return sp;
} /* v_hash() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_hmac(svalue_t *sp)

/* EFUN hmac()
 *
 *   string hmac(int method, string key, string arg)
 *   string hmac(int method, string key, int * arg)
 *
 * Calculate the Hashed Message Authenication Code for <arg> based
 * on the digest <method> and the password <key>. Return the HMAC.
 *
 * <method> is one of the TLS_HASH_ constants defined in tls.h; not
 * all recognized methods may be supported for a given driven.
 */

{
    string_t *digest;
    digest_t md;
    char *tmp;
    size_t hashlen;
    int i;

    if (sp->type == T_POINTER)
    {
        string_t * arg;
        char * argp;

        memsafe(arg = alloc_mstring(VEC_SIZE(sp->u.vec)), VEC_SIZE(sp->u.vec)
               , "hash argument string");
        argp = get_txt(arg);

        for (i = 0; i < VEC_SIZE(sp->u.vec); i++)
        {
            if (sp->u.vec->item[i].type != T_NUMBER)
            {
                free_mstring(arg);
                errorf("Bad argument 2 to hash(): got mixed*, expected string/int*.\n");
                /* NOTREACHED */
            }
            argp[i] = (char)sp->u.vec->item[i].u.number & 0xff;
        }

        free_svalue(sp);
        put_string(sp, arg);
    }

    if (!get_digest(sp[-2].u.number, &md, &hashlen))
    {
        errorf("Bad argument 1 to hmac(): hash function %d unknown or unsupported.\n", (int) sp[-2].u.number);
    }

    memsafe(tmp = xalloc_with_error_handler(hashlen), hashlen, "hash result");
    sp = inter_sp;

    calc_digest(md, tmp, hashlen
               , get_txt(sp[-1].u.str), mstrsize(sp[-1].u.str)
               , get_txt(sp[-2].u.str), mstrsize(sp[-2].u.str));

    memsafe(digest = alloc_mstring(2 * hashlen)
           , 2 & hashlen, "hmac result");
    for (i = 0; i < hashlen; i++)
        sprintf(get_txt(digest)+2*i, "%02x", tmp[i] & 0xff);

    free_svalue(sp--); /* The error handler. */
    free_svalue(sp--); /* The message. */
    free_svalue(sp--); /* The key. */
    free_svalue(sp);   /* The method. */
    put_string(sp, digest);

    return sp;
} /* f_hmac */

/*-------------------------------------------------------------------------*/
svalue_t *
f_regexp_package (svalue_t *sp)

/* EFUN regexp()
 *
 *   int regexp_package()
 *
 * Return which regexp package is used by default:
 *   RE_TRADITIONAL: traditional regexps
 *   RE_PCRE:        PCRE
 */

{
    p_int pkg = 0;

    if (driver_hook[H_REGEXP_PACKAGE].u.number)
        pkg = driver_hook[H_REGEXP_PACKAGE].u.number;
    else
        pkg = regex_package;

    push_number(sp, pkg);
    return sp;
} /* f_regexp_package() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_regexp (svalue_t *sp)

/* EFUN regexp()
 *
 *   string *regexp(string *list, string pattern)
 *   string *regexp(string *list, string pattern, int opt)
 *
 * Match the pattern pattern against all strings in list, and return a
 * new array with all strings that matched. This function uses the
 * same syntax for regular expressions as ed(), and can be given
 * additional options <opt> for the pattern interpretation.
 */

{
    vector_t *v;               /* The vector to match */
    regexp_t *reg;             /* compiled regexp */
    CBool *res;                /* res[i] true -> v[i] matches */
    mp_int num_match, v_size;  /* Number of matches, size of <v> */
    vector_t *ret;             /* The result vector */
    string_t * pattern;        /* The pattern passed in */
    int        opt;            /* The RE options passed in */
    int        rc;             /* Resultcode from the rx_exec() call */
    mp_int i, j;

    v = (sp-2)->u.vec;
    pattern = (sp-1)->u.str;
    opt = (int)sp->u.number;
    ret = NULL;

    do {
        /* Simple case: empty input yields empty output */
        if ((v_size = (mp_int)VEC_SIZE(v)) == 0)
        {
            ret = allocate_array(0);
            break;
        }

        /* Compile the regexp (or take it from the cache) */
        reg = rx_compile(pattern, opt, MY_FALSE);
        if (reg == NULL)
        {
            break;
        }

        /* Check every string in <v> if it matches and set res[]
         * accordingly.
         * Allocate memory and push error handler on the stack.
         */
        res = xalloc_with_error_handler(v_size * sizeof(*res));
        if (!res)
        {
            free_regexp(reg);
            errorf("Out of memory (%"PRIdMPINT" bytes) in regexp()",
                    v_size * sizeof(*res));
            /* NOTREACHED */
            return sp;
        }
        sp = inter_sp;

        for (num_match = i = 0; i < v_size; i++) {
            string_t *line;

            res[i] = MY_FALSE;

            if (v->item[i].type != T_STRING)
                continue;

            if (add_eval_cost(1))
            {
                /* Evalution cost exceeded: we abort matching at this point
                 * and let the interpreter detect the exception.
                 */
                break;
            }

            line = v->item[i].u.str;
            rc = rx_exec(reg, line, 0);
            if (rc == 0)
                continue;
            if (rc < 0)
            {
                const char * emsg = rx_error_message(rc, reg);
                free_regexp(reg);
                errorf("regexp: %s\n", emsg);
                /* NOTREACHED */
                return NULL;
            }

            res[i] = MY_TRUE;
            num_match++;
        }

        /* Create the result vector and copy the matching lines */
        ret = allocate_array(num_match);
        for (j=i=0; i < v_size && j < num_match; i++) {
            if (!res[i])
                continue;
            assign_svalue_no_free(&ret->item[j++], &v->item[i]);
        }
        /* Free regexp and the intermediate buffer res by freeing the error
         * handler. */
        free_regexp(reg);
        free_svalue(sp--);
    } while(0);

    free_svalue(sp--);
    free_svalue(sp--);
    free_svalue(sp);
    if (ret == NULL)
        put_number(sp, 0);
    else
        put_array(sp, ret);

    return sp;
} /* f_regexp() */

/*-------------------------------------------------------------------------*/
/* The found delimiter matches in f_regexplode() are kept in a list of these
 * structures.
 */
struct regexplode_match {
    size_t start, end;              /* Start and end of the match in text */
    struct regexplode_match *next;  /* Next list element */
};

/* We need a special error handling for f_reg_explode(). It allocates a
 * chained list of regexplode_match structures in a mempool and the compiled
 * regexp which we have to free.
 */
struct regexplode_cleanup_s {
    svalue_t sval;
    regexp_t *reg;
    Mempool matchmempool;
};

static void
regexplode_error_handler( svalue_t * arg)
/* The error handler: delete the mempool and free the compiled regexp.
 * Note: it is static, but the compiler will have to emit a function and 
 * symbol for this because the address of the function is taken and it is 
 * therefore not suitable to be inlined.
 */
{
    struct regexplode_cleanup_s *handler = (struct regexplode_cleanup_s *)arg;
    
    if (handler->reg)
        free_regexp(handler->reg);
    
    if (handler->matchmempool) {
        mempool_delete(handler->matchmempool);
    }
    xfree(handler);
} /* regexplode_error_handler() */

svalue_t *
f_regexplode (svalue_t *sp)

/* EFUN regexplode()
 *
 *   string *regexplode (string text, string pattern)
 *   string *regexplode (string text, string pattern, int opt)
 *
 * Explode the <text> by the delimiter <pattern> (interpreted according
 * to <opt> if given), returning a vector of the exploded text.
 * If flag RE_OMIT_DELIM is not set, then every second element in the result
 * vector will be the text that matched the delimiter.
 * Evalcost: number of matches.
 */

{

    string_t *text;                    /* Input string */
    string_t *pattern;                 /* Delimiter pattern from the vm stack */
    regexp_t *reg;                     /* Compiled pattern */
    struct regexplode_match *matches;  /* List of matches */
    struct regexplode_match **matchp;  /* Pointer to previous_match.next */
    struct regexplode_match *match;    /* Current match structure */
    vector_t *ret;                     /* Result vector */
    svalue_t *svp;                     /* Next element in ret to fill in */
    int num_match;                     /* Number of matches */
    p_int arraysize;                   /* Size of result array */
    int       opt;                     /* RE options */
    int       rc;                      /* Result from rx_exec() */
    size_t    start;                   /* Start position for match */
    Mempool   pool;                    /* Mempool for the list of matches */
    /* cleanup structure holding the head of chain of matches */
    struct regexplode_cleanup_s *cleanup;

    
    /* Get the efun arguments */
    text = sp[-2].u.str;
    pattern = sp[-1].u.str;
    opt = (int)sp->u.number;
    
    /* allocate space for cleanup structure. */
    cleanup = xalloc(sizeof(*cleanup));
    if (!cleanup)
        errorf("Out of memory (%zu bytes) for cleanup structure in "
               "regexplode().\n",sizeof(*cleanup));

    /* create mempool */
    pool = new_mempool(size_mempool(sizeof(*matches)));
    if (!pool)
    {
        xfree(cleanup);
        errorf("Out of memory (%zu) for mempool in regexplode().\n",
               sizeof(*matches));
    }
    cleanup->matchmempool = pool;
    cleanup->reg = NULL;
    /*  push error handler above the args on the stack */
    sp = push_error_handler(regexplode_error_handler, &(cleanup->sval));
        
    reg = rx_compile(pattern, opt, MY_FALSE);
    if (reg == 0) {
        errorf("Unrecognized search pattern");
        /* NOTREACHED */
        return sp;
    }
    cleanup->reg = reg;
    
    /* Loop over <text>, repeatedly matching it against the pattern,
     * until all matches have been found and recorded.
     */
    start = 0;
    num_match = 0;
    matches = NULL;
    matchp = &matches;
    while ((rc = rx_exec(reg, text, start)) > 0)
    {
        if (add_eval_cost(1))
        {
            /* Evaluation cost exceeded: terminate matching early, but
             * let the interpreter loop handle the exception.
             */
            rc = 0;
            break;
        }

        match = mempool_alloc(pool, sizeof *match);
        if (!match)
        {
            errorf("Out of memory (%zu bytes) in regexplode().\n",
                   sizeof(*match));
            /* NOTREACHED */
            return sp;
        }
        rx_get_match(reg, text, &(match->start), &(match->end));
        start = match->end;
        /* add match to the match list */
        *matchp = match;
        matchp = &match->next;
        num_match++;
        
        if (start == mstrsize(text)
         || (match->start == start && ++start == mstrsize(text)) )
            break;
    }

    if (rc < 0) /* Premature abort on error */
    {
        const char * emsg = rx_error_message(rc, reg);
        errorf("regexp: %s\n", emsg);
        /* NOTREACHED */
        return NULL;
    }

    *matchp = 0; /* Terminate list properly */

    /* Prepare the result vector */
    if (opt & RE_OMIT_DELIM)
        arraysize = num_match+1;
    else
        arraysize = 2 * num_match + 1;

    if (max_array_size && arraysize > (long)max_array_size-1 ) {
        errorf("Illegal array size: %"PRIdPINT".\n", arraysize);
        /* NOTREACHED */
        return sp;
    }
    ret = allocate_array(arraysize);

    /* Walk down the list of matches, extracting the text parts and matched 
     * delimiters, copying them into ret.
     */
    svp = ret->item;
    start = 0;
    for (match = matches; match; match = match->next) {
        mp_int len;
        string_t *txt;

        /* Copy the text leading up to the current delimiter match. */
        len = match->start - start;
        if (len)
        {
            memsafe(txt = mstr_extract(text, start, match->start-1), 
                    (size_t)len, "text before delimiter");
            put_string(svp, txt);
        }
        else
            put_ref_string(svp, STR_EMPTY);
        
        svp++;

        /* Copy the matched delimiter */
        if (!(opt & RE_OMIT_DELIM))
        {
            len = match->end - match->start;
            if (len)
            {
                memsafe(txt = mstr_extract(text, match->start, match->end-1), (size_t)len, "matched delimiter");
                put_string(svp, txt);
            }
            else
                put_ref_string(svp, STR_EMPTY);
            
            svp++;
        }

        start = match->end;
    }

    /* Copy the remaining text (maybe the empty string) */
    {
        size_t len;
        string_t *txt;

        len = mstrsize(text) - start;
        if (len > 0)
        {
            memsafe(txt = mstr_extract(text, start, mstrsize(text)-1), (size_t)len, "remaining text");
            put_string(svp, txt);
        }
        else
            put_ref_string(svp, STR_EMPTY);
    }

    /* Cleanup: free error handler and 3 arguments. Freeing the error handler
     * will free the regexp and the chain of matches. */
    sp = pop_n_elems(4, sp);

    /* Return the result */
    sp++;
    put_array(sp, ret);
    return sp;
} /* f_regexplode() */

/*-------------------------------------------------------------------------*/
/* The found delimiter matches are kept in a list of these structures.
 */
struct regreplace_match {
    size_t start, end;              /* Start and end of the match in text */
    string_t *sub;                  /* Substituted string (counted ref) */
    struct regreplace_match *next;  /* Next list element */
};

/* To facilitate automatic cleanup of the temporary structures in case
 * of an error, the following structure will be pushed onto the VM stack
 * as T_ERROR_HANDLER.
 */

struct regreplace_cleanup_s {
    svalue_t   head;  /* The link to the error handler function */

    struct regreplace_match *matches;  /* List of matches */
    regexp_t *reg;                     /* Compiled pattern */
};

static void
regreplace_cleanup (svalue_t * arg)
{
    struct regreplace_cleanup_s * data = (struct regreplace_cleanup_s *)arg;
    struct regreplace_match *match;

    free_regexp(data->reg);
    for (match = data->matches; match != NULL;)
    {
        struct regreplace_match * next = match->next;

        if (match->sub)
            free_mstring(match->sub);
        xfree(match);

        match = next;
    }
    xfree(arg);
} /* regreplace_cleanup() */

/*-------------------------------------------------------------------------*/
svalue_t*
f_regreplace (svalue_t *sp)

/* EFUN regreplace()
 *
 *     string regreplace (string txt, string pattern, closure|string replace
 *                                                  , int flags)
 *
 * Search through <txt> for one/all occurences of <pattern> and replace them
 * with the <replace> pattern, returning the result.
 * <replace> can be a string, or a closure returning a string. If it is
 * a closure, it will be called with the matched substring and
 * the position at which it was found as arguments.
 *
 * <flags> is the bit-or of the regexp options, including:
 *   RE_GLOBAL       = 1: when given, all occurences of <pattern> are replace,
 *                        else just the first
 *
 * The function behaves like the s/<pattern>/<replace>/<flags> command
 * in sed or vi. It offers an efficient and far more powerful replacement
 * for implode(regexplode()).
 */

{
    int       flags;                   /* RE options */
    string_t *sub = NULL;              /* Replacement string */
    svalue_t *subclosure = NULL;       /* Replacement closure */
    string_t *text;                    /* Input string */
    string_t *pattern;                 /* Delimiter pattern from the vm stack */
    string_t *result;                  /* Result string */
    char     *dst;                     /* Result copy pointer */
    regexp_t *reg;                     /* Compiled pattern */
    struct regreplace_match **matchp;  /* Pointer to previous_match.next */
    struct regreplace_match *match;    /* Current match structure */
    int       num_matches;             /* Number of matches */
    int       rc;                      /* Result from rx_exec() */
    size_t    start;                   /* Start position for match */
    size_t    reslen;                  /* Result length */

    struct regreplace_cleanup_s * rcp;

    /* Must set inter_sp before call to rx_compile(),
     * because it might call errorf().
     */
    inter_sp = sp;

    /* Extract the arguments */
    flags = sp->u.number;
    if (sp[-1].type == T_STRING)
    {
        sub = sp[-1].u.str;
        subclosure = NULL;
    }
    else /* it's a closure */
    {
        sub = NULL;
        subclosure = sp-1;
    }

    pattern = sp[-2].u.str;
    text = sp[-3].u.str;

    reg = rx_compile(pattern, flags, MY_FALSE);
    if (reg == 0)
    {
        errorf("Unrecognized search pattern");
        /* NOTREACHED */
        return sp;
    }

    /* Create the automatic cleanup structure */
    rcp = xalloc(sizeof(*rcp));
    if (!rcp)
    {
        free_regexp(reg);
        errorf("(regreplace) Out of memory: (%lu bytes) for cleanup structure\n"
             , (unsigned long)sizeof(*rcp));
    }

    rcp->reg = reg;
    rcp->matches = NULL;

    sp = push_error_handler(regreplace_cleanup, &(rcp->head));

    /* Loop over <text>, repeatedly matching it against the pattern,
     * until all matches have been found and recorded.
     */
    start = 0;
    num_matches = 0;
    matchp = &(rcp->matches);
    reslen = 0;
    while ((rc = rx_exec(reg, text, start)) > 0)
    {
        if (add_eval_cost(1))
        {
            /* Evaluation cost exceeded: terminate the matching early,
             * but let the interpreter handle the exception.
             */
            rc = 0;
            break;
        }

        xallocate(match, sizeof(*match), "regreplace match structure");
        rx_get_match(reg, text, &(match->start), &(match->end));
        match->sub = NULL;
        match->next = NULL;
        *matchp = match;
        matchp = &match->next;
        num_matches++;

        /* Compute the replacement string */
        /* Determine the replacement pattern.
         */
        if (subclosure != NULL)
        {
            mp_int len;
            string_t *matched_text;

            len = match->end - match->start;
            if (len)
            {
                matched_text = mstr_extract(text, match->start, match->end-1);
                if (!matched_text)
                {
                    outofmem((size_t)len, "matched text");
                    /* NOTREACHED */
                    return NULL;
                }
            }
            else
                matched_text = ref_mstring(STR_EMPTY);

            push_string(inter_sp, matched_text); /* Gives up the ref */
            push_number(inter_sp, match->start);
            call_lambda(subclosure, 2);
            transfer_svalue(&apply_return_value, inter_sp);
            inter_sp--;

            if (apply_return_value.type != T_STRING)
            {
                errorf("Invalid type for replacement pattern: %s, expected string.\n", typename(apply_return_value.type));
                /* NOTREACHED */
                return NULL;
            }

            sub = apply_return_value.u.str;
        }

        match->sub = rx_sub(reg, text, sub);
        if (!match->sub)
        {
            outofmemory("substituted string");
            /* NOTREACHED */
            return NULL;
        }

        /* Count the length(s) */
        reslen += match->start - start;
        reslen += mstrsize(match->sub);

        /* Prepare for the next match
         * Avoid another rx_exec() call if we are at the end.
         */
        start = match->end;

        if (start > mstrsize(text))
            break;
        if (match->start == start)
        {
            ++reslen; /* Empty match leaves old char in place */
            if (++start > mstrsize(text))
                break;
        }

        /* If RE_GLOBAL is not set, don't look for a second match */
        if (num_matches && (flags & RE_GLOBAL) == 0)
            break;
    } /* while(matches) */

    if (rc < 0) /* Premature abort on error */
    {
        const char * emsg = rx_error_message(rc, reg);
        errorf("regexp: %s\n", emsg);
        /* NOTREACHED */
        return NULL;
    }

    /* Add the remaining length */
    reslen += mstrsize(text) - start;

    /* Prepare the result string */
    result = alloc_mstring(reslen);
    if (!result)
    {
        outofmem(reslen, "result string");
        /* NOTREACHED */
        return NULL;
    }

    /* Walk down the list of matches, extracting the
     * text parts and substitute strings, copying them
     * into the result.
     */
    dst = get_txt(result);
    start = 0;
    for (match = rcp->matches; match; match = match->next)
    {
        size_t len;

        /* Copy the text leading up to the current delimiter match. */
        len = match->start - start;
        if (len)
        {
            memcpy(dst, get_txt(text)+start, len);
            dst += (size_t)len;
        }

        /* Copy the substitute string */
        len = mstrsize(match->sub);
        if (len)
        {
            memcpy(dst, get_txt(match->sub), len);
            dst += (size_t)len;
        }

        start = match->end;
    }

    /* Copy the remaining text if any */
    {
        size_t len;

        len = mstrsize(text) - start;
        if (len)
        {
            memcpy(dst, get_txt(text)+start, len);
            dst += (size_t)len;
        }
    }

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

    /* Return the result */
    put_string(sp, result);
    return sp;
} /* f_regreplace() */

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

/* EFUN regmatch()
 *
 *     string    regmatch (string txt, string pattern)
 *     string[*] regmatch (string txt, string pattern, int flags)
 *     string[*] regmatch (string txt, string pattern, int flags, int start)
 *
 * Match the string <txt> against <pattern>, which is interpreted according
 * to the RE options given in <flags>. If <start> is given, it is the start
 * position for the match and must be in the range [0..strlen(txt)].
 *
 * If there is no match, the result is 0. If there is a match, the exact
 * result is determined by the flag RE_MATCH_SUBS:
 *
 * If the flag RE_MATCH_SUBS is not set, the result is the matched expression.
 *
 * If the flag RE_MATCH_SUBS is set, the result is an array of the matched
 * string(s) of the first match. Entry [0] is the full string matching the
 * <pattern>, following entries are the string segments matching
 * parenthesized subexpressions in <pattern>. If a particular subexpression
 * didn't have a match, the corresponding array entry will be 0.
 * The last entry in the array will be the new start index in case you
 * want to repeat the match on the remaining parts of the string. This new
 * index is usually equal the length of the match, but at least one higher
 * than the original start index.
 */

{
    svalue_t *argp;     /* Arguments */
    regexp_t *reg;      /* The compiled RE */
    int       flags;    /* RE options */
    size_t    startpos; /* Match start argument */
    string_t *text;     /* Input string */
    string_t *pattern;  /* Delimiter pattern from the vm stack */
    int       rc;       /* Result from rx_exec() */
    vector_t *result;   /* Result vector */
    string_t *resstr;   /* Result string */

    /* Must set inter_sp before call to rx_compile(),
     * because it might call errorf().
     */
    inter_sp = sp;

    /* Extract the arguments */
    argp = sp - num_arg + 1;
    text = argp[0].u.str;
    pattern = argp[1].u.str;
    flags = startpos = 0;
    if (num_arg > 2)
    {
        flags = argp[2].u.number;
        if (num_arg > 3)
        {
            startpos = (size_t)argp[3].u.number;
            if (startpos > mstrsize(text))
            {
                errorf("regmatch(): Start index out of range: %zu, "
                      "should be in [0..%zu]\n",
                      startpos, mstrsize(text)
                     );
                /* NOTREACHED */
                startpos = 0;
            }

            if (startpos == mstrsize(text))
            {
                /* No match possible - return right here */
                sp -= 2; /* No need to free_svalue() the known two integers */
                free_svalue(sp); /* Pattern */
                sp--;
                free_svalue(sp); /* Text */
                put_number(sp, 0);
                return sp;
            }

            sp--;
        }
        sp--;

        num_arg = 2;
    }

    reg = rx_compile(pattern, flags, MY_FALSE);
    if (reg == 0) {
        errorf("Unrecognized match pattern");
        /* NOTREACHED */
        return sp;
    }

    rc = rx_exec(reg, text, startpos);
    if (rc < 0)
    {
        const char * emsg = rx_error_message(rc, reg);
        free_regexp(reg);
        errorf("regexp: %s\n", emsg);
        /* NOTREACHED */
        return NULL;
    }

    result = NULL;
    resstr = NULL;
    if (rc != 0)
    {
        if (flags & RE_MATCH_SUBS)
        {
            int num_matches = rx_num_matches(reg);
            int i;

            if (max_array_size && num_matches+1 > (long)max_array_size-1 ) {
                free_regexp(reg);
                inter_sp = sp;
                errorf("Illegal array size: %d", num_matches+1);
                /* NOTREACHED */
                return sp;
            }
            result = allocate_array(num_matches+1);
            if (!result)
            {
                free_regexp(reg);
                outofmemory("result array");
                /* NOTREACHED */
                return NULL;
            }

            for (i = 0; i < num_matches; i++)
            {
                size_t start, end;

                if (!rx_get_match_n(reg, text, i, &start, &end)
                 || start >= end
                   )
                {
                    put_number(&(result->item[i]), 0);
                }
                else
                {
                    string_t *str = mstr_extract(text, start, end-1);

                    if (!str)
                    {
                        free_regexp(reg);
                        free_array(result);
                        outofmem(end-start, "matched string");
                        /* NOTREACHED */
                        return NULL;
                    }

                    put_string(&(result->item[i]), str);
                }
            } /* for (i) */

            /* As last element, store the length of the match to give
             * the new starting position.
             */
            {
                size_t new_start;
                if (result->item[0].type == T_STRING)
                    new_start = mstrsize(result->item[0].u.str);
                else
                    new_start = 0;
                if (new_start == 0)
                    new_start++;
                put_number(&(result->item[num_matches]), (long)(startpos+new_start));
            }
        }
        else
        {
            size_t start, end;

            rx_get_match(reg, text, &start, &end);
            if (start >= end)
            {
                resstr = NULL;
            }
            else
            {
                resstr = mstr_extract(text, start, end-1);

                if (!resstr)
                {
                    free_regexp(reg);
                    outofmem(end-start, "matched string");
                    /* NOTREACHED */
                    return NULL;
                }
            }
        } /* if (flag & RE_MATCH_SUBS) */
    } /* if (rc > 0) */

    /* Cleanup */
    free_regexp(reg);
    free_svalue(sp); /* Pattern */
    sp--;
    free_svalue(sp); /* Text */

    /* Return the result */
    if (result)
        put_array(sp, result);
    else if (resstr)
        put_string(sp, resstr);
    else
        put_number(sp, 0);
    return sp;
} /* v_regmatch() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_strstr (svalue_t *sp)

/* EFUN strstr()
 *
 *   int strstr (string str, string str2, int pos)
 *
 * Returns the index of str2 in str searching from position pos forward.
 * If str2 is not found in str, -1 is returned. The returned
 * index is relativ to the beginning of the string.
 *
 * If pos is negativ, it counts from the end of the string.
 */

{
    const char *found;
    string_t *base, *pattern;
    p_int start, rc;

    base = sp[-2].u.str;
    pattern = sp[-1].u.str;

    if ( 0 != (start = sp->u.number) )
    {
        if (start < 0)
        {
            start += mstrsize(base);
            if (start < 0)
                start = 0;
        }
    }

    found = mstring_mstr_n_str(base, start, get_txt(pattern), mstrsize(pattern));
    rc = found ? (found - get_txt(base)) : -1;

    sp--;
    free_svalue(sp--);
    free_string_svalue(sp); /* Frees base ! */
    put_number(sp, rc);

    return sp;
} /* f_strstr() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_strrstr (svalue_t *sp)

/* EFUN strrstr()
 *
 *   int strrstr (string str, string str2, int pos)
 *
 * Returns the index of str2 in str searching from position pos backward.
 * If str2 is not found in str, -1 is returned. The returned
 * index is relativ to the beginning of the string.
 *
 * If pos is negativ, it counts from the end of the string.
 */

{
    const char *found;
    string_t *base, *pattern;
    p_int start, rc;

    base = sp[-2].u.str;
    pattern = sp[-1].u.str;

    if ( 0 != (start = sp->u.number) )
    {
        if (start < 0)
        {
            start += mstrsize(base);
            if (start < 0)
                start = 0;
        }
    }

    found = mstring_mstr_rn_str(base, start, get_txt(pattern), mstrsize(pattern));
    rc = found ? (found - get_txt(base)) : -1;

    sp--;
    free_svalue(sp--);
    free_string_svalue(sp); /* Frees base ! */
    put_number(sp, rc);

    return sp;
} /* f_strrstr() */

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

/* EFUN trim()
 *
 *    string trim (string s [, int where [, string|int ch]])
 *
 * Remove all leading/trailing characters <ch> from the string <s>
 * and return the new string. <ch> may be a single character, or a string
 * of characters to be trimmed. If <ch> is not given or 0, it defaults
 * to " \t". <where> determines where to remove the characters:
 *   TRIM_LEFT:  remove the leading characters
 *   TRIM_RIGHT: remove the trailing characters
 *   TRIM_BOTH:  remove both leading and trailing characters.
 *
 * TODO: Expand this to remove interim characters as well?
 * TODO: Expand this to fold runs of embedded chs into just one?
 */

{
    svalue_t * argp;
    string_t *strarg;    /* The string argument */
    size_t    strarg_l;  /* Length of *strarg */
    char *str, *end;     /* Pointer to string begin and end */
    char *left, *right;  /* Pointer to the strings left and right end */
    char def_ch[3]       /* Buffer for single characters to strip */
      = { '\t', ' ', '\0' };
    char *strip;         /* String of characters to strip */
    size_t strip_l;      /* Length of *strip */
    p_int  where;

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

    strarg = argp->u.str;
    str = get_txt(strarg);
    strarg_l = mstrsize(strarg);

    if (num_arg > 1)
    {
        where = argp[1].u.number;
        if (!where)
            where = TRIM_BOTH;
        if (where > TRIM_BOTH)
            errorf("Bad argument 2 to trim(): illegal value %"PRIdPINT"\n",
                   where);
    }
    else
        where = TRIM_BOTH;

    if (num_arg > 2)
    {
        if (argp[2].type == T_NUMBER)
        {
            if (argp[2].u.number < 0 || argp[2].u.number >= 1 << CHAR_BIT)
                errorf("Bad argument 3 to trim(): %"PRIdPINT
                       " is not a character\n", argp[2].u.number);
            def_ch[0] = (char)argp[2].u.number;
            def_ch[1] = '\0';
            strip = def_ch;
            strip_l = 1;
        }
        else /* it's a string */
        {
            strip = get_txt(argp[2].u.str);
            strip_l = mstrsize(argp[2].u.str);
        }
    }
    else
    {
       strip = def_ch;
       strip_l = 2;
    }

    /* Get the string limits */
    end = str + strarg_l;
    if (where & TRIM_LEFT)
    {
        for ( left = str
            ; left < str+strarg_l && memchr(strip, *left, strip_l) != NULL
            ; left++
            ) NOOP;
    }
    else
        left = str;

    if (where & TRIM_RIGHT && end != left)
    {
        for (right = end
            ; right != left && NULL != memchr(strip, right[-1], strip_l)
            ; right--) NOOP;
    }
    else
        right = end;

    /* If there are things to strip, create a new string and put it
     * into the place of the old one.
     */
    if (left != str || right != end)
    {
        string_t * trimmed;
        size_t newlen;

        newlen = (size_t)(right - left);
        memsafe(trimmed = new_n_mstring(left, newlen), newlen, "trimmed result");
        free_string_svalue(argp);
        put_string(argp, trimmed);
    }

    /* argp+2 might need to be freed, but argp+1 is always just a number.
     * And the result argp is fine as it is.
     */

    if (num_arg > 2 && argp[2].type == T_STRING)
        free_svalue(argp+2);

    return argp;
} /* v_trim() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_upper_case (svalue_t *sp)

/* EFUN upper_case()
 *
 *    string upper_case (string s)
 *
 * Convert all characters in <s> to upper case and return the new string.
 */

{
    char *s, c;
    size_t count, len;

    /* Find the first non-uppercase character in the string */
    len = mstrsize(sp->u.str);
    for (s = get_txt(sp->u.str), count = 0
        ; count < len && ('\0' == (c = *s) || !islower((unsigned char)c))
        ; s++, count++)
        NOOP;

    if (count < len)  /* there are lowercase characters */
    {
        string_t *new;
        memsafe(new = unshare_mstring(sp->u.str), mstrsize(sp->u.str), "result string");
        sp->u.str = new;

        for (s = get_txt(sp->u.str)+count; count < len; s++, count++)
        {
            c = *s;

            if ('\0' != c && islower((unsigned char)c))
                *s = (char)toupper((unsigned char)c);
        }
    }

    /* That's it */
    return sp;
} /* f_upper_case() */

/*-------------------------------------------------------------------------*/
static Bool
at_end (int i, int imax, int z, p_int *lens)

/* Auxilary function for e_terminal_colour().
 *
 * <z> is the position within string number <i>. <lens> is an array
 * with the lengths of all <imax> strings.
 *
 * The function returns true if there are no more characters to process
 * after <i>:<z> in all strings, else it returns false.
 */

{
    if (z + 1 < lens[i])
        return MY_FALSE;
    for (i++; i < imax; i++) {
        if (lens[i] > 0)
            return MY_FALSE;
    }
    return MY_TRUE;
}

/*-------------------------------------------------------------------------*/
static string_t *
e_terminal_colour ( string_t * text, mapping_t * map, svalue_t * cl
                  , int indent, int wrap
                  )

/* Implementation of the efun terminal_colour().
 * See f_terminal_colour() for the complete description.
 * TODO: Instead of computing the wrapping twice, the first pass
 * TODO:: should record what to break where.
 */

{
#define CALLOCATE(num, type) ((type *)xalloc(sizeof(type[1]) * (num) ))
  /* Allocate a block of <num> elements of <type>
   */

#define RESIZE(ptr, num, type) ((type *)rexalloc((void *)ptr, sizeof(type) * (num)))
  /* Resize the block <ptr> to hold <num> elements of <type>.
   */

#define NSTRSEGS       32
  /* Allocation increment. */

#define TC_FIRST_CHAR  '%'
#define TC_SECOND_CHAR '^'
  /* The two magic characters.
   */

#define MAX_STRING_LENGTH 200000
  /* The maximum length of the result.
   */

    char *cp;              /* Workpointer */
    string_t *savestr = NULL;  /* Allocated auxiliary string */
    char *instr;
      /* The input string. This may be get_txt(<text>) itself, or a working
       * copy. */
    string_t *deststr;         /* Result string */
    char **parts;
      /* The <num> delimited parts from <instr>. This are mostly
       * pointers into *<instr>, but can also be (uncounted) pointers to
       * the string data in <map>.
       */
    int num;               /* Number of delimited parts in <instr> */
    p_int *lens = NULL;
      /* Length of the <num> parts. This value is negative for strings
       * 'retrieved' from the <map>ping when wrapping is required. This
       * is necessary to determine which parts[] to exempt from the
       * wrapping calculation.
       */
    svalue_t * mdata_save = NULL;
      /* Pointer into an array on the stack, pointing to the next
       * free entry.
       * The array is used to keep copies of the replacement string
       * svalues to make sure that the strings exist as long as we
       * need them.
       * By keeping the array itself on the stack, cleanup is automatic.
       */
    int num_tmp;           /* Number of temporary svalues on the stack */
    int k;                 /* Index within a string */
    int col;               /* Current print column */
    int j;                 /* Accumulated total length of result */
    int j_extra;           /* Temporary extra length of result before fmt'ing */
    int start;             /* Col of first non-blank character */
    int space;             /* Col of last space char */
    int i;
    Bool maybe_at_end;     /* TRUE if the next text might start a new line */
    Bool no_keys;          /* TRUE if no delimiter in the string */
    Bool indent_overflows;
      /* Used to catch this boundary condition:
       *   t_c("\\/ "*32, 0, indent > MAX_STRING_LENGTH - 40, 40)
       * In this case, the last indent is followed by no data, which the
       * data copying part notices, but not the previous length calculation
       * part.
       * Set to TRUE in the length calculation when the possibility arises.
       */

    if (wrap && indent > wrap)
    {
        errorf("(terminal_colour) indent %ld > wrap %ld\n"
             , (long)indent, (long)wrap);
        /* NOTREACHED */
        return NULL;
    }

    instr = get_txt(text);
    num_tmp = 0;

    /* Find the first occurance of the magic character pair.
     * If found, duplicate the input string into instr and
     * let cp point into that copy at the delimiter.
     * If not found (or no mapping/closure given), cp will be NULL.
     */

    if (map != NULL || cl != NULL)
    {
        p_int left = mstrsize(text);

        cp = instr;
        do {
            char * last_cp = cp;
            cp = memchr(cp, TC_FIRST_CHAR, (size_t)left);
            if (cp)
            {
                if (cp[1] == TC_SECOND_CHAR)
                {
                    memsafe(savestr = dup_mstring(text), mstrsize(text)
                           , "working string");
                    cp = get_txt(savestr) + (cp - instr);
                    instr = get_txt(savestr);

                    /* Check for the special escape '%%^^'.
                     * If found, modify it to '%^%^, and let cp
                     * point to it.
                     */
                    if (cp > get_txt(savestr)
                     && cp[-1] == TC_FIRST_CHAR
                     && cp[2] == TC_SECOND_CHAR
                       )
                    {
                        cp--;
                        cp[1] = TC_SECOND_CHAR;
                        cp[2] = TC_FIRST_CHAR;
                    }
                    break;
                }

                /* Single '%': skip it and continue searching */
                cp++;
                left -= (cp - last_cp);
            }
        } while (cp && left > 0);

        if (left <= 0)
            cp = NULL;
    }
    else
        cp = NULL;

    /* If the delimiter was found, split up the instr into the
     * parts and store them. If not found, just return.
     */
    no_keys = MY_FALSE;
    if (cp == NULL)
    {
        /* No delimiter found - but maybe we need to wrap */
        if (wrap)
        {
            /* Yup, just fake one delimited part which just happens
             * to not match anything in the mapping.
             */
            num = 1;
            parts = CALLOCATE(1, char *);
            parts[0] = instr;
            lens = CALLOCATE(1, p_int);
            lens[0] = mstrsize(text);
            savestr = NULL;  /* should be NULL already anyway */
            no_keys = MY_TRUE;
        }
        else
        {
            /* no delimiter in string and no wrapping, so return the original.
             */
            return ref_mstring(text);
        }
    }
    else
    {
        /* There are delimiters in the string. Find them all, let the
         * pointers in *<parts> point to the strings delimited by
         * them, and let those parts end with a '\0'.
         * This means modifying the *<instr>, but it is already
         * a copy.
         */

        p_int left;

        /* If we got a mapping, do a one-time lookup for the default
         * entry and store it in <cl>.
         */
        if (map != NULL)
        {
            cl = get_map_value(map, &const0);
            if (cl->type == T_NUMBER && cl->u.number == 0)
                cl = NULL; /* No default entry */

            if (cl && cl->type != T_STRING && cl->type != T_CLOSURE)
            {
                errorf("(terminal_colour) Illegal type for default entry: %s, expected string or closure.\n", typename(cl->type));
                /* NOTREACHED */
                return text;
            }
        }

        /* cp here points to the first delimiter found */

        parts = CALLOCATE( NSTRSEGS, char * );
        if (!parts)
        {
            errorf("(terminal_colour) Out of memory (%lu bytes) "
                  "for %d parts.\n"
                 , (unsigned long) NSTRSEGS * sizeof(char*), NSTRSEGS);
            /* NOTREACHED */
            return NULL;
        }

        lens = CALLOCATE(NSTRSEGS, p_int);
        if (!lens)
        {
            xfree(parts);
            errorf("(terminal_colour) Out of memory (%lu bytes) "
                  "for %d parts.\n"
                 , (unsigned long) NSTRSEGS * sizeof(p_int), NSTRSEGS);
            /* NOTREACHED */
            return NULL;
        }

        /* The string by definition starts with a non-keyword,
         * which might be empty.
         * Initialize our variables accordingly.
         */
        num = 1;
        parts[0] = instr;
        lens[0] = cp - instr;
        left = mstrsize(text) - lens[0];

        /* Search and find the other delimited segments.
         * Loop variant: cp points to the last delimiter found,
         * or cp is NULL (exit condition)
         * Loop invariant: instr points to the begin of the last delimited
         * segment, left is the number of characters left in the string.
         */
        while (cp && left > 0)
        {
            /* Skip the delimiter found last and search the next */
            cp += 2;
            instr = cp;
            left -= 2;

            do
            {
                char * last_cp = cp;
                cp = memchr(cp, TC_FIRST_CHAR, left);
                if (cp) {
                    left -= (cp - last_cp);
                    if (cp[1] == TC_SECOND_CHAR)
                    {
                        /* Check for the special escape '%%^^'.
                         * If found, modify it to '%^%^, and let cp
                         * point to it.
                         */
                        if (cp > get_txt(savestr)
                         && cp[-1] == TC_FIRST_CHAR
                         && cp[2] == TC_SECOND_CHAR
                           )
                        {
                            cp--;
                            cp[1] = TC_SECOND_CHAR;
                            cp[2] = TC_FIRST_CHAR;
                            left++;
                        }
                        break;
                    }
                    cp++;
                    left--;
                }
            } while (cp && left > 0);
            if (left <= 0)
                cp = NULL;

            if (cp)
            {
                /* Another delimiter found: put it into the parts array.
                 */
                parts[num] = instr;
                lens[num] = cp - instr;
                num++;
                if (num % NSTRSEGS == 0)
                {
                    parts = RESIZE(parts, num + NSTRSEGS, char * );
                    lens = RESIZE(lens, num + NSTRSEGS, p_int );
                }
            }
        }

        /* Trailing part, or maybe just a delimiter */
        if (*instr)
        {
            parts[num] = instr;
            lens[num] = strlen(instr); /* Note: left is 0 here */
            num++;
        }
    } /* if (delimiter found or not) */

    /* If required, allocate the mdata save array on the stack */
    if (!no_keys)
    {
        vector_t *vec;

        vec = allocate_array_unlimited(num/2 + 1);
          /* Slightly bigger than required */
        mdata_save = vec->item;
        push_array(inter_sp, vec);
        num_tmp++;
    }

    /* Do the the keyword replacement and calculate the lengths.
     * The lengths are collected in the lens[] array to save the
     * need for repeated strlens().
     */
    for (i = 0; i < num; i++)
    {
        string_t * str;
        svalue_t * mdata;

        /* If parts[i] is a valid colour key, there must exist a shared
         * string for it. Is that the case, look up parts[i] in the
         * mapping and set the result in mdata, otherwise save that effort.
         * However, if i is even, parts[i] is by definition not a colour
         * key.
         */
        mdata = NULL;
        if (i % 2 && !no_keys)
        {
            if (lens[i] == 0) /* Empty key - already handled */
                str = NULL;
            else
            {
                str = find_tabled_str_n(parts[i], lens[i]);
            }
            if (str != NULL && map != NULL)
            {
                svalue_t mkey;

                put_string(&mkey, str);
                 /* The only use of mkey is to index a mapping - an
                  * operation which will not decrement the refcount
                  * for <str>. This makes it safe to not count the
                  * ref by mkey here, and saves a bit time.
                  */

                /* now look for mapping data */
                mdata = get_map_value(map, &mkey);
                if (mdata->type == T_NUMBER && mdata->u.number == 0)
                    mdata = NULL; /* No entry */
            }

            /* If the map lookup didn't find anything, try the
             * <cl>osure (which might be the default entry)
             */
            if (mdata == NULL && cl != NULL && parts[i][0] != '\0')
            {
                if (cl->type == T_STRING)
                {
                    mdata = cl;
                }
                else
                {
                    /* It's a closure.
                     * We keep the result in the array on the stack
                     * to make sure it lives until we are done processing it.
                     */
                    push_c_n_string(inter_sp, parts[i], lens[i]);
                    call_lambda(cl, 1);
                    *mdata_save = *inter_sp;
                    inter_sp--;
                    mdata = mdata_save++;
                    if (mdata->type != T_STRING)
                    {
                        errorf("(terminal_colour) Closure did not return a string.\n");
                        /* NOTREACHED */
                        return NULL;
                    }
                }
            }
        }
        else if (!(i % 2) && !no_keys
              && i < num -1 && lens[i+1] == 0)
        {
            /* Special case: the following colour key is the empty "%^%^".
             * We interpret it as literal "%^" and add it to this part.
             * Both part[i] and part[i+1] will end with the same char.
             */
            lens[i] += 2;
        }

        /* If mdata found a string, use it instead of the old parts[i].
         * Note its length, making it negative where necessary.
         */
        if ( mdata && mdata->type == T_STRING )
        {
            parts[i] = get_txt(mdata->u.str);
            lens[i] = (p_int)mstrsize(mdata->u.str);
            if (wrap)
                lens[i] = -lens[i];
        }
    } /* for (i = 0..num) for length gathering */

    /* Do the wrapping analysis.
     * In order to do this, we need to have all lengths already
     * available.
     */
    col = 0;
    start = -1;
    space = 0;
    maybe_at_end = MY_FALSE;
    indent_overflows =  MY_FALSE;
    j = 0; /* gathers the total length of the final string */
    j_extra = 0; /* gathers the extra length needed during fmt'ing */
    for (i = 0; i < num; i++)
    {
        if (lens[i] > 0)
        {
            /* This part must be considered for wrapping/indentation */
            p_int len;

            len = lens[i];
            if (maybe_at_end)
            {
                /* This part may start a new line, so count in the indent */

                if (j + indent > MAX_STRING_LENGTH)
                {
                    /* This string no longer counts, so we are still in a
                     * maybe_at_end condition.  This means we will end up
                     * truncating the rest of the fragments too, since the
                     * indent will never fit.
                     */
                    lens[i] = 0;
                    len = 0;
                }
                else
                {
                    j += indent;
                    col += indent;
                    maybe_at_end = MY_FALSE;
                }
            }

            /* Add the new string to the total length */
            j += len;
            if (j > MAX_STRING_LENGTH)
            {
                /* Overflow: shorten this fragment to fit (and all
                 * the following ones will be shortened to 0 length).
                 */
                lens[i] -= j - MAX_STRING_LENGTH;
                j = MAX_STRING_LENGTH;
            }

            /* If wrapping is requested, perform the analysis */
            if (wrap)
            {
                int   z;             /* Index into the current string */
                char *p = parts[i];  /* Pointer into the current string */

                for (z = 0; z < lens[i]; z++)
                {
                    char c = p[z];   /* current character */

                    if (c == '\n')
                    {
                        /* Hard line break: start a new line */
                        col = 0;
                        start = -1;
                    }
                    else
                    {
                        /* All space characters in columns before col <start>
                         * do not count.
                         */
                        if (col > start || c != ' ')
                            col++;
                        else
                        {
                            j--;
                            j_extra++;
                        }

                        /* If space, remember the position */
                        if (c == ' ')
                            space = col;

                        if (col == wrap+1)
                        {
                            /* Wrapping necessary */

                            if (space)
                            {
                                /* Break the line at the last space */
                                int next_word_len = 0;

                                if (col - space > 2)
                                {
                                    /* Check if the current word is too
                                     * long to be put on one line. If it
                                     * is, don't bother breaking at the last
                                     * space.
                                     */
                                    int test_z = z;
                                    int test_i = i;
                                    Bool done = MY_FALSE;

                                    next_word_len = col - space;
                                    for ( ; !done && test_i <  num; test_i++)
                                    {
                                        if (lens[test_i] < 0)
                                            continue;
                                        for ( ; !done && test_z < lens[test_i]; test_z++)
                                        {
                                            char testc = parts[test_i][test_z];
                                            if (testc == ' ' || testc == '\n')
                                            {
                                                done = MY_TRUE;
                                                break;
                                            }
                                            next_word_len++;
                                        }
                                        test_z = 0;
                                    }
                                }

                                if (next_word_len+indent > wrap)
                                {
                                    /* Word is too long, just treat it
                                     * as if there is no space within range.
                                     */
                                    space = 0;
                                    j++;
                                    col = 1;
                                }
                                else
                                {
                                    /* It makes sense to break properly */
                                    col -= space;
                                    space = 0;
                                }
                            }
                            else
                            {
                                /* No space within range: simply let this
                                 * one extent over the wrap margin and
                                 * restart counting.
                                 */
                                j++;
                                col = 1;
                            }

                            /* Reset the start column. */
                            start = indent;
                        }
                        else
                            continue; /* the for(z) */
                    }

                    /* If we get here, we ended a line */

                    if (col || z + 1 != lens[i])
                    {
                        /* Not at the end of the fragment: count in
                         * the indent from the new line.
                         */
                        j += indent;
                        col += indent;
                    }
                    else
                        maybe_at_end = MY_TRUE;

                    /* Guard against overflow */
                    if (j > MAX_STRING_LENGTH)
                    {
                        /* Reduce this part to fit; all the following
                         * parts will be reduced to shreds.
                         */
                        indent_overflows = MY_TRUE;
                        lens[i] -= (j - MAX_STRING_LENGTH);
                        j = MAX_STRING_LENGTH;
                        if (lens[i] < z)
                        {
                            /* must have been ok or we wouldn't be here */
                            lens[i] = z;
                            break;
                        }
                    }
                } /* for (z = 0..lens[i]) */
            } /* if (wrap) */
        }
        else
        {
            /* This replacement does not need to be wrapped. */
            indent_overflows = MY_FALSE;
            j += -lens[i];
            if (j > MAX_STRING_LENGTH)
            {
                /* Max length exceeded: shrink the working length
                 * to something usable. All following fragments
                 * will be shrunk to length 0.
                 */
                lens[i] = -(-(lens[i]) - (j - MAX_STRING_LENGTH));
                j = MAX_STRING_LENGTH;
            }
        } /* if (lens[i] > 0) */
    } /* for (i = 0..num) for wrapping analysis */


    /* Now we have the final string in parts and length in j.
     * let's compose the result, wrapping it where necessary.
     */
    memsafe(deststr = alloc_mstring((size_t)j), (size_t)j, "result string");

    cp = get_txt(deststr); /* destination pointer */

    if (wrap)
    {
        /* Catenate and wrap the parts together. This will look similar
         * to the length computation above.
         */

        int space_garbage = 0;
          /* Number of characters to be ignored since the last space,
           * most of them are control codes and other junk.
           */
        size_t tmpmem_size;
        char *tmpmem;
          /* Temporary buffer for the current line */
        char *pt;
          /* Pointer into tmpmem */

        tmpmem_size = (size_t)j+j_extra+1;
          /* Actually, the allocated '+j_extra' size is never used, but
           * it makes the sanity check below simpler.
           */
        xallocate(tmpmem, tmpmem_size, "temporary string");

        col = 0;
        start = -1;
        space = 0;
        pt = tmpmem;

        /* Loop over all parts */
        for (i = 0; i < num; i++)
        {
            int kind;            /* The kind of a line break */
            int len;             /* Actual length of the line */
            p_int l = lens[i];   /* Length of current part */
            char *p = parts[i];  /* Current part */

            if (pt - tmpmem + ((l < 0) ? -l : l) >= (ptrdiff_t)tmpmem_size)
            {
                errorf("Partial string '%s' too long (%td+%"PRIdPINT" >= %zu).\n"
                     , p
                     , (ptrdiff_t)(pt - tmpmem), ((l < 0) ? -l : l)
                     , tmpmem_size);
                /* NOTREACHED */
                return NULL;
            }

            if (l < 0)
            {
                /* String retrieved from the mapping: not to be counted */
                memcpy(pt, p, (size_t)-l);
                pt += -l;
                space_garbage += -l;
                continue;
            }

            /* Loop over the current part, copying and wrapping */
            for (k = 0; k < lens[i]; k++)
            {
                int n;
                char c = p[k];  /* Current character */

                /* Copy the character into tmpmem */
                *pt++ = c;

                if (c == '\n')
                {
                    /* Start a new line */
                    col = 0;
                    kind = 0;
                    start = -1;
                }
                else
                {
                    /* All space characters in columns before col <start>
                     * do not count.
                     */
                    if (col > start || c != ' ')
                        col++;
                    else
                        pt--;

                    /* If space, remember the position */
                    if (c == ' ')
                    {
                        space = col;
                        space_garbage = 0;
                    }

                    /* Wrapping necessary? */
                    if (col == wrap+1)
                    {
                        if (space)
                        {
                            /* Break at last space */
                            int next_word_len = 0;

                            if (col - space > 2)
                            {
                                /* Check if the current word is too
                                 * long to be put on one line. If it
                                 * is, don't bother breaking at the last
                                 * space.
                                 */
                                int test_k = k;
                                int test_i = i;
                                Bool done = MY_FALSE;

                                next_word_len = col - space;
                                for ( ; !done && test_i <  num; test_i++)
                                {
                                    if (lens[test_i] < 0)
                                        continue;
                                    for ( ; !done && test_k < lens[test_i]
                                          ; test_k++)
                                    {
                                        char testc = parts[test_i][test_k];
                                        if (testc == ' ' || testc == '\n')
                                        {
                                            done = MY_TRUE;
                                            break;
                                        }
                                        next_word_len++;
                                    }
                                    test_k = 0;
                                }
                            }

                            if (next_word_len + indent > wrap)
                            {
                                /* Word is too long: treat it as if there
                                 * is no space within range.
                                 */
                                space = 0;
                                col = 1;
                                kind = 2;
                            }
                            else
                            {
                                col -= space;
                                space = 0;
                                kind = 1;
                            }
                        }
                        else
                        {
                            /* No space within range: simply let this
                             * one extent over the wrap margin and
                             * restart counting.
                             */
                            col = 1;
                            kind = 2;
                        }

                        /* Reset the start column */
                        start = indent;
                    }
                    else
                        continue;
                } /* if (type of c) */

                /* If we get here, we ended a line, and kind tells us why:
                 *   kind == 0: hard line break
                 *           1: line wrapped at suitable space
                 *           2: line extended over the limit with no space
                 */

                len = (kind == 1 ? col + space_garbage : col);

                /* Determine the length of the _previous_ (and therefore
                 * wrapped) line and copy it from tmpmem into deststr.
                 */
                n = (pt - tmpmem) - len;
                memcpy(cp, tmpmem, (size_t)n);
                cp += n;

                if (kind == 1)
                {
                    /* replace the space with the newline */
                    cp[-1] = '\n';
                }
                if (kind == 2)
                {
                    /* need to insert a newline */
                    *cp++ = '\n';
                }

                /* Remove the previous line from tmpmem */
                move_memory(tmpmem, tmpmem + n, (size_t)len);
                pt = tmpmem + len;

                /* If we are indenting, check if we have to add the
                 * indentation space.
                 * Note: if kind == 2, it's the current character which
                 *   will go onto the next line, otherwise it's the next
                 *   character will. The difference is important in the
                 *   call to at_end().
                 */
                if (indent != 0
                 && (   len > space_garbage
                     || !at_end(i, num, (kind == 2) ? k-1 : k, lens))
                   )
                {
                    /* There will be data coming next: insert the
                     * indentation.
                     */
                    memset(cp, ' ', (size_t)indent);
                    cp += indent;
                    col += indent;
                }

                /* Since we're in a new line, all the 'garbage' is gone. */
                space_garbage = 0;
            } /* for(k = 0.. lens[i] */
        } /* for(i = 0..num) */

        /* Append the last fragment from the tmpmem to the result */
        memcpy(cp, tmpmem, (size_t)(pt - tmpmem));
        cp += pt - tmpmem;
        xfree(tmpmem);
    }
    else
    {
        /* No wrapping: just catenate the parts (and all lens[] entries
         * are positive here)
         */
        for (i = 0; i < num; i++)
        {
            memcpy(cp, parts[i], (size_t)lens[i]);
            cp += lens[i];
        }
    }

    if ( lens )
      xfree(lens);
    if ( parts )
      xfree(parts);
    if (savestr)
      free_mstring(savestr);
    while (num_tmp > 0)
    {
        free_svalue(inter_sp);
        inter_sp--;
        num_tmp--;
    }


    /* now we have what we want */
#ifdef DEBUG
    if ((long)(cp - get_txt(deststr)) != j
     && (!indent_overflows || (long)(cp - get_txt(deststr)) != wrap)
       ) {
      fatal("Length miscalculated in terminal_colour()\n"
            "    Expected: %i (or %i) Was: %td\n"
            "    In string: %.*s\n"
            "    Out string: %.*s\n"
            "    Indent: %i Wrap: %i, indent overflow: %s\n"
           , j, wrap
           , (ptrdiff_t)(cp - get_txt(deststr))
           , (int)mstrsize(text), get_txt(text)
           , (int)mstrsize(deststr), get_txt(deststr)
           , indent, wrap
           , indent_overflows ? "true" : "false"
           );
    }
#endif
    return deststr;

#undef CALLOCATE
#undef RESIZE
#undef NSTRSEGS
#undef TC_FIRST_CHAR
#undef TC_SECOND_CHAR
} /* e_terminal_colour() */

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

/* EFUN terminal_colour()
 *
 *   varargs string terminal_colour( string str, mapping|closure map,
 *                                   int wrap, int indent )
 *
 * Expands all colour-defines from the input-string and replaces them by the
 * apropriate values found for the color-key inside the given mapping. The
 * mapping has the format "KEY" : "value", non-string contents are ignored
 * with one exception: the entry (0 : value) is used for otherwise
 * unrecognized tags, if existing; <value> may be a string or a closure (see
 * below).
 *
 * If <map> is given as 0, no keyword detection or replacement will be
 * performed and the efun acts just as a text wrapper and indenter (assuming
 * that <wrap> and <indent> are given).
 *
 * If <map> is given as a closure, it is called for each KEY with the key
 * as argument, and it has to return the replacement string.
 *
 * The parameters wrap and indent are both optional, if only wrap is given
 * then the str will be linewrapped at the column given with wrap.  If indent
 * is given too, then all wrapped lines will be indented with the number of
 * blanks specified with indent.
 *
 * The wrapper itself ignores the length of the color macros and that what
 * they contain, it wraps the string based on the length of the other chars
 * inside. Therefor it is color-aware.
 *
 * This function is called from the evaluator and provided with the
 * proper arguments.
 *
 * Result is a pointer to the final string. If no changes were necessary,
 * this is <text> again; otherwise it is a pointer to memory allocated
 * by the function.
 */

{
    int        indent = 0;
    int        wrap = 0;
    string_t * str;
    mapping_t * map = NULL;
    svalue_t * cl = NULL;

    if ( num_arg >= 3 )
    {
        if ( num_arg == 4 )
        {
            indent = (sp--)->u.number;
            if (indent < 0)
            {
                errorf("terminal_colour() requires an indent >= 0.\n");
                /* NOTREACHED */
                return sp;
            }
        }
        wrap = (sp--)->u.number;
        if (wrap < 0)
        {
            errorf("terminal_colour() requires a wrap >= 0.\n");
            /* NOTREACHED */
            return sp;
        }
    }

    if (sp->type == T_MAPPING)
    {
        map = sp->u.map;
        if (map->num_values < 1)

        {
            errorf("terminal_colour() requires a mapping with values.\n");
            /* NOTREACHED */
            return sp;
        }
        cl = NULL;
    }
    else if (sp->type == T_CLOSURE)
    {
        map = NULL;
        cl = sp;
    }
    else
    {
        map = NULL;
        cl = NULL;
    }

    inter_sp = sp;

    str = e_terminal_colour(sp[-1].u.str, map, cl, indent, wrap);

    free_svalue(sp--);
    free_svalue(sp);
    put_string(sp, str);

    return sp;
} /* v_terminal_colour() */

#ifdef USE_PROCESS_STRING
/*-------------------------------------------------------------------------*/
static string_t *
process_value (const char *str, Bool original)

/* Helper function for process_string(): take a function call in <str>
 * in the form "function[:objectname]{|arg}" and try to call it.
 * If the function exists and returns a string, the result is an uncounted
 * pointer to the string (which itself is referenced by apply_return_value).
 * If the function can't be called, or does not return a string, the
 * result is NULL.
 */

{
    svalue_t *ret;     /* Return value from the function call */
    char     *func;    /* Copy of the <str> string for local modifications */
    string_t *func2;   /* Shared string with the function name from <func> */
    char     *obj;     /* NULL or points to the object part in <func> */
    char     *arg;     /* NULL or points to the first arg in <func> */
    char     *narg;    /* Next argument while pushing them */
    int       numargs; /* Number of arguments to the call */
    object_t *ob;

    /* Simple check if the argument is valid */
    if (strlen(str) < 1 || !isalpha((unsigned char)(str[0])))
        return NULL;

    /* If necessary, copy the argument so that we can separate the various
     * parts with \0 characters.
     */
    if (original)
    {
        /* allocate memory and push error handler */
        func = xalloc_with_error_handler(strlen(str)+1);
        if (!func)
            errorf("Out of memory (%zu bytes) in process_value().\n"
                 , strlen(str)+1);
        strcpy(func, str);
    }
    else
    {
        func = (char *)str;
    }

    /* Find the object and the argument part */
    arg = strchr(func,'|'); if (arg) { *arg='\0'; arg++; }
    obj = strchr(func,':'); if (obj) { *obj='\0'; obj++; }

    /* Check if the function exists at all. apply() will be delighted
     * over the shared string anyway.
     */
    if ( NULL == (func2 = find_tabled_str(func)) )
    {
        /* free the error handler if necessary. */
        if (original)
            free_svalue(inter_sp--);
        return NULL;
    }


    /* Get the object */
    if (!obj)
        ob = current_object;
    else
    {
        string_t *objstr;

        memsafe(objstr = new_mstring(obj), strlen(obj), "object name");
        ob = find_object(objstr);
        free_mstring(objstr);
    }

    if (!ob)
    {
        /* free the error handler if necessary. */
        if (original)
            free_svalue(inter_sp--);
        return NULL;
    }

    /* Push all arguments as strings to the stack
     */
    for (numargs = 0; arg; arg = narg)
    {
        narg = strchr(arg,'|');
        if (narg)
            *narg = '\0';
        push_c_string(inter_sp, arg);
        numargs++;
        if (narg)
        {
            *narg = '|';
            narg++;
        }
    }
    
    /* Apply the function */
    ret = apply(func2, ob, numargs);

    /* Free func by freeing the error handler (if we allocated func).
     * Has to be done now, after the arguments have been popped by apply().
     */
    if (original)
        free_svalue(inter_sp--);
    
    /* see if adequate answer is returned by the apply(). */
    if (ret && ret->type == T_STRING)
        return ret->u.str;
        /* The svalue is stored statically in apply_return_value */

    return NULL;
} /* process_value() */

/*-------------------------------------------------------------------------*/
svalue_t *
f_process_string(svalue_t *sp)

/* EFUN process_string()
 *
 *     string process_string(string str)
 *
 * Searches string str for occurences of a "value by function
 * call", which is @@ followed by an implicit function call. See
 * "value_by_function_call" in the principles section.
 *
 * The value should contain a string like this:
 * @@function[:filename][|arg|arg]@@
 *
 * function must return a string or else the string which should be
 * processed will be returned unchanged.
 *
 * Note that process_string() does not recurse over returned
 * replacement values. If a function returns another function
 * description, that description will not be replaced.
 *
 * Both filename and args are optional.
 */

{
    vector_t   *vec;           /* Arg string exploded by '@@' */
    object_t   *old_cur;       /* Old current object */
    wiz_list_t *old_eff_user;  /* Old euid */
    int         il;            /* Index in vec */
    Bool        changed;       /* True if there was a replacement */
    Bool        ch_last;       /* True if the last vec-entry was replaced */
    string_t *buf;             /* Result string(s) */
    string_t *str;             /* The argument string */

    str = sp->u.str;

    if (NULL == strchr(get_txt(str), '@'))
        return sp;  /* Nothing to do */

    old_eff_user = NULL;
    old_cur = current_object;

    if (!current_object)
    {
        /* This means we are called from notify_ in comm1
         * We must temporary set eff_user to backbone uid for
         * security reasons.
         */

        svalue_t *ret;

        current_object = command_giver;
        ret = apply_master(STR_GET_BB_UID,0);
        if (!ret)
            return sp;

        if (ret->type != T_STRING
         && (strict_euids || ret->type != T_NUMBER || ret->u.number))
            return sp;

        if (current_object->eff_user)
        {
            old_eff_user = current_object->eff_user;
            if (ret->type == T_STRING)
                current_object->eff_user = add_name(ret->u.str);
            else
                current_object->eff_user = NULL;
        }
    }

    /* Explode the argument by the '@@' */
    vec = explode_string(str, STR_ATAT);
    if (!vec)
        return sp;
    push_array(inter_sp, vec); /* automatic free in case of errors */

    for ( ch_last = MY_FALSE, changed = MY_FALSE, il = 1
        ; il < VEC_SIZE(vec)
        ; il++)
    {
        string_t *p0, *p2;

        p0 = vec->item[il].u.str;

        /* The entry might be a function call */
        p2 = process_value(get_txt(p0), MY_TRUE);
        if (p2)
        {
            /* Yup, it is: reference the result */
            p2 = ref_mstring(p2);
            ch_last = MY_TRUE;
            changed = MY_TRUE;
        }
        else
        {
            /* No replacement by function call */
            if (!ch_last)
            {
                /* ...but we have to recreate the '@@' from the original */
                memsafe(p2 = alloc_mstring(2+mstrsize(p0)), 2+mstrsize(p0)
                       , "intermediate result string");
                memcpy(get_txt(p2), "@@", 2);
                memcpy(get_txt(p2)+2, get_txt(p0), mstrsize(p0));
            }
            else
            {
                ch_last = MY_FALSE;
            }
        }

        /* If we have a replacement string, put it into place. */
        if (p2)
        {
            free_mstring(p0);
            vec->item[il].u.str = p2;
        }
    } /* for() */

    /* If there were changes, implode the vector again */
    if (changed)
        buf = implode_string(vec, STR_EMPTY);
    else
        buf = NULL;

    /* Clean up */
    inter_sp--;
    free_array(vec);

    if (old_eff_user)
    {
        current_object->eff_user = old_eff_user;
    }

    current_object = old_cur;

    /* Return the result */
    if (buf)
    {
        free_string_svalue(sp);
        put_string(sp, buf);
    }

    return sp;
} /* f_process_string() */

#endif /* USE_PROCESS_STRING */

/*-------------------------------------------------------------------------*/
/* Structures for sscanf() */

/* Flags for every argument whether to assign and/or count it
 */

struct sscanf_flags {
    int do_assign: 16;
    int count_match: 16;
};

/* Packet of information passed between the scan functions:
 */

struct sscanf_info
{
    svalue_t *arg_start;    /* first argument for the current %-spec */
    svalue_t *arg_current;  /* current argument to consider */
    svalue_t *arg_end;      /* the last argument */
    char          *fmt_end;
      /* After the match: the next character in the fmt-string to match.
       */
    char          *match_end;
      /* After the match: the next character in the in-string to match.
       * NULL for 'no match' or 'all matched'.
       */
    Bool           match_req;
      /* Before a match: TRUE if the subsequent chars need to match as well.
       */
    Bool           no_match;
      /* After a match: TRUE if there was a mismatch in the non-% match.
       */
    mp_uint        field;        /* Numbers: parsed fieldwidth */
    mp_uint        min;          /* Numbers: parsed precision */
    mp_uint        string_max;   /* Strings: parsed fieldwidth */
    mp_uint        string_min;   /* Strings: parsed 'precision' */
    struct sscanf_flags flags;
    int            sign;         /* -1 for '%-d', 0 for '%d', '%+d' or '%u' */
    mp_int         number_of_matches;  /* Number of matches so far */
};

/*-------------------------------------------------------------------------*/
static void
sscanf_decimal (char *str, struct sscanf_info *info)

/* Parse a number from <str> according the .field and .min given in <info>,
 * and, if successfull, store it in <info>->arg_current, which is then
 * incremented.
 *
 * <info>.match_end and .fmt_end are set properly on return.
 */

{
    static svalue_t tmp_svalue = { T_NUMBER };

    mp_int i, num;
    char c;

    num = 0;

    i = (mp_int)info->min;
    if (i > 0)
    {
        /* The number must have at least i digits */
        info->field -= i;
        do
        {
            if (!lexdigit(c = *str))
            {
                if (info->fmt_end[-1] != 'd')
                {
                    info->match_end = NULL;
                }
                else
                {
                    info->match_end = str;
                    info->fmt_end = "d"+1;
                }
                return;
            }
            str++;
            num = num * 10 + c - '0';
        } while (--i);
    }

    /* There can be info->field more digits */
    i = (mp_int)info->field;
    while  (--i >= 0)
    {
        if (!lexdigit(c = *str))
            break;
        str++;
        num = num * 10 + c - '0';
    }

    info->match_end = str;

    if (info->flags.do_assign)
    {
        /* Assign the parsed number */
        if (info->arg_current >= info->arg_end)
            return;

        tmp_svalue.u.number = (p_int)((num ^ info->sign) - info->sign);
        transfer_svalue((info->arg_current++)->u.lvalue, &tmp_svalue);
    }

    info->number_of_matches += info->flags.count_match;
    return;
}

/*-------------------------------------------------------------------------*/
static char *
sscanf_match_percent (char *str, char *fmt, struct sscanf_info *info)

/* Match a %-specification, called from sscanf_match().
 *
 * <fmt> points to the first character after the '%'.
 * <str> points to the first character to match.
 *
 * Return new value for <str> if matching is to be continued, else
 * return NULL and write in info->match_end the match end if a match was
 * found,  NULL otherwise.
 *
 * If a match was found, also write info->fmt_end with a pointer to the
 * conversion character, and info->flags, info->field, info->min.
 */

{
    char c;
    mp_uint *nump; /* Pointer to parsed fieldwidth resp. precision */

    /* Initialize field with a large value that will become
     * zero when doubled. Because 10 is divisible by 2, the multiply
     * will zero it. Note that it is negative before we decrement it
     * the first time.
     */
    *(nump = &info->field) = (((mp_uint)-1 / 2)) + 1;
    info->min = 1;
    info->flags.do_assign = 1;
    info->flags.count_match = 1;
    info->match_req = MY_FALSE;

    for (;;)
    {
        switch(c = *fmt++)
        {
        case '+':
            info->match_req = MY_TRUE;
            continue;

        case '!':
            info->flags.count_match ^= 1;
            info->flags.do_assign ^= 1;
            continue;

        case '~':
            info->flags.do_assign ^= 1;
            continue;

        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            *nump = *nump * 10 + c - '0';
            continue;

        case '*':
            if (info->arg_current >= info->arg_end
             || info->arg_current->u.lvalue->type != T_NUMBER)
            {
                info->match_end = NULL;
                return NULL;
            }
            *nump = (mp_uint)((info->arg_current++)->u.lvalue->u.number);
            continue;

        case '.':
            *(nump = &info->min) = 0;
            continue;

        case 'd':
            /* Skip leading whitespace */
            while(isspace((unsigned char)*str))
                str++;
            /* FALLTHROUGH */

        case 'D':
            /* Match a signed number */
            if (*str == '-')
            {
                info->s

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

Site Stats

Snippets: 1791
Codebases: 571