Exemplo n.º 1
0
void* HeapAllocate(MemAllocHeap* heap, size_t size)
{
  bool thread_safe = 0 != (heap->m_Flags & HeapFlags::kThreadSafe);

  if (thread_safe)
  {
    MutexLock(&heap->m_Lock);
  }

  void* ptr = nullptr;
#if ENABLED(USE_DLMALLOC)
  ptr = mspace_malloc(heap->m_MemSpace, size);
#else
  ptr = malloc(size);
#endif
  if (!ptr)
  {
    Croak("out of memory allocating %d bytes", (int) size);
  }

  if (thread_safe)
  {
    MutexUnlock(&heap->m_Lock);
  }

  return ptr;
}
Exemplo n.º 2
0
/*! \brief Main function of the example memory manager.
 *
 *  This example shows how memory can be allocated from different
 *  memory spaces.
 *  The default allocation will get memory from the internal SRAM.
 *  By using the "memory space" functionality of the memory manager
 *  it is possible to use other memory spaces as resources like an
 *  attached SDRAM.
 */
int main(void)
{
    void *some_space;
    void *some_more_space;
    void *some_space_in_sdram;
    mspace sdram_msp;

    // Switch to external oscillator 0.
    pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);

    sdramc_init(FHSB_HZ);

    // default allocation from internal SRAM
    some_space = dlmalloc(512);
    some_more_space = dlmalloc(64);

    // Create a new memory space the covers the SDRAM
    sdram_msp = create_mspace_with_base((void*) SDRAM_START_ADDRESS, MEM_SPACE_SIZE, 0);

    // allocate memory from the created memroy space
    some_space_in_sdram = mspace_malloc(sdram_msp, 512);

    while (true)
    {
    }
}
Exemplo n.º 3
0
void* extmem_malloc(size_t bytes) {
	void *mem = NULL;
    extmem_init();
	mem = mspace_malloc(extmem_mspace, bytes);
	extmem_printk("[EXT_MEM] %s mem:%p, size: 0x%zx\n", __FUNCTION__, mem, bytes);
    return mem;
}
Exemplo n.º 4
0
void * NONNULL(1) MALLOC
mm_shared_space_alloc(struct mm_shared_space *space, size_t size)
{
    mm_common_lock(&space->lock);
    void *ptr = mspace_malloc(space->space.opaque, size);
    mm_common_unlock(&space->lock);
    return ptr;
}
Exemplo n.º 5
0
void* gm_malloc(size_t size) {
    assert(GM);
    assert(GM->mspace_ptr);
    futex_lock(&GM->lock);
    void* ptr = mspace_malloc(GM->mspace_ptr, size);
    futex_unlock(&GM->lock);
    if (!ptr) panic("gm_malloc(): Out of global heap memory, use a larger GM segment");
    return ptr;
}
Exemplo n.º 6
0
Assembly::Assembly(size_t size)
    : mCount(0), mSize(0)
{
    mBase = (uint32_t*)mspace_malloc(getMspace(), size);
    LOG_ALWAYS_FATAL_IF(mBase == NULL,
                        "Failed to create Assembly of size %zd in executable "
                        "store of size %zd", size, kMaxCodeCacheCapacity);
    mSize = size;
}
void *
Impl_malloc_zone_malloc(malloc_zone_t *zone, size_t size) {
	OSMemoryZone* osm = (OSMemoryZone*)zone;
	if (osm->global_zone) {
		return malloc(size);
	}
	else {
		return mspace_malloc(osm->memory_space, size);
	}
}
Exemplo n.º 8
0
void *
shmemi_mem_alloc (size_t size)
{
    void *addr = mspace_malloc (myspace, size);

#ifdef HAVE_FEATURE_DEBUG
    debug_alloc_add (addr, size);
#endif /* HAVE_FEATURE_DEBUG */

    return addr;
}
Exemplo n.º 9
0
static void*
malloc_starter(size_t sz, const void *caller)
{
  void* victim;

  /*ptmalloc_init_minimal();*/
  victim = mspace_malloc(arena_to_mspace(&main_arena), sz);
  THREAD_STAT(++main_arena.stat_starter);

  return victim;
}
Exemplo n.º 10
0
  void* malloc(size_t size){
    if(!everUsed){
	    initMutex.lock();
      if (!everUsed) {
        initTheSpaces();
        everUsed = true;
      }
      initMutex.unlock();
    }
    
    if ( mspaceId < 0 ) {
      mspaceId = (lastMspace+1) % N_MSPACES;

      initMutex.lock();
      lastMspace = mspaceId;
      initMutex.unlock();
      
      return mspace_malloc(mspaces[ mspaceId ], size);
    }
        
	return mspace_malloc(mspaces[ mspaceId ], size);
  }
Exemplo n.º 11
0
void * 
mempool_malloc(size_t size)
{
	void *	ptr = NULL;
	if (mp_mspace__)
	{
		KIRQL	irql;
		KeAcquireSpinLock(&mp_spinlock__, &irql);
		ptr = mspace_malloc(mp_mspace__, size);
		KeReleaseSpinLock(&mp_spinlock__, irql);
	}
	return ptr;
}
Exemplo n.º 12
0
void* hbw_malloc(size_t size)
{
    if (myhbwmalloc_mspace == NULL) {
        if (!myhbwmalloc_hardfail) {
            fprintf(stderr, "hbwmalloc: mspace invalid - allocating from default heap\n");
            return malloc(size);
        } else {
            fprintf(stderr, "hbwmalloc: mspace invalid - cannot allocate from hbw heap\n");
            abort();
        }
    }
    return mspace_malloc(myhbwmalloc_mspace, size);
}
Exemplo n.º 13
0
void *
qxl_alloc            (struct qxl_mem         *mem,
		      unsigned long           n_bytes)
{
    void *addr = mspace_malloc (mem->space, n_bytes);

#ifdef DEBUG_QXL_MEM
    VALGRIND_MALLOCLIKE_BLOCK(addr, n_bytes, 0, 0);
#ifdef DEBUG_QXL_MEM_VERBOSE
    fprintf(stderr, "alloc %p: %ld\n", addr, n_bytes);
#endif
#endif
    return addr;
}
Exemplo n.º 14
0
void* memory_malloc(size_t bytes)
{
    void* mem = NULL;
    int i = 0;

    if (!use_allocator)
    {
        memory_check_limits(bytes, 0);
        MALLOC_ALIGN(mem, bytes, CACHELINE_SIZE);
        return mem;
    }

    while (mem == NULL)
    {
        memory_t* memptr = &memory_table[i];
        /* First try to allocate in one of the existing chunks */
        if (memptr->in_use == 1)
            if ((mem = mspace_malloc(memptr->shm_mspace, bytes)) != NULL)
                break;

        /* Create a new chunck if already past the last valid chunk */
        if (i > memory_table_last)
        {
            memptr = memory_expand(bytes);
            if ((mem = mspace_malloc(memptr->shm_mspace, bytes)) != NULL)
                break;
            else
                ERROR("EPLIB malloc failed to allocate %ld bytes\n", bytes);
        }
        i++;
    }

    DEBUG_ASSERT(mem);
    MAKE_BOUNDS(mem, bytes);

    return mem;
}
Exemplo n.º 15
0
METHODPREFIX(CLASS, jobject, dlalloc)(ST_ARGS, jlong size, jint align)
{
	MYHEADID(JNISTRUCT, FID);
	void * ret=mspace_malloc(str->space, size);
	char * base=(char *)(str->base);
	if(ret<str->base || ret>=base+str->size)
	{
		// mspace is filled and implementation backed to stdc malloc
		// Our specification does not let this happen
		mspace_free(str->space, ret);
		JNU_ThrowByName(env, EXCCLASS_OUT, "Out of mspace area");
		return NULL;
	}
	memset ( ret, 0, size );
	return env->NewDirectByteBuffer(ret, size);
}
Exemplo n.º 16
0
static void*
malloc_atfork(size_t sz, const void *caller)
{
  void *vptr = NULL;

  tsd_getspecific(arena_key, vptr);
  if(vptr == ATFORK_ARENA_PTR) {
    /* We are the only thread that may allocate at all.  */
    return mspace_malloc(arena_to_mspace(&main_arena), sz);
  } else {
    /* Suspend the thread until the `atfork' handlers have completed.
       By that time, the hooks will have been reset as well, so that
       mALLOc() can be used again. */
    (void)mutex_lock(&list_lock);
    (void)mutex_unlock(&list_lock);
    return public_mALLOc(sz);
  }
}
Exemplo n.º 17
0
void*
public_mALLOc(size_t bytes)
{
  struct malloc_arena* ar_ptr;
  void *victim;

  void * (*hook) (size_t, const void *) = __malloc_hook;
  if (hook != NULL)
    return (*hook)(bytes, RETURN_ADDRESS (0));

  arena_get(ar_ptr, bytes + FOOTER_OVERHEAD);
  if (!ar_ptr)
    return 0;
  if (ar_ptr != &main_arena)
    bytes += FOOTER_OVERHEAD;
  victim = mspace_malloc(arena_to_mspace(ar_ptr), bytes);
  if (victim && ar_ptr != &main_arena)
    set_non_main_arena(victim, ar_ptr);
  (void)mutex_unlock(&ar_ptr->mutex);
  assert(!victim || is_mmapped(mem2chunk(victim)) ||
	 ar_ptr == arena_for_chunk(mem2chunk(victim)));
  return victim;
}
Exemplo n.º 18
0
void*	MemoryHeap::malloc(size_t size)
	{
	if (mMspace == NULL) 
		initialize();
	
	if (size >= mPageSize)
		{
		void* newAddr = mMMapFun(size);

		if (newAddr != MAP_FAILED)
			{
			mBytesUsed += size;
			mark_allocated(newAddr, size, true);
			return newAddr;
			}

		return 0;
		}

	void* newAddr = mspace_malloc(mMspace, size);
	if (newAddr != NULL)
		mBytesUsed += mspace_usable_size(newAddr);
	return newAddr;
	}
Exemplo n.º 19
0
void *sq_vm_malloc(SQUnsignedInteger size)
{
    return mspace_malloc(g_mspace, size);
}
Exemplo n.º 20
0
void* extmem_malloc(size_t bytes) {
    extmem_init();
    extmem_printk("[EXT_MEM] %s size: 0x%x\n", __FUNCTION__, bytes);
    return mspace_malloc(extmem_mspace, bytes);
}
Exemplo n.º 21
0
void * NONNULL(1) MALLOC
mm_private_space_alloc(struct mm_private_space *space, size_t size)
{
    return mspace_malloc(space->space.opaque, size);
}
Exemplo n.º 22
0
	void* PoolAllocator::Allocate(size_t size)
	{
		void* p = mspace_malloc(m_mspace, size);
		SI_ASSERT(p != nullptr);
		return p;
	}
Exemplo n.º 23
0
int main(void)
{
  size_t n, m;
  usCount start, end;
  size_t roundings[16];
  printf("N1527lib test program\n"
         "-=-=-=-=-=-=-=-=-=-=-\n");
  n=mpool_minimum_roundings(roundings, 16); assert(n<16);
  printf("Minimum roundings from available allocators:\n");
  for(m=0; m<n; m++)
  {
    printf("  %u\n", roundings[m]);
  }
  {
    mpool pool128, pool4096, poolA;
    void *temp1, *temp2;
    size_t usagecount, *alignments, *roundings;
    pool128=mpool_obtain(alignment128_attributes);
    temp1=mpool_malloc(pool128, 1);
    temp2=mpool_malloc(pool128, 1);
    printf("128 aligned %p (%u), %p (%u)", temp1, mpool_usable_size(pool128, temp1), temp2, mpool_usable_size(pool128, temp2));
    assert(!((size_t)temp1 & 127));
    assert(!((size_t)temp2 & 127));
    mpool_info(pool128, &usagecount, &alignments, &roundings, NULL);
    printf("  usagecount=%u, roundings[0]=%u\n", usagecount, roundings[0]);

    pool4096=mpool_obtain(alignment4096_attributes);
    temp1=mpool_malloc(pool4096, 1);
    temp2=mpool_malloc(pool4096, 1);
    printf("4096 aligned %p (%u), %p (%u)", temp1, mpool_usable_size(pool4096, temp1), temp2, mpool_usable_size(pool4096, temp2));
    assert(!((size_t)temp1 & 4095));
    assert(!((size_t)temp2 & 4095));
    mpool_info(pool4096, &usagecount, &alignments, &roundings, NULL);
    printf("  usagecount=%u, roundings[0]=%u\n", usagecount, roundings[0]);

    poolA=mpool_obtain(alignment128_attributes_a);
    mpool_info(poolA, &usagecount, &alignments, &roundings, NULL);
    printf("PoolA: usagecount=%u, roundings[0]=%u\n", usagecount, roundings[0]);
    assert(poolA==pool128);
  }

  syspool=mpool_obtain(MPOOL_DEFAULT);
  srand(1);
  for(n=0; n<RECORDS; n++)
    sizes[n]=rand() & 1023;
  if(1)
  {
    unsigned frees=0;
    printf("Fragmenting free space ...\n");
    start=GetUsCount();
    while(GetUsCount()-start<3000000000000)
    {
      n=rand() % RECORDS;
      if(ptrs[n]) { mpool_free(syspool, ptrs[n]); ptrs[n]=0; frees++; }
      else ptrs[n]=mpool_malloc(syspool, sizes[n]);
    }
    memset(ptrs, 0, RECORDS*sizeof(void *));
    printf("Did %u frees\n", frees);
  }

  if(0)
  {
    typedef void* mspace;
    extern mspace get_dlmalloc_mspace(mpool pool);
    extern void* mspace_malloc(mspace msp, size_t bytes);
    extern void mspace_free(mspace msp, void* mem);
    printf("\ndlmalloc Speed test\n"
             "-------------------\n");
    {
      mspace ms=get_dlmalloc_mspace(syspool);
      for(m=0; m<3; m++)
      {
        size_t count=RECORDS, size=1024;
        for(n=0; n<RECORDS; n++)
          sizes[n]=rand() & 1023;

        start=GetUsCount();
        for(n=0; n<RECORDS; n++)
        {
          ptrs[n]=mspace_malloc(ms, sizes[n]);
        }
        end=GetUsCount();
        printf("mspace_malloc() does %f mallocs/sec\n", RECORDS/((end-start)/1000000000000.0));

        start=GetUsCount();
        for(n=0; n<RECORDS; n++)
        {
          mspace_free(ms, ptrs[n]);
          ptrs[n]=0;
        }
        end=GetUsCount();
        printf("mspace_free() does %f frees/sec\n\n", RECORDS/((end-start)/1000000000000.0));
      }
    }
  }
  if(1)
  {
    printf("\nMPool Speed test\n"
             "----------------\n");
    for(m=0; m<3; m++)
    {
      size_t count=RECORDS, size=1024;
      for(n=0; n<RECORDS; n++)
        sizes[n]=rand() & 1023;

      start=GetUsCount();
      mpool_batch(syspool, NULL, ptrs, sizes, &count, 0);
      end=GetUsCount();
      printf("mpool_batch() does %f mallocs/sec\n", RECORDS/((end-start)/1000000000000.0));

      count=RECORDS;
      start=GetUsCount();
      mpool_batch(syspool, NULL, ptrs, NULL, &count, 0);
      end=GetUsCount();
      printf("mpool_batch() does %f frees/sec\n", RECORDS/((end-start)/1000000000000.0));

      start=GetUsCount();
      for(n=0; n<RECORDS; n++)
      {
        ptrs[n]=mpool_malloc(syspool, sizes[n]);
      }
      end=GetUsCount();
      printf("mpool_malloc() does %f mallocs/sec\n", RECORDS/((end-start)/1000000000000.0));

      start=GetUsCount();
      for(n=0; n<RECORDS; n++)
      {
        mpool_free(syspool, ptrs[n]);
        ptrs[n]=0;
      }
      end=GetUsCount();
      printf("mpool_free() does %f frees/sec\n\n", RECORDS/((end-start)/1000000000000.0));
    }
  }
#ifdef _MSC_VER
  printf("Press Return to exit ...\n");
  getchar();
#endif
  return 0;
}
Exemplo n.º 24
0
void* malloc(size_t bytes) {
    if(unlikely(sm_mspace == NULL)) __sm_init();

    return mspace_malloc(sm_mspace, bytes);
}
Exemplo n.º 25
0
void panel_article_list(struct env_t *_SERVER)
{
	tpl_t  *tpl;
	char   url[128];
	char   *html, *sql;
	int    rc, i, type, total;
	

	uint limit[2], cur;
	sqlite3_stmt   *stmt;
	const char     *sortlevel, *page;
	
	
	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/panel/article_list.html") != TPL_OK)
    {
		printf("Content-type: text/html\r\n\r\n./templets/panel/article_list.html Error loading template file!");
		tpl_free(tpl);
		return ;
    }

	total     = 0;
	sortlevel = tclistval2(_SERVER->_GET, 3);
	page      = tclistval2(_SERVER->_GET, 4);

	memset(&url, 0, sizeof(url));
	if((sortlevel) && (strcmp(sortlevel, "all") == 0))
	{
		strcpy(url, "/panel-article-list-all");
		rc   = sqlite3_prepare(db, "SELECT COUNT(*) AS c FROM article;", -1, &stmt, NULL);
	}
	else if((sortlevel) && (is_alpha(sortlevel)) && (strcmp(sortlevel, "html") != 0))
	{
		rc   = sqlite3_prepare(db, "SELECT COUNT(*) AS c FROM article WHERE catid = ?;", -1, &stmt, NULL);
		sqlite3_bind_text(stmt, 1, sortlevel, -1, SQLITE_STATIC);
		
		snprintf(url, sizeof(url), "/panel-article-list-%s", sortlevel);
	}
	else
	{
		strcpy(url, "/panel-article-list-all");
		rc   = sqlite3_prepare(db, "SELECT COUNT(*) AS c FROM article;", -1, &stmt, NULL);
	}

	rc = sqlite3_step(stmt);
	if(rc == SQLITE_ROW)
	{
		total = sqlite3_column_int(stmt, 0);
	}
	sqlite3_finalize(stmt);
	
	
	cur = (page) ? atoi(page) : 1;

	//分页
	pager(tpl, total, conf.page.admin, cur, url, limit);

	tpl_set_field_int_global(tpl, "total", total);

	if((sortlevel) && (strcmp(sortlevel, "all") == 0))
	{
		rc = sqlite3_prepare(db, "SELECT art.comment_num, art.hit, art.art_id, art.title, art.content, datetime(art.post_time, 'unixepoch') AS dt, cat.sortname, cat.sortdir FROM article AS art LEFT JOIN category AS cat ON cat.sortdir = art.catid ORDER BY art.art_id DESC LIMIT ?, ?;", -1, &stmt, NULL);
		
		sqlite3_bind_int(stmt, 1, limit[0]);
		sqlite3_bind_int(stmt, 2, limit[1]);
	}
	else if((sortlevel) && (is_alpha(sortlevel)) && (strcmp(sortlevel, "html") != 0))
	{
		rc = sqlite3_prepare(db, "SELECT art.comment_num, art.hit, art.art_id, art.title, art.content, datetime(art.post_time, 'unixepoch') AS dt, cat.sortname, cat.sortdir FROM article AS art LEFT JOIN category AS cat ON cat.sortdir = art.catid WHERE art.catid = ? ORDER BY art.art_id DESC LIMIT ?, ?;", -1, &stmt, NULL);
		
		sqlite3_bind_text(stmt, 1, sortlevel, -1, SQLITE_STATIC);
		sqlite3_bind_int(stmt,  2, limit[0]);
		sqlite3_bind_int(stmt,  3, limit[1]);
	}
	else
	{
		rc = sqlite3_prepare(db, "SELECT art.comment_num, art.hit, art.art_id, art.title, art.content, datetime(art.post_time, 'unixepoch') AS dt, cat.sortname, cat.sortdir FROM article AS art LEFT JOIN category AS cat ON cat.sortdir = art.catid ORDER BY art.art_id DESC LIMIT ?, ?;", -1, &stmt, NULL);
		
		sqlite3_bind_int(stmt, 1, limit[0]);
		sqlite3_bind_int(stmt, 2, limit[1]);
	}
	
	
	
	tpl_select_section(tpl, "data");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			type = sqlite3_column_type(stmt, i);
			switch(type)
			{
				case SQLITE_INTEGER:
					tpl_set_field_uint(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i));
					break;
				case SQLITE_TEXT:
					tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
					break;
			}
		}
		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);
	

	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);
	
	printf("Content-type: text/html\r\n\r\n%s", html);

	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
	
}
Exemplo n.º 26
0
void panel_article_insert(struct env_t *_SERVER)
{
	time_t       visit;
	tpl_t        *tpl;
	TCLIST       *arr;
	char         *html, path[128], buf[128];
	
	sqlite3_int64   id;
	sqlite3_stmt    *stmt;
	int             rc, i, pos, n, len;
	const char      *title, *sortlevel, *content, *recommend, *keyword, *filename, *file;

	if(tcmapget2(_SERVER->_POST, "Article_Insert"))
	{
		visit     = time((time_t*)0);
		file      = tcmapget2(_SERVER->_COOKIE, "file");
		title     = tcmapget2(_SERVER->_POST,   "title");
		content   = tcmapget2(_SERVER->_POST,   "content");
		keyword   = tcmapget2(_SERVER->_POST,   "keyword");
		filename  = tcmapget2(_SERVER->_POST,   "filename");
		sortlevel = tcmapget2(_SERVER->_POST,   "sortlevel");
		recommend = tcmapget2(_SERVER->_POST,   "recommend");
		
		pos = strpos(content, "<!-- idx -->");
		pos = (pos == -1) ? strlen(content) : pos;
		rc  = sqlite3_prepare(db, "INSERT INTO article(title, content, catid, keyword, filename, recommend, post_time, position, hit, comment_num) VALUES(?, ?, ?, ?, ?, ?, ?, ?, 0, 0);", -1, &stmt, NULL); 
		
		sqlite3_bind_text(stmt, 1, title,     -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 2, content,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 3, sortlevel, -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 4, keyword,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 5, filename,  -1, SQLITE_STATIC);

		sqlite3_bind_int(stmt, 6, atoi(recommend));
		sqlite3_bind_int(stmt, 7, visit);
		sqlite3_bind_int(stmt, 8, pos);

		
		sqlite3_step(stmt); 
		sqlite3_finalize(stmt); 
		
		id = sqlite3_last_insert_rowid(db);
				
		if(file)
		{
			memset(buf,  0, sizeof(buf));
			memset(path, 0, sizeof(path));
			
			strftime(buf, sizeof(buf), "%Y/%m/%d", localtime(&visit));

			//如果有上传的文件,就把上传的文件,从临时目录移动目标目录
			len = snprintf(path, sizeof(path), "./attachment/%s/%llu/", buf, id);
			
			if(!is_dir(path)) mkpath(_SERVER->mp, path, 0777);
			if(!strchr(file, '|'))
			{
				memset(buf,  0, sizeof(buf));
				snprintf(buf, sizeof(buf), "./files/%s", file);
				strcat(path, file);
				
			//	log_debug("panel_article_insert buf = %s\tpath = %s\r\n", buf, path);
				if(file_exists(buf)) rename(buf, path);
			}
			else
			{
				arr = explode("|", (char *)file);
				n   = tclistnum(arr);
				for(i=0; i<n; i++)
				{
					memset(buf,  0, sizeof(buf));
					filename = tclistval2(arr, i);
					snprintf(buf, sizeof(buf), "./files/%s", filename);

					path[len] = '\0';
					strcat(path, filename);

		//			log_debug("panel_article_insert explode buf = %s\tpath = %s\r\n", buf, path);

					if(file_exists(buf)) rename(buf, path);
				}
				tclistdel(arr);
			}
			
			path[len] = '\0';
			

			//更新图片附件的 路径
			rc = sqlite3_prepare(db, "UPDATE article SET content = replace(content, '/files/', ?) WHERE art_id = ?;", -1, &stmt, NULL);
			
			sqlite3_bind_text(stmt,  1, path+1, -1, SQLITE_STATIC);
			sqlite3_bind_int64(stmt, 2, id);
			sqlite3_step(stmt); 
			sqlite3_finalize(stmt); 
			
		}
		

#ifdef _BUILD_HTML
		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/list/%s", sortlevel);
		ftw(path, fn, 500);
#endif
		make_article_index(_SERVER);
		printf("Content-type: text/html\r\n\r\n<script>alert('添加成功!');window.location.href='/panel-article-list-%s.html';</script>", sortlevel);

		return ;
	}
	

	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/panel/article_insert.html") != TPL_OK)
    {
		puts("Content-type: text/html\r\n\r\n./templets/panel/article_insert.html Error loading template file!");
        tpl_free(tpl);
		return ;
    }

	rc = sqlite3_prepare(db, "SELECT sortname, sortdir FROM category", -1, &stmt, NULL);
	
	tpl_select_section(tpl, "classic");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
		}

		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);


	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);

	printf("Content-type: text/html\r\n\r\n%s", html);
	
	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
}
Exemplo n.º 27
0
void make_article_index(struct env_t *_SERVER)
{
	uint  total;
	tpl_t *tpl;
	char  *html;
	FILE   *fp;

	int  rc, i, type;
	uint limit[2];
	sqlite3_stmt *stmt;

	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/blog/article_list.html") != TPL_OK)
    {
		puts("Content-type: text/html\r\n\r\n./templets/blog/article_list.html Error loading template file!");
		tpl_free(tpl);
		return ;
    }
	
	//获取总数据集大小
	total = dataset_count("SELECT COUNT(*) AS c FROM article");
	
	tpl_set_field_int_global(tpl, "total", total);
	//分页
	pager(tpl, total, conf.page.blog, 1, "/article-list-all", limit);

	//获取分类数据
	assign_tpl_category(tpl);
	//加载推荐数据
	assign_tpl_recommend(tpl);

	//加载友情链接
	assign_tpl_friendlink(tpl);
	rc = sqlite3_prepare(db, "SELECT art.filename, art.comment_num, art.hit, art.art_id, art.title,  substring(art.content, art.position) AS c, datetime(art.post_time, 'unixepoch') AS dt, cat.sortname, cat.sortdir FROM article AS art LEFT JOIN category AS cat ON cat.sortdir = art.catid ORDER BY art.art_id DESC LIMIT ?;", -1, &stmt, NULL);
		
	sqlite3_bind_int(stmt, 1, conf.page.blog);


	tpl_select_section(tpl, "data");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			type = sqlite3_column_type(stmt, i);
			switch(type)
			{
				case SQLITE_INTEGER:
					tpl_set_field_uint(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i));
					break;
				case SQLITE_TEXT:
					tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
					break;
			}
		}

		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);

	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);
	
	//printf("Content-type: text/html\r\n\r\n%s", html);
	
	fp = fopen("./index.htm", "wb");
	if(fp)
	{
		fwrite(html, sizeof(char), tpl_length(tpl), fp);
		fclose(fp);
	}
	
	chmod("./index.htm", S_IRWXU | S_IRWXG | S_IRWXO);
	
	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
}
Exemplo n.º 28
0
void panel_article_update(struct env_t *_SERVER)
{
	tpl_t        *tpl;
	TCLIST       *arr;
	char         *html, path[128], buf[128];

	sqlite3_stmt *stmt;
	time_t       visit;
	int          rc, i, type, pos, len, n;
	const char   *id, *title, *sortlevel, *content, *recommend, *keyword, *filename, *file, *post_time;


	if(tcmapget2(_SERVER->_POST, "Article_Update"))
	{
		file      = tcmapget2(_SERVER->_COOKIE, "file");
		id        = tcmapget2(_SERVER->_POST, "id");
		title     = tcmapget2(_SERVER->_POST, "title");
		content   = tcmapget2(_SERVER->_POST, "content");
		keyword   = tcmapget2(_SERVER->_POST, "keyword");
		filename  = tcmapget2(_SERVER->_POST, "filename");
		sortlevel = tcmapget2(_SERVER->_POST, "sortlevel");
		recommend = tcmapget2(_SERVER->_POST, "recommend");
		post_time = tcmapget2(_SERVER->_POST, "post_time");

		pos = strpos(content, "<!-- idx -->");
		pos = (pos == -1) ? strlen(content) : pos;
		rc = sqlite3_prepare(db, "UPDATE article SET title = ?, content = ?, catid = ?, keyword = ?, filename = ?, recommend = ?, position = ? WHERE art_id = ?;", -1, &stmt, NULL); 
		
		sqlite3_bind_text(stmt, 1, title,     -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 2, content,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 3, sortlevel, -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 4, keyword,   -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 5, filename,  -1, SQLITE_STATIC);

		sqlite3_bind_int(stmt, 6, atoi(recommend));
		sqlite3_bind_int(stmt, 7, pos);
		sqlite3_bind_int(stmt, 8, atoi(id));
		

		sqlite3_step(stmt); 
		sqlite3_finalize(stmt); 

		visit = atoi(post_time);

		if(file)
		{
			memset(buf,  0, sizeof(buf));
			memset(path, 0, sizeof(path));
			
			strftime(buf, sizeof(buf), "%Y/%m/%d", localtime(&visit));

			//如果有上传的文件,就把上传的文件,从临时目录移动目标目录
			len = snprintf(path, sizeof(path), "./attachment/%s/%llu/", buf, (long long unsigned int)id);
			
			if(!is_dir(path)) mkpath(_SERVER->mp, path, 0777);
			if(!strchr(file, '|'))
			{
				memset(buf,  0, sizeof(buf));
				snprintf(buf, sizeof(buf), "./files/%s", file);
				strcat(path, file);
				
			//	log_debug("panel_article_insert buf = %s\tpath = %s\r\n", buf, path);
				if(file_exists(buf)) rename(buf, path);
			}
			else
			{
				arr = explode("|", (char *)file);
				n   = tclistnum(arr);
				for(i=0; i<n; i++)
				{
					memset(buf,  0, sizeof(buf));
					filename = tclistval2(arr, i);
					snprintf(buf, sizeof(buf), "./files/%s", filename);

					path[len] = '\0';
					strcat(path, filename);

		//			log_debug("panel_article_insert explode buf = %s\tpath = %s\r\n", buf, path);

					if(file_exists(buf)) rename(buf, path);
				}
				tclistdel(arr);
			}
			
			path[len] = '\0';
			

			//更新图片附件的 路径
			rc = sqlite3_prepare(db, "UPDATE article SET content = replace(content, '/files/', ?) WHERE art_id = ?;", -1, &stmt, NULL);
			
			sqlite3_bind_text(stmt, 1, path+1,   -1, SQLITE_STATIC);
			sqlite3_bind_int(stmt, 2, atoi(id));
			sqlite3_step(stmt); 
			sqlite3_finalize(stmt); 
			
		}

#ifdef _BUILD_HTML
		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/article/%s/%s.htm", sortlevel, id);
		if(file_exists(path))
			remove(path);

		memset(path, 0, sizeof(path));
		snprintf(path, sizeof(path), "./html/list/%s", sortlevel);
		ftw(path, fn, 500);
#endif
		printf("Content-type: text/html\r\n\r\n<script>alert('编辑成功!');window.location.href='/panel-article-list-%s.html';</script>", sortlevel);

		return ;
	}
	
	id = tclistval2(_SERVER->_GET, 3);
	if(id == NULL || !is_digit(id))
	{
		puts("Content-type: text/html\r\n\r\n<script>alert('请您选择要更新的文章');window.location.href='/panel-article-list-all.html';</script>");
		return ;
	}

	tpl = tpl_alloc();
	if (tpl_load(tpl, "./templets/panel/article_update.html") != TPL_OK)
    {
		printf("Content-type: text/html\r\n\r\n./templets/panel/article_update.html Error loading template file!");
        tpl_free(tpl);
		return ;
    }
	
	//加载分类的数据
	rc = sqlite3_prepare(db, "SELECT sortname, sortdir FROM category", -1, &stmt, NULL);
	
	tpl_select_section(tpl, "classic");
	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			tpl_set_field(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
		}
		tpl_append_section(tpl);
	}

	tpl_deselect_section(tpl);
	sqlite3_finalize(stmt);
	
	//加载需要编辑的数据
	rc = sqlite3_prepare(db, "SELECT * FROM article WHERE art_id = ?", -1, &stmt, NULL);
	sqlite3_bind_int(stmt, 1, atoi(id));

	while((rc = sqlite3_step(stmt)) == SQLITE_ROW)
	{
		for(i=0; i<sqlite3_column_count(stmt); i++)
		{
			type = sqlite3_column_type(stmt, i);
			switch(type)
			{
				case SQLITE_INTEGER:
					tpl_set_field_uint_global(tpl, sqlite3_column_name(stmt,i), sqlite3_column_int(stmt, i));
					break;
				case SQLITE_TEXT:
					tpl_set_field_global(tpl, sqlite3_column_name(stmt,i) ,sqlite3_column_text(stmt,i), strlen(sqlite3_column_text(stmt,i)));
					break;
			}
		}
	}

	sqlite3_finalize(stmt);


	html = mspace_malloc(_SERVER->mp, tpl_length(tpl) + 1);
    tpl_get_content(tpl, html);

	printf("Content-type: text/html\r\n\r\n%s", html);
	
	tpl_free(tpl);
	mspace_free(_SERVER->mp, html);
	
	tpl  = NULL;
}
Exemplo n.º 29
0
/*
 * Allocates <n> bytes of zeroed data.
 */
void* dvmHeapSourceAlloc(size_t n)
{
    HS_BOILERPLATE();

    HeapSource *hs = gHs;
    Heap* heap = hs2heap(hs);
    if (heap->bytesAllocated + n > hs->softLimit) {
        /*
         * This allocation would push us over the soft limit; act as
         * if the heap is full.
         */
        LOGV_HEAP("softLimit of %zd.%03zdMB hit for %zd-byte allocation",
                  FRACTIONAL_MB(hs->softLimit), n);
        return NULL;
    }
    void* ptr;
    if (gDvm.lowMemoryMode) {
        /* This is only necessary because mspace_calloc always memsets the
         * allocated memory to 0. This is bad for memory usage since it leads
         * to dirty zero pages. If low memory mode is enabled, we use
         * mspace_malloc which doesn't memset the allocated memory and madvise
         * the page aligned region back to the kernel.
         */
        ptr = mspace_malloc(heap->msp, n);
        if (ptr == NULL) {
            return NULL;
        }
        uintptr_t zero_begin = (uintptr_t)ptr;
        uintptr_t zero_end = (uintptr_t)ptr + n;
        /* Calculate the page aligned region.
         */
        uintptr_t begin = ALIGN_UP_TO_PAGE_SIZE(zero_begin);
        uintptr_t end = zero_end & ~(uintptr_t)(SYSTEM_PAGE_SIZE - 1);
        /* If our allocation spans more than one page, we attempt to madvise.
         */
        if (begin < end) {
            /* madvise the page aligned region to kernel.
             */
            madvise((void*)begin, end - begin, MADV_DONTNEED);
            /* Zero the region after the page aligned region.
             */
            memset((void*)end, 0, zero_end - end);
            /* Zero out the region before the page aligned region.
             */
            zero_end = begin;
        }
        memset((void*)zero_begin, 0, zero_end - zero_begin);
    } else {
        ptr = mspace_calloc(heap->msp, 1, n);
        if (ptr == NULL) {
            return NULL;
        }
    }

    countAllocation(heap, ptr);
    /*
     * Check to see if a concurrent GC should be initiated.
     */
    if (gDvm.gcHeap->gcRunning || !hs->hasGcThread) {
        /*
         * The garbage collector thread is already running or has yet
         * to be started.  Do nothing.
         */
        return ptr;
    }
    if (heap->bytesAllocated > heap->concurrentStartBytes) {
        /*
         * We have exceeded the allocation threshold.  Wake up the
         * garbage collector.
         */
        dvmSignalCond(&gHs->gcThreadCond);
    }
    return ptr;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	size_t size1 = 255;
	void *addr1 = NULL;
	size_t size2 = 256;
	void *addr2 = NULL;
	size_t size3 = kMaxCodeCacheCapacity - 512;
	void *addr3 = NULL;
		
	gExecutableStore = malloc(kMaxCodeCacheCapacity);
	if (gExecutableStore == NULL) {
		printf("error malloc\n");
		return -1;
	}
    gMspace = create_mspace_with_base(gExecutableStore, kMaxCodeCacheCapacity,
              /*locked=*/ true);
    
    printf("-> create mspace\n");
    mspace_malloc_stats(gMspace);
              
	addr1 = mspace_malloc(gMspace, size1);
	if (addr1 != NULL) {
		printf("-> malloc addr1 = %p, 0x%x\n", addr1, (uint32_t)size1);
		mspace_malloc_stats(gMspace);
		printf("addr1 size = 0x%x\n", (uint32_t)mspace_usable_size(addr1));
	}					
	
	addr2 = mspace_malloc(gMspace, size2);
	if (addr2 != NULL) {
		printf("-> malloc addr2 = %p, 0x%x\n", addr2, (uint32_t)size2);
		mspace_malloc_stats(gMspace);
		printf("addr2 size = 0x%x\n", (uint32_t)mspace_usable_size(addr2));
	}	
				
	addr3 = mspace_malloc(gMspace, size3);
	if (addr3 != NULL) {
		printf("-> malloc addr3 = %p, 0x%x\n", addr3, (uint32_t)size3);
		mspace_malloc_stats(gMspace);
		printf("addr3 size = 0x%x\n", (uint32_t)mspace_usable_size(addr3));
	} else {
		printf("malloc addr3 error!\n");
	}			

	if (addr1 != NULL) {
		mspace_free(gMspace, addr1);
	}
	
	if (addr2 != NULL) {
		mspace_free(gMspace, addr2);
	}				

	if (addr3 != NULL) {
		mspace_free(gMspace, addr3);
	}				
	
	printf("-> all free\n");
	mspace_malloc_stats(gMspace);
              
_exit:
	if (gMspace != NULL) {
		destroy_mspace(gMspace);
		gMspace = NULL;
	}
	
	if (gExecutableStore != NULL) {
		free(gExecutableStore);
		gExecutableStore = NULL;
	}			
	
	return 0;
}