⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bget.c

📁 最新版IAR FOR ARM(EWARM)5.11中的代码例子
💻 C
📖 第 1 页 / 共 4 页
字号:

#define SizeQuant   4              /* Buffer allocation size quantum:
                     all buffers allocated are a
                     multiple of this size.  This
                     MUST be a power of two. */

#define BufDump     1              /* Define this symbol to enable the
                     bpoold() function which dumps the
                     buffers in a buffer pool. */
#undef BufDump

#define BufValid    1              /* Define this symbol to enable the
                     bpoolv() function for validating
                     a buffer pool. */
#undef BufValid

#define DumpData    1              /* Define this symbol to enable the
                     bufdump() function which allows
                     dumping the contents of an allocated
                     or free buffer. */
#undef DumpData

#define BufStats    1              /* Define this symbol to enable the
                     bstats() function which calculates
                     the total free space in the buffer
                     pool, the largest available
                     buffer, and the total space
                     currently allocated. */
#ifndef DEBUG
#undef BufStats
#endif

#define FreeWipe    1              /* Wipe free buffers to a guaranteed
                     pattern of garbage to trip up
                     miscreants who attempt to use
                     pointers into released buffers. */
#undef FreeWipe

#define BestFit     1              /* Use a best fit algorithm when
                     searching for space for an
                     allocation request.  This uses
                     memory more efficiently, but
                     allocation will be much slower. */

#define BECtl        1              /* Define this symbol to enable the
                     bectl() function for automatic
                     pool space control.  */
#undef BECtl

//#include <stdio.h>

#ifdef lint
#define NDEBUG                  /* Exits in asserts confuse lint */
/* LINTLIBRARY */                     /* Don't complain about def, no ref */
extern char *sprintf();               /* Sun includes don't define sprintf */
#endif

#include <string.h>

/* Replaced #include <assert.h> with this local definition. This prevents
 * calls to the C runtime from assert(). These had caused problems when
 * building using the IAR Embedded Workbench toolchain with semihosting
 * disabled.
 */
#ifdef DEBUG
extern void __error__(char *, unsigned long);
#define ASSERT(expr) {                                      \
                         if(!(expr))                        \
                         {                                  \
                             __error__(__FILE__, __LINE__); \
                         }                                  \
                     }
#else
#define ASSERT(expr)
#endif

#ifdef BufDump                  /* BufDump implies DumpData */
#ifndef DumpData
#define DumpData    1
#endif
#endif

#ifdef DumpData
#include <ctype.h>
#endif

/*  Declare the interface, including the requested buffer size type,
    bufsize.  */

#include "bget.h"

#define MemSize     int           /* Type for size arguments to memxxx()
                     functions such as memcmp(). */

/* Queue links */

struct qlinks {
    struct bfhead *flink;          /* Forward link */
    struct bfhead *blink;          /* Backward link */
};

/* Header in allocated and free buffers */

struct bhead {
    bufsize prevfree;              /* Relative link back to previous
                     free buffer in memory or 0 if
                     previous buffer is allocated.    */
    bufsize bsize;              /* Buffer size: positive if free,
                     negative if allocated. */
};
#define BH(p)    ((struct bhead *) (p))

/*  Header in directly allocated buffers (by acqfcn) */

struct bdhead {
    bufsize tsize;              /* Total size, including overhead */
    struct bhead bh;              /* Common header */
};
#define BDH(p)    ((struct bdhead *) (p))

/* Header in free buffers */

struct bfhead {
    struct bhead bh;              /* Common allocated/free header */
    struct qlinks ql;              /* Links on free list */
};
#define BFH(p)    ((struct bfhead *) (p))

static struct bfhead freelist = {     /* List of free buffers */
    {0, 0},
    {&freelist, &freelist}
};


#ifdef BufStats
static bufsize totalloc = 0;          /* Total space currently allocated */
static long numget = 0, numrel = 0;   /* Number of bget() and brel() calls */
#ifdef BECtl
static long numpblk = 0;          /* Number of pool blocks */
static long numpget = 0, numprel = 0; /* Number of block gets and rels */
static long numdget = 0, numdrel = 0; /* Number of direct gets and rels */
#endif /* BECtl */
#endif /* BufStats */

#ifdef BECtl

/* Automatic expansion block management functions */

static int (*compfcn) _((bufsize sizereq, int sequence)) = NULL;
static void *(*acqfcn) _((bufsize size)) = NULL;
static void (*relfcn) _((void *buf)) = NULL;

static bufsize exp_incr = 0;          /* Expansion block size */
static bufsize pool_len = 0;          /* 0: no bpool calls have been made
                     -1: not all pool blocks are
                         the same size
                     >0: (common) block size for all
                         bpool calls made so far
                      */
#endif

/*  Minimum allocation quantum: */

#define QLSize    (sizeof(struct qlinks))
#define SizeQ    ((SizeQuant > QLSize) ? SizeQuant : QLSize)

#define V   (void)              /* To denote unwanted returned values */

/* End sentinel: value placed in bsize field of dummy block delimiting
   end of pool block.  The most negative number which will  fit  in  a
   bufsize, defined in a way that the compiler will accept. */

#define ESent    ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2))

/*  BGET  --  Allocate a buffer.  */

void *bget(
  bufsize requested_size)
{
    bufsize size = requested_size;
    struct bfhead *b;
#ifdef BestFit
    struct bfhead *best;
#endif
    void *buf;
#ifdef BECtl
    int compactseq = 0;
#endif

    ASSERT(size > 0);

    if (size < SizeQ) {           /* Need at least room for the */
    size = SizeQ;              /*    queue links.  */
    }
#ifdef SizeQuant
#if SizeQuant > 1
    size = (size + (SizeQuant - 1)) & (~(SizeQuant - 1));
#endif
#endif

    size += sizeof(struct bhead);     /* Add overhead in allocated buffer
                     to size required. */

#ifdef BECtl
    /* If a compact function was provided in the call to bectl(), wrap
       a loop around the allocation process  to  allow    compaction  to
       intervene in case we don't find a suitable buffer in the chain. */

    while (1) {
#endif
    b = freelist.ql.flink;
#ifdef BestFit
    best = &freelist;
#endif


    /* Scan the free list searching for the first buffer big enough
       to hold the requested size buffer. */

#ifdef BestFit
    while (b != &freelist) {
        if (b->bh.bsize >= size) {
        if ((best == &freelist) || (b->bh.bsize < best->bh.bsize)) {
            best = b;
        }
        }
        b = b->ql.flink;          /* Link to next buffer */
    }
    b = best;
#endif /* BestFit */

    while (b != &freelist) {
        if ((bufsize) b->bh.bsize >= size) {

        /* Buffer  is big enough to satisfy  the request.  Allocate it
           to the caller.  We must decide whether the buffer is  large
           enough  to  split  into  the part given to the caller and a
           free buffer that remains on the free list, or  whether  the
           entire  buffer  should  be  removed    from the free list and
           given to the caller in its entirety.   We  only  split  the
           buffer if enough room remains for a header plus the minimum
           quantum of allocation. */

        if ((b->bh.bsize - size) > (SizeQ + (sizeof(struct bhead)))) {
            struct bhead *ba, *bn;

            ba = BH(((char *) b) + (b->bh.bsize - size));
            bn = BH(((char *) ba) + size);
            ASSERT(bn->prevfree == b->bh.bsize);
            /* Subtract size from length of free block. */
            b->bh.bsize -= size;
            /* Link allocated buffer to the previous free buffer. */
            ba->prevfree = b->bh.bsize;
            /* Plug negative size into user buffer. */
            ba->bsize = -(bufsize) size;
            /* Mark buffer after this one not preceded by free block. */
            bn->prevfree = 0;

#ifdef BufStats
            totalloc += size;
            numget++;          /* Increment number of bget() calls */
#endif
            buf = (void *) ((((char *) ba) + sizeof(struct bhead)));
            return buf;
        } else {
            struct bhead *ba;

            ba = BH(((char *) b) + b->bh.bsize);
            ASSERT(ba->prevfree == b->bh.bsize);

                    /* The buffer isn't big enough to split.  Give  the  whole
               shebang to the caller and remove it from the free list. */

            ASSERT(b->ql.blink->ql.flink == b);
            ASSERT(b->ql.flink->ql.blink == b);
            b->ql.blink->ql.flink = b->ql.flink;
            b->ql.flink->ql.blink = b->ql.blink;

#ifdef BufStats
            totalloc += b->bh.bsize;
            numget++;          /* Increment number of bget() calls */
#endif
            /* Negate size to mark buffer allocated. */
            b->bh.bsize = -(b->bh.bsize);

            /* Zero the back pointer in the next buffer in memory
               to indicate that this buffer is allocated. */
            ba->prevfree = 0;

            /* Give user buffer starting at queue links. */
            buf =  (void *) &(b->ql);
            return buf;
        }
        }
        b = b->ql.flink;          /* Link to next buffer */
    }
#ifdef BECtl

        /* We failed to find a buffer.  If there's a compact  function
       defined,  notify  it  of the size requested.  If it returns
       TRUE, try the allocation again. */

    if ((compfcn == NULL) || (!(*compfcn)(size, ++compactseq))) {
        break;
    }
    }

    /* No buffer available with requested size free. */

    /* Don't give up yet -- look in the reserve supply. */

    if (acqfcn != NULL) {
    if (size > exp_incr - sizeof(struct bhead)) {

        /* Request    is  too  large    to  fit in a single expansion
           block.  Try to satisy it by a direct buffer acquisition. */

        struct bdhead *bdh;

        size += sizeof(struct bdhead) - sizeof(struct bhead);
        if ((bdh = BDH((*acqfcn)((bufsize) size))) != NULL) {

        /*  Mark the buffer special by setting the size field
            of its header to zero.  */
        bdh->bh.bsize = 0;
        bdh->bh.prevfree = 0;
        bdh->tsize = size;
#ifdef BufStats
        totalloc += size;
        numget++;          /* Increment number of bget() calls */
        numdget++;          /* Direct bget() call count */
#endif
        buf =  (void *) (bdh + 1);
        return buf;
        }

    } else {

        /*    Try to obtain a new expansion block */

        void *newpool;

        if ((newpool = (*acqfcn)((bufsize) exp_incr)) != NULL) {
        bpool(newpool, exp_incr);
                buf =  bget(requested_size);  /* This can't, I say, can't
                         get into a loop. */
        return buf;
        }
    }
    }

    /*    Still no buffer available */

#endif /* BECtl */

    return NULL;
}

/*  BGETZ  --  Allocate a buffer and clear its contents to zero.  We clear
           the  entire  contents  of  the buffer to zero, not just the
           region requested by the caller. */

void *bgetz(
  bufsize size)
{
    char *buf = (char *) bget(size);

    if (buf != NULL) {
    struct bhead *b;
    bufsize rsize;

    b = BH(buf - sizeof(struct bhead));
    rsize = -(b->bsize);
    if (rsize == 0) {
        struct bdhead *bd;

        bd = BDH(buf - sizeof(struct bdhead));
        rsize = bd->tsize - sizeof(struct bdhead);
    } else {
        rsize -= sizeof(struct bhead);
    }
    ASSERT(rsize >= size);
    V memset(buf, 0, (MemSize) rsize);
    }
    return ((void *) buf);
}

/*  BGETR  --  Reallocate a buffer.  This is a minimal implementation,
           simply in terms of brel()  and  bget().     It  could  be
           enhanced to allow the buffer to grow into adjacent free
           blocks and to avoid moving data unnecessarily.  */

void *bgetr(
  void *buf,
  bufsize size)
{
    void *nbuf;
    bufsize osize;              /* Old size of buffer */
    struct bhead *b;

    if ((nbuf = bget(size)) == NULL) { /* Acquire new buffer */
    return NULL;
    }
    if (buf == NULL) {
    return nbuf;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -