Ejemplo n.º 1
0
void CommandStats::DoStats(char statschar, User* user, string_list &results)
{
	bool isPublic = ServerInstance->Config->UserStats.find(statschar) != std::string::npos;
	bool isRemoteOper = IS_REMOTE(user) && (user->IsOper());
	bool isLocalOperWithPrivs = IS_LOCAL(user) && user->HasPrivPermission("servers/auspex");

	if (!isPublic && !isRemoteOper && !isLocalOperWithPrivs)
	{
		ServerInstance->SNO->WriteToSnoMask('t',
				"%s '%c' denied for %s (%s@%s)",
				(IS_LOCAL(user) ? "Stats" : "Remote stats"),
				statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
		results.push_back("481 " + user->nick + " :Permission Denied - STATS " + statschar + " requires the servers/auspex priv.");
		return;
	}

	ModResult MOD_RESULT;
	FIRST_MOD_RESULT(OnStats, MOD_RESULT, (statschar, user, results));
	if (MOD_RESULT == MOD_RES_DENY)
	{
		results.push_back("219 "+user->nick+" "+statschar+" :End of /STATS report");
		ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
			(IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
		return;
	}

	switch (statschar)
	{
		/* stats p (show listening ports) */
		case 'p':
		{
			for (std::vector<ListenSocket*>::const_iterator i = ServerInstance->ports.begin(); i != ServerInstance->ports.end(); ++i)
			{
				ListenSocket* ls = *i;
				std::string ip = ls->bind_addr;
				if (ip.empty())
					ip.assign("*");
				std::string type = ls->bind_tag->getString("type", "clients");
				std::string hook = ls->bind_tag->getString("ssl", "plaintext");

				results.push_back("249 "+user->nick+" :"+ ip + ":"+ConvToStr(ls->bind_port)+
					" (" + type + ", " + hook + ")");
			}
		}
		break;

		/* These stats symbols must be handled by a linking module */
		case 'n':
		case 'c':
		break;

		case 'i':
		{
			for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
			{
				ConnectClass* c = *i;
				std::stringstream res;
				res << "215 " << user->nick << " I " << c->name << ' ';
				if (c->type == CC_ALLOW)
					res << '+';
				if (c->type == CC_DENY)
					res << '-';

				if (c->type == CC_NAMED)
					res << '*';
				else
					res << c->host;

				res << ' ' << c->config->getString("port", "*") << ' ';

				res << c->GetRecvqMax() << ' ' << c->GetSendqSoftMax() << ' ' << c->GetSendqHardMax()
					<< ' ' << c->GetCommandRate() << ' ' << c->GetPenaltyThreshold();
				if (c->fakelag)
					res << '*';
				results.push_back(res.str());
			}
		}
		break;

		case 'Y':
		{
			int idx = 0;
			for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
			{
				ConnectClass* c = *i;
				results.push_back("215 "+user->nick+" i NOMATCH * "+c->GetHost()+" "+ConvToStr(c->limit ? c->limit : SocketEngine::GetMaxFds())+" "+ConvToStr(idx)+" "+ServerInstance->Config->ServerName+" *");
				results.push_back("218 "+user->nick+" Y "+ConvToStr(idx)+" "+ConvToStr(c->GetPingTime())+" 0 "+ConvToStr(c->GetSendqHardMax())+" :"+
						ConvToStr(c->GetRecvqMax())+" "+ConvToStr(c->GetRegTimeout()));
				idx++;
			}
		}
		break;

		case 'P':
		{
			unsigned int idx = 0;
			const UserManager::OperList& opers = ServerInstance->Users->all_opers;
			for (UserManager::OperList::const_iterator i = opers.begin(); i != opers.end(); ++i)
			{
				User* oper = *i;
				if (!oper->server->IsULine())
				{
					LocalUser* lu = IS_LOCAL(oper);
					results.push_back("249 " + user->nick + " :" + oper->nick + " (" + oper->ident + "@" + oper->dhost + ") Idle: " +
							(lu ? ConvToStr(ServerInstance->Time() - lu->idle_lastmsg) + " secs" : "unavailable"));
					idx++;
				}
			}
			results.push_back("249 "+user->nick+" :"+ConvToStr(idx)+" OPER(s)");
		}
		break;

		case 'k':
			ServerInstance->XLines->InvokeStats("K",216,user,results);
		break;
		case 'g':
			ServerInstance->XLines->InvokeStats("G",223,user,results);
		break;
		case 'q':
			ServerInstance->XLines->InvokeStats("Q",217,user,results);
		break;
		case 'Z':
			ServerInstance->XLines->InvokeStats("Z",223,user,results);
		break;
		case 'e':
			ServerInstance->XLines->InvokeStats("E",223,user,results);
		break;
		case 'E':
		{
			const SocketEngine::Statistics& stats = SocketEngine::GetStats();
			results.push_back("249 "+user->nick+" :Total events: "+ConvToStr(stats.TotalEvents));
			results.push_back("249 "+user->nick+" :Read events:  "+ConvToStr(stats.ReadEvents));
			results.push_back("249 "+user->nick+" :Write events: "+ConvToStr(stats.WriteEvents));
			results.push_back("249 "+user->nick+" :Error events: "+ConvToStr(stats.ErrorEvents));
			break;
		}

		/* stats m (list number of times each command has been used, plus bytecount) */
		case 'm':
		{
			const CommandParser::CommandMap& commands = ServerInstance->Parser.GetCommands();
			for (CommandParser::CommandMap::const_iterator i = commands.begin(); i != commands.end(); ++i)
			{
				if (i->second->use_count)
				{
					/* RPL_STATSCOMMANDS */
					results.push_back("212 "+user->nick+" "+i->second->name+" "+ConvToStr(i->second->use_count));
				}
			}
		}
		break;

		/* stats z (debug and memory info) */
		case 'z':
		{
			results.push_back("249 "+user->nick+" :Users: "+ConvToStr(ServerInstance->Users->GetUsers().size()));
			results.push_back("249 "+user->nick+" :Channels: "+ConvToStr(ServerInstance->GetChans().size()));
			results.push_back("249 "+user->nick+" :Commands: "+ConvToStr(ServerInstance->Parser.GetCommands().size()));

			float kbitpersec_in, kbitpersec_out, kbitpersec_total;
			char kbitpersec_in_s[30], kbitpersec_out_s[30], kbitpersec_total_s[30];

			SocketEngine::GetStats().GetBandwidth(kbitpersec_in, kbitpersec_out, kbitpersec_total);

			snprintf(kbitpersec_total_s, 30, "%03.5f", kbitpersec_total);
			snprintf(kbitpersec_out_s, 30, "%03.5f", kbitpersec_out);
			snprintf(kbitpersec_in_s, 30, "%03.5f", kbitpersec_in);

			results.push_back("249 "+user->nick+" :Bandwidth total:  "+ConvToStr(kbitpersec_total_s)+" kilobits/sec");
			results.push_back("249 "+user->nick+" :Bandwidth out:    "+ConvToStr(kbitpersec_out_s)+" kilobits/sec");
			results.push_back("249 "+user->nick+" :Bandwidth in:     "+ConvToStr(kbitpersec_in_s)+" kilobits/sec");

#ifndef _WIN32
			/* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
			 * Also cuts out some identical code in both branches of the ifndef. -- Om
			 */
			rusage R;

			/* Not sure why we were doing '0' with a RUSAGE_SELF comment rather than just using RUSAGE_SELF -- Om */
			if (!getrusage(RUSAGE_SELF,&R))	/* RUSAGE_SELF */
			{
				results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr(R.ru_maxrss)+"K");
				results.push_back("249 "+user->nick+" :Signals:          "+ConvToStr(R.ru_nsignals));
				results.push_back("249 "+user->nick+" :Page faults:      "+ConvToStr(R.ru_majflt));
				results.push_back("249 "+user->nick+" :Swaps:            "+ConvToStr(R.ru_nswap));
				results.push_back("249 "+user->nick+" :Context Switches: Voluntary; "+ConvToStr(R.ru_nvcsw)+" Involuntary; "+ConvToStr(R.ru_nivcsw));

				char percent[30];

				float n_elapsed = (ServerInstance->Time() - ServerInstance->stats.LastSampled.tv_sec) * 1000000
					+ (ServerInstance->Time_ns() - ServerInstance->stats.LastSampled.tv_nsec) / 1000;
				float n_eaten = ((R.ru_utime.tv_sec - ServerInstance->stats.LastCPU.tv_sec) * 1000000 + R.ru_utime.tv_usec - ServerInstance->stats.LastCPU.tv_usec);
				float per = (n_eaten / n_elapsed) * 100;

				snprintf(percent, 30, "%03.5f%%", per);
				results.push_back("249 "+user->nick+" :CPU Use (now):    "+percent);

				n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
				n_eaten = (float)R.ru_utime.tv_sec + R.ru_utime.tv_usec / 100000.0;
				per = (n_eaten / n_elapsed) * 100;
				snprintf(percent, 30, "%03.5f%%", per);
				results.push_back("249 "+user->nick+" :CPU Use (total):  "+percent);
			}
#else
			PROCESS_MEMORY_COUNTERS MemCounters;
			if (GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters)))
			{
				results.push_back("249 "+user->nick+" :Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
				results.push_back("249 "+user->nick+" :Pagefile usage:   "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
				results.push_back("249 "+user->nick+" :Page faults:      "+ConvToStr(MemCounters.PageFaultCount));
			}

			FILETIME CreationTime;
			FILETIME ExitTime;
			FILETIME KernelTime;
			FILETIME UserTime;
			LARGE_INTEGER ThisSample;
			if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
				QueryPerformanceCounter(&ThisSample))
			{
				KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
				KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
				double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats.LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats.LastCPU.dwLowDateTime) )/100000;
				double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats.LastSampled.QuadPart) / ServerInstance->stats.QPFrequency.QuadPart;
				double per = (n_eaten/n_elapsed);

				char percent[30];

				snprintf(percent, 30, "%03.5f%%", per);
				results.push_back("249 "+user->nick+" :CPU Use (now):    "+percent);

				n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
				n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
				per = (n_eaten / n_elapsed);
				snprintf(percent, 30, "%03.5f%%", per);
				results.push_back("249 "+user->nick+" :CPU Use (total):  "+percent);
			}
#endif
		}
		break;

		case 'T':
		{
			results.push_back("249 "+user->nick+" :accepts "+ConvToStr(ServerInstance->stats.Accept)+" refused "+ConvToStr(ServerInstance->stats.Refused));
			results.push_back("249 "+user->nick+" :unknown commands "+ConvToStr(ServerInstance->stats.Unknown));
			results.push_back("249 "+user->nick+" :nick collisions "+ConvToStr(ServerInstance->stats.Collisions));
			results.push_back("249 "+user->nick+" :dns requests "+ConvToStr(ServerInstance->stats.DnsGood+ServerInstance->stats.DnsBad)+" succeeded "+ConvToStr(ServerInstance->stats.DnsGood)+" failed "+ConvToStr(ServerInstance->stats.DnsBad));
			results.push_back("249 "+user->nick+" :connection count "+ConvToStr(ServerInstance->stats.Connects));
			results.push_back(InspIRCd::Format("249 %s :bytes sent %5.2fK recv %5.2fK", user->nick.c_str(),
				ServerInstance->stats.Sent / 1024.0, ServerInstance->stats.Recv / 1024.0));
		}
		break;

		/* stats o */
		case 'o':
		{
			ConfigTagList tags = ServerInstance->Config->ConfTags("oper");
			for(ConfigIter i = tags.first; i != tags.second; ++i)
			{
				ConfigTag* tag = i->second;
				results.push_back("243 "+user->nick+" O "+tag->getString("host")+" * "+
					tag->getString("name") + " " + tag->getString("type")+" 0");
			}
		}
		break;
		case 'O':
		{
			for (ServerConfig::OperIndex::const_iterator i = ServerInstance->Config->OperTypes.begin(); i != ServerInstance->Config->OperTypes.end(); ++i)
			{
				OperInfo* tag = i->second;
				tag->init();
				std::string umodes;
				std::string cmodes;
				for(char c='A'; c <= 'z'; c++)
				{
					ModeHandler* mh = ServerInstance->Modes->FindMode(c, MODETYPE_USER);
					if (mh && mh->NeedsOper() && tag->AllowedUserModes[c - 'A'])
						umodes.push_back(c);
					mh = ServerInstance->Modes->FindMode(c, MODETYPE_CHANNEL);
					if (mh && mh->NeedsOper() && tag->AllowedChanModes[c - 'A'])
						cmodes.push_back(c);
				}
				results.push_back("243 "+user->nick+" O "+tag->name.c_str() + " " + umodes + " " + cmodes);
			}
		}
		break;

		/* stats l (show user I/O stats) */
		case 'l':
		/* stats L (show user I/O stats with IP addresses) */
		case 'L':
			GenerateStatsLl(user, results, statschar);
		break;

		/* stats u (show server uptime) */
		case 'u':
		{
			unsigned int up = static_cast<unsigned int>(ServerInstance->Time() - ServerInstance->startup_time);
			results.push_back(InspIRCd::Format("242 %s :Server up %u days, %.2u:%.2u:%.2u", user->nick.c_str(),
				up / 86400, (up / 3600) % 24, (up / 60) % 60, up % 60));
		}
		break;

		default:
		break;
	}

	results.push_back("219 "+user->nick+" "+statschar+" :End of /STATS report");
	ServerInstance->SNO->WriteToSnoMask('t',"%s '%c' requested by %s (%s@%s)",
		(IS_LOCAL(user) ? "Stats" : "Remote stats"), statschar, user->nick.c_str(), user->ident.c_str(), user->host.c_str());
	return;
}
Ejemplo n.º 2
0
int MemoryTracker::get_current_memory() {
    GetProcessMemoryInfo(GetCurrentProcess(), &memStruct, sizeof(memStruct));
    return memStruct.QuotaNonPagedPoolUsage;
}
Ejemplo n.º 3
0
void MemoryTracker::save_memory() {
    GetProcessMemoryInfo(GetCurrentProcess(), &memStruct, sizeof(memStruct));
    loggedMemory = memStruct.QuotaNonPagedPoolUsage;
}
Ejemplo n.º 4
0
void worksize() {
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
    std::cout << info.WorkingSetSize << std::endl;
}
Ejemplo n.º 5
0
TCN_IMPLEMENT_CALL(jint, OS, info)(TCN_STDARGS,
                                   jlongArray inf)
{
    MEMORYSTATUSEX ms;
    ULONGLONG st[4];
    FILETIME ft[4];
    PROCESS_MEMORY_COUNTERS pmc;
    jint rv;
    int i;
    jsize ilen = (*e)->GetArrayLength(e, inf);
    jlong *pvals = (*e)->GetLongArrayElements(e, inf, NULL);

    if (ilen < 16) {
        return APR_EINVAL;
    }
    for (i = 0; i < 16; i++)
        pvals[i] = 0;

    ms.dwLength = sizeof(MEMORYSTATUSEX);

    UNREFERENCED(o);
    if (GlobalMemoryStatusEx(&ms)) {
        pvals[0] = (jlong)ms.ullTotalPhys;
        pvals[1] = (jlong)ms.ullAvailPhys;
        pvals[2] = (jlong)ms.ullTotalPageFile;
        pvals[3] = (jlong)ms.ullAvailPageFile;
        /* Slots 4 and 5 are for shared memory */
        pvals[6] = (jlong)ms.dwMemoryLoad;
    }
    else
        goto cleanup;

    memset(st, 0, sizeof(st));

    if (fnGetSystemTimes) {
        if ((*fnGetSystemTimes)(&ft[0], &ft[1], &ft[2])) {
            st[0] = (((ULONGLONG)ft[0].dwHighDateTime << 32) | ft[0].dwLowDateTime) / 10;
            st[1] = (((ULONGLONG)ft[1].dwHighDateTime << 32) | ft[1].dwLowDateTime) / 10;
            st[2] = (((ULONGLONG)ft[2].dwHighDateTime << 32) | ft[2].dwLowDateTime) / 10;
        }
        else
            goto cleanup;
    }
#if (_WIN32_WINNT < 0x0501)
    else if (fnNtQuerySystemInformation) {
        BYTE buf[2048]; /* This should ne enough for 32 processors */
        NTSTATUS rs = (*fnNtQuerySystemInformation)(SystemProcessorPerformanceInformation,
                                           (LPVOID)buf, 2048, NULL);
        if (rs == 0) {
            PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION pspi = (PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)&buf[0];
            DWORD i;
            /* Calculate all processors */
            for (i = 0; i < dll_system_info.dwNumberOfProcessors; i++) {
                st[0] += pspi[i].IdleTime.QuadPart / 10;
                st[1] += pspi[i].KernelTime.QuadPart / 10;
                st[2] += pspi[i].UserTime.QuadPart / 10;
            }
        }
        else
            goto cleanup;
    }
#endif
    pvals[7] = st[0];
    pvals[8] = st[1];
    pvals[9] = st[2];

    memset(st, 0, sizeof(st));
    if (GetProcessTimes(GetCurrentProcess(), &ft[0], &ft[1], &ft[2], &ft[3])) {
        FileTimeToAprTime((apr_time_t *)&st[0], &ft[0]);
        st[1] = (((ULONGLONG)ft[2].dwHighDateTime << 32) | ft[2].dwLowDateTime) / 10;
        st[2] = (((ULONGLONG)ft[3].dwHighDateTime << 32) | ft[3].dwLowDateTime) / 10;
    }
    pvals[10] = st[0];
    pvals[11] = st[1];
    pvals[12] = st[2];

    if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) {
        pvals[13] = pmc.WorkingSetSize;
        pvals[14] = pmc.PeakWorkingSetSize;
        pvals[15] = pmc.PageFaultCount;
    }

    (*e)->ReleaseLongArrayElements(e, inf, pvals, 0);
    return APR_SUCCESS;
cleanup:
    rv = apr_get_os_error();
    (*e)->ReleaseLongArrayElements(e, inf, pvals, 0);
    return rv;
}
Ejemplo n.º 6
0
 int ProcessInfo::getResidentSize() {
     PROCESS_MEMORY_COUNTERS pmc;
     assert( GetProcessMemoryInfo( GetCurrentProcess() , &pmc, sizeof(pmc) ) );
     return _wconvertmtos( pmc.WorkingSetSize );
 }
Ejemplo n.º 7
0
JNIEXPORT jint
JNICALL Java_us_temerity_pipeline_NativeProcessLight_execNativeLight
(
 JNIEnv *env, 
 jobject obj, 
 jobjectArray jcmdarray,   /* IN: command[0] and arguments[1+] */                 
 jobjectArray jenvp,       /* IN: environmental variable name=value pairs */  
 jstring jdir              /* IN: the working directory */  
)
{
  /* exception initialization */ 
  char msg[2048];
  jclass IOException = env->FindClass("java/io/IOException");
  if(IOException == 0) {
    errno = EINVAL;
    perror("NativeProcessLight.execNative(), unable to lookup \"java/lang/IOException\"");
    return -1;
  }

  /* get handles for the NativeProcessLight object's fields/methods */ 
  jclass NativeProcessLightClass = env->GetObjectClass(obj);  
  if(NativeProcessLightClass == 0) {
    env->ThrowNew(IOException, "unable to lookup class: NativeProcessLight");
    return -1;
  }
    
  jfieldID pStdInFileDesc = env->GetFieldID(NativeProcessLightClass, "pStdInFileDesc", "I");
  if(pStdInFileDesc == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pStdInFileDesc");
    return -1;
  }
    
  jfieldID pStdOutFileDesc = env->GetFieldID(NativeProcessLightClass, "pStdOutFileDesc", "I");
  if(pStdOutFileDesc == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pStdOutFileDesc");
    return -1;
  }

  jfieldID pStdErrFileDesc = env->GetFieldID(NativeProcessLightClass, "pStdErrFileDesc", "I");
  if(pStdErrFileDesc == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pStdErrFileDesc");
    return -1;
  }
 
  jfieldID pUTime = env->GetFieldID(NativeProcessLightClass, "pUTime", "J");
  if(pUTime == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pUTime");
    return -1;
  }

  jfieldID pSTime = env->GetFieldID(NativeProcessLightClass, "pSTime", "J");
  if(pSTime == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pSTime");
    return -1;
  }
  
  jfieldID pPageFaults = env->GetFieldID(NativeProcessLightClass, "pPageFaults", "J");
  if(pPageFaults == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pPageFaults");
    return -1;
  }
  
  jfieldID pVirtualSize = env->GetFieldID(NativeProcessLightClass, "pVirtualSize", "J");
  if(pVirtualSize == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pVirtualSize");
    return -1;
  }
  
  jfieldID pResidentSize = env->GetFieldID(NativeProcessLightClass, "pResidentSize", "J");
  if(pResidentSize == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pResidentSize");
    return -1;
  }
  
  jfieldID pSwappedSize = env->GetFieldID(NativeProcessLightClass, "pSwappedSize", "J");
  if(pSwappedSize == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.pSwappedSize");
    return -1;
  }
  
  jmethodID setPid = env->GetMethodID(NativeProcessLightClass, "setPid", "(I)V");
  if(setPid == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.setPid()");
    return -1;
  }
  
  jmethodID setIsRunning = env->GetMethodID(NativeProcessLightClass, "setIsRunning", "(Z)V");
  if(setIsRunning == 0) {
    env->ThrowNew(IOException, "unable to access: NativeProcessLight.setIsRunning()");
    return -1;
  }
  
  /* repackage the arguments */ 
  const char* dir = NULL; 
  char* cmdline = NULL; 
  TCHAR envbuf[32768]; 
  {
    {
      dir = env->GetStringUTFChars(jdir, 0);      
      if((dir == NULL) || (strlen(dir) == 0)) {
        env->ThrowNew(IOException,"empty working directory");
        return -1;
      } 

      printf("Dir = %s\n", dir);    // DEBUG

      struct stat buf;
      if(stat(dir, &buf) == -1) {
        sprintf(msg, "stat failed for \"%s\": %s", dir, strerror(errno));
        env->ReleaseStringUTFChars(jdir, dir);

        env->ThrowNew(IOException, msg);
        return -1;
      }
      else if(!(buf.st_mode & _S_IFDIR)) {
        sprintf(msg, "illegal working directory \"%s\"", dir);
        env->ReleaseStringUTFChars(jdir, dir);

        env->ThrowNew(IOException, msg);
        return -1;
      }
    }

    printf("Dir is OK\n");      // DEBUG

    {
      jsize len = env->GetArrayLength(jcmdarray);
      if(len == 0) {
        env->ReleaseStringUTFChars(jdir, dir);

        env->ThrowNew(IOException, "empty command arguments array");
        return -1;
      }

      jsize i;
      size_t csize = 0; 
      for(i=0; i<len; i++) {    
        jstring s = (jstring) env->GetObjectArrayElement(jcmdarray, i);
        const char* arg = env->GetStringUTFChars(s, NULL);
        csize += strlen(arg) + ((i == 0) ? 2 : 1);
        env->ReleaseStringUTFChars(s, arg);     
      }

      printf("Cmdline Size = %d\n", csize);     // DEBUG

      if(csize >= 32767) {
        env->ReleaseStringUTFChars(jdir, dir);

        env->ThrowNew(IOException, "command line exceeds 32K limit on Windows!");
        return -1; 
      }

      cmdline = new char[csize+1];
      cmdline[0] = '\0';
      for(i=0; i<len; i++) {
        jstring s = (jstring) env->GetObjectArrayElement(jcmdarray, i);
        const char* arg = env->GetStringUTFChars(s, NULL);      

        strcat(cmdline, (i == 0) ? "\"" : " ");
        strcat(cmdline, arg);
        if(i == 0)
          strcat(cmdline, "\"");

        env->ReleaseStringUTFChars(s, arg);
      }

      printf("Cmdline = %s\n", cmdline);     // DEBUG
    }

    {
      jsize len = env->GetArrayLength(jenvp);

      printf("Environment:\n");      // DEBUG

      LPTSTR envp = envbuf;
      int total = 0;
      jsize i;
      for(i=0; i<len; i++) {
        jstring s = (jstring) env->GetObjectArrayElement(jenvp, i);
        const char* keyval = env->GetStringUTFChars(s, NULL);

        printf("  %s\n", keyval);

        if(lstrcpy(envp, TEXT(keyval)) == NULL) {
          env->ReleaseStringUTFChars(jdir, dir);
          delete[] cmdline;

          env->ThrowNew(IOException, "failed to copy environment");
          return -1;
        }

        env->ReleaseStringUTFChars(s, keyval);

        int size = (lstrlen(envp) + 1) * sizeof(TCHAR);
        total += size;

        if(total > 32768) {
          env->ReleaseStringUTFChars(jdir, dir);
          delete[] cmdline;

          env->ThrowNew(IOException, "environment exceeds 32K limit on Windows!");
          return -1; 
        }

        envp += size;
      }
      *envp = '\0';
    }
  }
  
  /* create pipes to communicate with the child process */ 
  HANDLE child_stdin, child_stdout, child_stderr;
  HANDLE parent_stdin, parent_stdout, parent_stderr; 
  {
    /* security attributes which allow handles to be inherited by the child process */ 
    SECURITY_ATTRIBUTES saAttr; 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL; 
 
    /* create a pipe to the child's STDIN */
    if(!CreatePipe(&child_stdin, &parent_stdin, &saAttr, 0)) {
      env->ReleaseStringUTFChars(jdir, dir);
      delete[] cmdline;        

      env->ThrowNew(IOException, "unable to create the STDIN pipe!"); 
      return -1;
    }

    /* create a pipe to the child's STDOUT */
    if(!CreatePipe(&parent_stdout, &child_stdout, &saAttr, 0)) {
      env->ReleaseStringUTFChars(jdir, dir);
      delete[] cmdline;
      CloseHandle(child_stdin);

      env->ThrowNew(IOException, "unable to create the STDOUT pipe!"); 
      return -1;
    }

    /* create a pipe to the child's STDERR */
    if(!CreatePipe(&parent_stderr, &child_stderr, &saAttr, 0)) {
      env->ReleaseStringUTFChars(jdir, dir);
      delete[] cmdline;
      CloseHandle(child_stdin);
      CloseHandle(child_stdout);

      env->ThrowNew(IOException, "unable to create the STDERR pipe!"); 
      return -1;
    }  
    
    /* make sure parent side of STDIN STDOUT and STDERR pipes are not inherited */ 
    SetHandleInformation(parent_stdin, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(parent_stdout, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(parent_stderr, HANDLE_FLAG_INHERIT, 0);
  }
  
  /* create the child process */ 
  DWORD exitCode; 
  {
    PROCESS_INFORMATION procInfo; 
    STARTUPINFO startInfo;

    ZeroMemory(&procInfo, sizeof(PROCESS_INFORMATION));
 
    ZeroMemory(&startInfo, sizeof(STARTUPINFO));
    startInfo.cb = sizeof(STARTUPINFO); 
    startInfo.hStdError  = child_stderr;
    startInfo.hStdOutput = child_stdout; 
    startInfo.hStdInput  = child_stdin;
    startInfo.dwFlags |= STARTF_USESTDHANDLES;
 
    if(CreateProcess(NULL, TEXT(cmdline), NULL, NULL, TRUE, 0, 
                     (LPVOID) envbuf, TEXT(dir), &startInfo, &procInfo) == 0)  {
      env->ReleaseStringUTFChars(jdir, dir);
      delete[] cmdline;       
      CloseHandle(child_stdin);
      CloseHandle(child_stdout);
      CloseHandle(child_stderr);
      
      throwWindowsIOException(env, IOException, "CreateProcessAsUser"); 
      return -1;
    }
    env->ReleaseStringUTFChars(jdir, dir);
    delete[] cmdline;
                    
    printf("Created Process\n");     // DEBUG

    /* set the process ID */ 
    jint pid = (jint) procInfo.dwProcessId;
    env->CallVoidMethod(obj, setPid, pid);

    /* set IO fields for the parent ends of the pipes */ 
    env->SetIntField(obj, pStdInFileDesc, (jint) parent_stdin);
    env->SetIntField(obj, pStdOutFileDesc, (jint) parent_stdout);
    env->SetIntField(obj, pStdErrFileDesc, (jint) parent_stderr);

    /* let Java know that the process is running */ 
    env->CallVoidMethod(obj, setIsRunning, true);
      
    printf("Wating on PID (%d)...\n", pid);     // DEBUG

    /* wait on the process to exit */ 
    if(WaitForSingleObject(procInfo.hProcess, INFINITE) == WAIT_FAILED) {
      CloseHandle(child_stdin);
      CloseHandle(child_stdout);
      CloseHandle(child_stderr);

      env->ThrowNew(IOException, "failed to wait on subprocess!"); 
      return -1;
    }

    printf("Done Wating!\n");     // DEBUG

    /* let Java know that the process has exited */ 
    env->CallVoidMethod(obj, setIsRunning, false);
        
    /* get the exit code */ 
    if(!GetExitCodeProcess(procInfo.hProcess, &exitCode)) {
      CloseHandle(child_stdin);
      CloseHandle(child_stdout);
      CloseHandle(child_stderr);

      env->ThrowNew(IOException, "failed to get subprocess exit code!"); 
      return -1;
    }

    printf("Exit Code = %d\n", exitCode);       // DEBUG

    /* close the child side of the STDIN pipe */ 
    if(!CloseHandle(child_stdin)) {
      CloseHandle(child_stdout);
      CloseHandle(child_stderr);

      env->ThrowNew(IOException, "unable to close the child side of the STDIN pipe!"); 
      return -1;
    }

    /* close the child side of the STDOUT pipe */ 
    if(!CloseHandle(child_stdout)) {
      env->ThrowNew(IOException, "unable to close the child side of the STDOUT pipe!"); 
      return -1;
    }
    
    /* close the child side of the STDERR pipe */ 
    if(!CloseHandle(child_stderr)) {
      env->ThrowNew(IOException, "unable to close the child side of the STDERR pipe!"); 
      return -1;
    }

    /* get usage statistics */
    {
      FILETIME createTime, exitTime, sysTime, userTime; 
      if(!GetProcessTimes(procInfo.hProcess, &createTime, &exitTime, &sysTime, &userTime)) {
        env->ThrowNew(IOException, "failed to get subprocess timing statistics!"); 
        return -1;
      }

      /* 64-bit times returned by GetProcessTime are in 100ns (100/10^9), 
         while the times reported to Java are in jiffies (1/100) of a second */   
      jlong denom = 100000L;

      { 
        ULARGE_INTEGER li;
        memcpy(&li, &userTime, sizeof(FILETIME));
        env->SetLongField(obj, pUTime, li.QuadPart / denom);  

        printf("User Time = %I64u (100-ns)  %I64u (jiffies)\n", 
               li.QuadPart, li.QuadPart / denom); 
      }                                   

      { 
        ULARGE_INTEGER li;
        memcpy(&li, &sysTime, sizeof(FILETIME));
        env->SetLongField(obj, pSTime, li.QuadPart / denom);

        printf("System Time = %I64u (100-ns)  %I64u (jiffies)\n", 
               li.QuadPart, li.QuadPart / denom); 
      }

      /* get process memory usage statistics */ 
      {
        PROCESS_MEMORY_COUNTERS pmc;
        if(!GetProcessMemoryInfo(procInfo.hProcess, &pmc, sizeof(pmc))) {
          env->ThrowNew(IOException, "failed to get subprocess memory usage statistics!"); 
          return -1;
        }

        // DEBUG
        printf("PageFaults = %I64d\n", (jlong) pmc.PageFaultCount);
        printf("PeakWorking Set Size = %I64d\n", (jlong) pmc.PeakWorkingSetSize);
        printf("PeakPagefileUsage = %I64d\n", (jlong) pmc.PeakPagefileUsage);
        printf("QuotaPeakPagedPoolUsage = %I64d\n", (jlong) pmc.QuotaPeakPagedPoolUsage);
        // DEBUG

        env->SetLongField(obj, pPageFaults,   (jlong) pmc.PageFaultCount);
        env->SetLongField(obj, pResidentSize, (jlong) pmc.PeakWorkingSetSize); 
        env->SetLongField(obj, pVirtualSize,  (jlong) pmc.PeakPagefileUsage); 
        env->SetLongField(obj, pSwappedSize,  (jlong) pmc.QuotaPeakPagedPoolUsage);
      } 
    }

    /* cleanup process/thread handles */ 
    CloseHandle(procInfo.hProcess);
    CloseHandle(procInfo.hThread);
  }

  return ((jint) exitCode);
}
Ejemplo n.º 8
0
int _tmain(int argc, TCHAR* argv[])
{
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	FILETIME CreationTime, ExitTime, KernelTime, UserTime;
	IO_COUNTERS ic;
	PROCESS_MEMORY_COUNTERS pmc;
	DWORD exitCode = 0;

	LPTSTR lpCmdLine = GetCommandLine();
	BOOL quoted = lpCmdLine[0] == L'"';

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	ZeroMemory(&pmc, sizeof(pmc));

	// Get the command line, run the process, and then wait for it to terminate
	++lpCmdLine; // skips the " or the first letter (all paths are at least 1 letter)
	while (*lpCmdLine)
	{
		if (quoted && lpCmdLine[0] == L'"') { quoted = FALSE; } // found end quote
		else if (!quoted && lpCmdLine[0] == L' ') // found an unquoted space, now skip all spaces
		{
			do { ++lpCmdLine; } while (lpCmdLine[0] == L' ');
			break;
		}
		++lpCmdLine;
	}
	if (!CreateProcess(NULL, lpCmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
	{
		DisplayError(TEXT("Failed to start process"), GetLastError());
		return 127;
	}
	WaitForSingleObject(pi.hProcess, INFINITE);

	// Get and display process information
	if (GetProcessTimes(pi.hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime))
	{
		_ftprintf(stderr, TEXT("Real Time:         %.3f sec\nUser Time:         %.3f sec\nKernel Time:       %.3f sec\n"),
			FT_TO_SEC(ExitTime) - FT_TO_SEC(CreationTime), FT_TO_SEC(UserTime), FT_TO_SEC(KernelTime));
	}
	else { DisplayError(TEXT("Failed to get time usage of process"), GetLastError()); }
	if (GetProcessMemoryInfo(pi.hProcess, &pmc, sizeof(pmc)))
	{
		_ftprintf(stderr, TEXT("Page Faults:       %Iu\n"),    pmc.PageFaultCount);
		_ftprintf(stderr, TEXT("Max Memory:        %Iu Kb\nMax Commit:        %Iu Kb\n"), pmc.PeakWorkingSetSize / 1024, pmc.PeakPagefileUsage / 1024);
		_ftprintf(stderr, TEXT("Max Paged Pool:    %Iu Kb\nMax Nonpaged Pool: %Iu Kb\n"), pmc.QuotaPeakPagedPoolUsage / 1024, pmc.QuotaPeakNonPagedPoolUsage / 1024);
	}
	else { DisplayError(TEXT("Failed to get memory usage of process"), GetLastError()); }
	if (GetProcessIoCounters(pi.hProcess, &ic))
	{
		_ftprintf(stderr, TEXT("I/O Read:          %I64u Kb during %I64u operations\n"), ic.ReadTransferCount / 1024, ic.ReadOperationCount);
		_ftprintf(stderr, TEXT("I/O Write:         %I64u Kb during %I64u operations\n"), ic.WriteTransferCount / 1024, ic.WriteOperationCount);
		_ftprintf(stderr, TEXT("I/O Other:         %I64u Kb during %I64u operations\n"), ic.OtherTransferCount / 1024, ic.OtherOperationCount);
	}
	else { DisplayError(TEXT("Failed to get I/O usage of process"), GetLastError()); }

	// Close process and thread handles and return the exit code
	GetExitCodeProcess(pi.hProcess, &exitCode);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return exitCode;
}
Ejemplo n.º 9
0
static double GetProcessAttribute(HANDLE hProcess,int attr,int type,int count,double *lastValue)
{
   double value;
   PROCESS_MEMORY_COUNTERS mc;
   IO_COUNTERS ioCounters;
   FILETIME ftCreate,ftExit,ftKernel,ftUser;

   /* Get value for current process instance */
   switch(attr)
   {
      case 0:        /* vmsize */
         GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS));
         value=(double)mc.PagefileUsage/1024;   /* Convert to Kbytes */
         break;
      case 1:        /* wkset */
         GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS));
         value=(double)mc.WorkingSetSize/1024;   /* Convert to Kbytes */
         break;
      case 2:        /* pf */
         GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS));
         value=(double)mc.PageFaultCount;
         break;
      case 3:        /* ktime */
      case 4:        /* utime */
         GetProcessTimes(hProcess,&ftCreate,&ftExit,&ftKernel,&ftUser);
         value = ConvertProcessTime(attr==3 ? &ftKernel : &ftUser);
         break;

      case 5:        /* gdiobj */
      case 6:        /* userobj */
         if(NULL == zbx_GetGuiResources)
	     return SYSINFO_RET_FAIL;

         value = (double)zbx_GetGuiResources(hProcess,attr==5 ? 0 : 1);
         break;

      case 7:        /* io_read_b */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.ReadTransferCount);
         break;
      case 8:        /* io_read_op */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.ReadOperationCount);
         break;
      case 9:        /* io_write_b */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.WriteTransferCount);
         break;
      case 10:       /* io_write_op */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.WriteOperationCount);
         break;
      case 11:       /* io_other_b */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.OtherTransferCount);
         break;
      case 12:       /* io_other_op */
         if(NULL == zbx_GetProcessIoCounters)
	     return SYSINFO_RET_FAIL;

         zbx_GetProcessIoCounters(hProcess,&ioCounters);
         value=(double)((__int64)ioCounters.OtherOperationCount);
         break;

      default:       /* Unknown attribute */
         return SYSINFO_RET_FAIL;
   }

   /* Recalculate final value according to selected type */
   if (count==1)     /* First instance */
   {
      *lastValue = value;
   }

   switch(type)
   {
      case 0:     /* min */
         *lastValue = min((*lastValue),value);
	 break;
      case 1:     /* max */
         *lastValue = max((*lastValue),value);
	 break;
      case 2:     /* avg */
         *lastValue = ((*lastValue) * (count-1) + value) / count;
	 break;
      case 3:     /* sum */
         *lastValue = (*lastValue) + value;
	 break;
      default:
         return SYSINFO_RET_FAIL;
   }

   return SYSINFO_RET_OK;
}
Ejemplo n.º 10
0
/** @name	getMemoryUsage
	@text	Get the current amount of memory used by MOAI and its subsystems. This will
			attempt to return reasonable estimates where exact values cannot be obtained.
			Some fields represent informational fields (i.e. are not double counted in the
			total, but present to assist debugging) and may be only available on certain
			platforms (e.g. Windows, etc). These fields begin with a '_' character.
 
	@out	table	usage		The breakdown of each subsystem's memory usage, in bytes. There is also a "total" field that contains the summed value.
*/
int MOAISim::_getMemoryUsage ( lua_State* L ) {
	
	float divisor = 1.0f;
	
	if( lua_type(L, 1) == LUA_TSTRING )
	{
		cc8* str = lua_tostring(L, 1);
		if( str[0] == 'k' || str[0] == 'K' )
			divisor = 1024.0f;
		else if( str[0] == 'm' || str[0] == 'M' )
			divisor = 1024.0f * 1024.0f;
		else if( str[0] == 'b' || str[0] == 'B' )
			divisor = 1.0f;
	}
	
	size_t total = 0;
	
	lua_newtable(L);
	
	size_t count;
	
	count = MOAILuaRuntime::Get().GetMemoryUsage ();
	lua_pushnumber(L, count / divisor);
	lua_setfield(L, -2, "lua");
	total += count;

	// This is informational only (i.e. don't double count with the previous field).
	// It doesn't actually seem to represent the real usage of lua, but maybe
	// someone is interested.
	lua_pushnumber ( L, lua_gc ( L, LUA_GCCOUNTB, 0 ) / divisor );
	lua_setfield ( L, -2, "_luagc_count" );
	
	count = MOAIGfxDevice::Get ().GetTextureMemoryUsage ();
	lua_pushnumber ( L, count / divisor );
	lua_setfield ( L, -2, "texture" );
	total += count;
	
#if defined(_WIN32)
    PROCESS_MEMORY_COUNTERS pmc;

    // Print the process identifier.
    if ( GetProcessMemoryInfo( GetCurrentProcess(), &pmc, sizeof(pmc)) )
    {
		lua_pushnumber(L, pmc.PagefileUsage / divisor);
		lua_setfield(L, -2, "_sys_vs");
		lua_pushnumber(L, pmc.WorkingSetSize / divisor);
		lua_setfield(L, -2, "_sys_rss");
    }
#elif defined(__APPLE__) //&& defined(TARGET_IPHONE_SIMULATOR) 
	// Tricky undocumented mach polling of memory
	struct task_basic_info t_info;
	mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
	kern_return_t kr = task_info(mach_task_self(),
								 TASK_BASIC_INFO,
								 reinterpret_cast<task_info_t>(&t_info),
								 &t_info_count);
	// Most likely cause for failure: |task| is a zombie.
	if( kr == KERN_SUCCESS )
	{
		lua_pushnumber(L, t_info.virtual_size / divisor);
		lua_setfield(L, -2, "_sys_vs");
		lua_pushnumber(L, t_info.resident_size / divisor);
		lua_setfield(L, -2, "_sys_rss");
	}
#endif
	
	lua_pushnumber(L, total / divisor);
	lua_setfield(L, -2, "total");
	
	return 1;
}
Ejemplo n.º 11
0
Ipp32u vm_sys_info_get_process_memory_usage(VM_PID process_ID)
{
    PROCESS_MEMORY_COUNTERS mc;
    GetProcessMemoryInfo(process_ID, &mc, sizeof(PROCESS_MEMORY_COUNTERS));
    return (Ipp32u)(mc.WorkingSetSize/1024);
}
Ejemplo n.º 12
0
void FastTrackGiftDll::CheckPerformanceCounters()
{
	UINT i;

    // Collect the pdh query data
	if(PdhCollectQueryData(m_pdh))
	{
//		MessageBox(NULL,"Error collecting pdh query data","Error",MB_OK);
//		MessageBox(NULL,m_keynames[1].c_str(),"On this network adaptor",MB_OK);
		//return;
	}

	// Check the processor usage counter
	PDH_FMT_COUNTERVALUE value;
    PDH_STATUS error;

	error=PdhGetFormattedCounterValue(m_pdh_counters[0],PDH_FMT_LONG,0,&value);
	if(error)
	{
//		MessageBox(NULL,"Error formatting pdh counter data","Error",MB_OK);
//		MessageBox(NULL,m_keynames[1].c_str(),"On this network adaptor",MB_OK);
//		m_dlg.SetWindowText("Error formatting pdh coutner data");
		return;
	}

	m_proc_percent_usage=value.longValue;

	// If less than 90 % kick off another mod if there is less than min count of them
	if(/*(m_proc_percent_usage<90) & */(m_connection_manager.ReturnModCount()<(UINT)m_min_module_count))
	{
		m_connection_manager.AddModule();

		char log[1024];
		sprintf(log,"Module Added : (Current Count : %u) : (Proc % Usage : %u%%) : (Min Mod Count : %u)",
			m_connection_manager.ReturnModCount(),m_proc_percent_usage,m_min_module_count);
		m_dlg.Log(log);
	}

	// Check the bandwidth counter
	error=PdhGetFormattedCounterValue(m_pdh_counters[1],PDH_FMT_LONG,0,&value);
	if(error)
	{
//		MessageBox(NULL,"Error formatting bandwidth counter data","Error",MB_OK);
//		MessageBox(NULL,m_keynames[1].c_str(),"On this network adaptor",MB_OK);
//		m_dlg.SetWindowText("Error formatting pdh coutner data");
		return;
	}

	m_bandwidth_in_bytes=value.longValue;

	// Check the current bandwidth in bits per second
	error=PdhGetFormattedCounterValue(m_pdh_counters[2],PDH_FMT_LONG,0,&value);
	if(error)
	{
//		MessageBox(NULL,"Error formatting bandwidth in bits per second data","Error",MB_OK);
//		MessageBox(NULL,m_keynames[1].c_str(),"On this network adaptor",MB_OK);
		return;
	}

	m_current_bandwdith_in_bits_per_second=value.longValue;	// this should be 100 Mbps
	
	double bps=m_bandwidth_in_bytes*8;

	// Measure the processes mem usage
	HANDLE hHandle;
	DuplicateHandle(GetCurrentProcess(),GetCurrentProcess(),GetCurrentProcess(),&hHandle,0,FALSE,DUPLICATE_SAME_ACCESS);
	
	PROCESS_MEMORY_COUNTERS pmc;
	pmc.cb=sizeof(PROCESS_MEMORY_COUNTERS);
	GetProcessMemoryInfo(hHandle,&pmc,sizeof(PROCESS_MEMORY_COUNTERS));

	CloseHandle(hHandle);

	m_mem_usage=(UINT)pmc.WorkingSetSize;	// in bytes

	// Put commas in the mem measurement value
	char mem_buf[1024];
	string mem;
	_itoa(m_mem_usage/1024,mem_buf,10);
	strrev(mem_buf);
	for(i=0;i<strlen(mem_buf);i++)
	{
		if((i>0) && (i%3==0))
		{
			mem+=",";
		}
		
		mem+=mem_buf[i];
	}
	strcpy(mem_buf,mem.c_str());
	strrev(mem_buf);
	
	// Display the status
	char buf[1024];
	sprintf(buf,"[ %u %% ] - [ %.2f KB/sec - %.2f %% ] - [ %s KB ]",m_proc_percent_usage,((double)m_bandwidth_in_bytes)/1024,
		(100*bps)/m_current_bandwdith_in_bits_per_second,mem_buf);
	m_dlg.GetDlgItem(IDC_Computer_Status_Static)->SetWindowText(buf);
}
Ejemplo n.º 13
0
void CMemoryWatcherDlg::OnTimer(UINT_PTR nIDEvent)
{
	if (nIDEvent == 1)
	{
		if (!h)
		{
			if (m_ProcessID)
				h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, m_ProcessID);
			else
				h = GetCurrentProcess();
			if (!h)
				return;
		}
		PROCESS_MEMORY_COUNTERS pmc;
		if (GetProcessMemoryInfo(h, &pmc, sizeof(pmc)))
		{
			points.push(pmc.WorkingSetSize);
			points_pagefile.push(pmc.PagefileUsage);
			peak = pmc.PeakWorkingSetSize;
			peak_pagefile = pmc.PeakPagefileUsage;
		}
		else
		{
			points.push(0);
			points_pagefile.push(0);
		}
		if (points.size() > m_NumSteps + 1)
		{
			points.pop();
			points_pagefile.pop();
		}
		SIZE_T l, total;
		CDC * idc = CDC::FromHandle(img->GetDC());
		CPen pen, * oldpen, * oldpen2, pen2, pen3;
		CString s;
		// setting pen color
		pen.CreatePen(PS_SOLID, 3, RGB(0, 200, 0));
		oldpen = idc->SelectObject(&pen);
		double dx = double(img->GetWidth()) / (m_NumSteps - 1), dy = double(img->GetHeight()) / (m_MaxMem - 1);
		int x, y;
		// clearing image
		idc->FillSolidRect(-1, -1, img->GetWidth() + 2, img->GetHeight() + 2, RGB(0, 0, 0));
		// drawing grid
		pen2.CreatePen(PS_SOLID, 1, RGB(150, 150, 150));
		oldpen2 = idc->SelectObject(&pen2);
		for (UINT i = 0; i < points.size(); i++)
		{
			x = int(i * dx);
			idc->MoveTo(x, 0);
			idc->LineTo(x, img->GetHeight());
		}
		for (double i = 0.0; i < img->GetHeight(); i += img->GetHeight() / 10.0)
		{
			idc->MoveTo(0, int(i));
			idc->LineTo(img->GetWidth(), int(i));
		}
		idc->SelectObject(oldpen2);
		// setting text color
		idc->SetTextColor(RGB(0, 200, 0));
		// drawing points
		for (UINT i = 0; i < points.size(); i++)
		{
			l = points._Get_container()[i];
			x = int(i * dx);
			y = img->GetHeight() - int(l * dy) - 1;
			if (!i)
			{
				idc->MoveTo(x, y);
			}
			else
			{
				idc->LineTo(x, y);
			}
			if (i == points.size() - 1)
			{
				s.Format(L"Memory: %u KB of %u KB, peak %u KB", l / 1024, m_MaxMem / 1024, peak / 1024);
				idc->TextOutW(1, 1, s);
				total = l;
			}
		}
		// drawing points_pagefile
		// setting other pen color
		pen3.CreatePen(PS_SOLID, 3, RGB(200, 0, 0));
		oldpen2 = idc->SelectObject(&pen3);
		// setting text color
		idc->SetTextColor(RGB(200, 0, 0));
		for (UINT i = 0; i < points_pagefile.size(); i++)
		{
			l = points_pagefile._Get_container()[i];
			x = int(i * dx);
			y = img->GetHeight() - int(l * dy) - 1;
			if (!i)
			{
				idc->MoveTo(x, y);
			}
			else
			{
				idc->LineTo(x, y);
			}
			if (i == points_pagefile.size() - 1)
			{
				s.Format(L"Swap: %u KB, peak %u KB", l / 1024, peak_pagefile / 1024);
				idc->TextOutW(1, 17, s);
				total += l;
			}
		}
		// setting text color
		idc->SetTextColor(RGB(200, 200, 0));
		s.Format(L"Total: %u KB, peak %u KB", total / 1024, (peak_pagefile + peak) / 1024);
		idc->TextOutW(1, 33, s);
		idc->SelectObject(oldpen2);
		idc->SelectObject(oldpen);
		img->ReleaseDC();
		// displaying image
		DrawImage();
		// saving to file
		f << l << L"\n";
	}
	CDialog::OnTimer(nIDEvent);
}
Ejemplo n.º 14
0
void CCrashInfoReader::CollectMiscCrashInfo(CErrorReportInfo& eri)
{   
    // Get crash time
    Utility::GetSystemTimeUTC(eri.m_sSystemTimeUTC);

    // Open parent process handle
    HANDLE hProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, 
        FALSE, 
        m_dwProcessId);
		
    if(hProcess!=NULL)
    {	
		SIZE_T uBytesRead = 0;
		BYTE buff[1024];
		memset(&buff, 0, 1024);
		
		// Read exception information from process memory
		if(m_pExInfo!=NULL)
		{			
			if(ReadProcessMemory(hProcess, m_pExInfo, &buff, sizeof(EXCEPTION_POINTERS), &uBytesRead) &&
				uBytesRead==sizeof(EXCEPTION_POINTERS))
			{
				EXCEPTION_POINTERS* pExcPtrs = (EXCEPTION_POINTERS*)buff;

				if(pExcPtrs->ExceptionRecord!=NULL)
				{
					DWORD64 dwExcRecordAddr = (DWORD64)pExcPtrs->ExceptionRecord;
					if(ReadProcessMemory(hProcess, (LPCVOID)dwExcRecordAddr, &buff, sizeof(EXCEPTION_RECORD), &uBytesRead) &&
						uBytesRead==sizeof(EXCEPTION_RECORD))
					{
						EXCEPTION_RECORD* pExcRec = (EXCEPTION_RECORD*)buff;

						eri.m_dwExceptionAddress = (DWORD64)pExcRec->ExceptionAddress;
					}
				}				
			}
		}
		else
			eri.m_dwExceptionAddress = 0;

        // Get number of GUI resources in use  
        eri.m_dwGuiResources = GetGuiResources(hProcess, GR_GDIOBJECTS);

        // Determine if GetProcessHandleCount function available
        typedef BOOL (WINAPI *LPGETPROCESSHANDLECOUNT)(HANDLE, PDWORD);
        HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll"));
        if(hKernel32!=NULL)
        {
            LPGETPROCESSHANDLECOUNT pfnGetProcessHandleCount = 
                (LPGETPROCESSHANDLECOUNT)GetProcAddress(hKernel32, "GetProcessHandleCount");
            if(pfnGetProcessHandleCount!=NULL)
            {    
                // Get count of opened handles
                DWORD dwHandleCount = 0;
                BOOL bGetHandleCount = pfnGetProcessHandleCount(hProcess, &dwHandleCount);
                if(bGetHandleCount)
                    eri.m_dwProcessHandleCount = dwHandleCount;
                else
                    eri.m_dwProcessHandleCount = 0;
            }

            FreeLibrary(hKernel32);
            hKernel32=NULL;
        }

        // Get memory usage info
        PROCESS_MEMORY_COUNTERS meminfo;
        BOOL bGetMemInfo = GetProcessMemoryInfo(hProcess, &meminfo, 
            sizeof(PROCESS_MEMORY_COUNTERS));
        if(bGetMemInfo)
        {    
            CString sMemUsage;
#ifdef _WIN64
            sMemUsage.Format(_T("%I64u"), meminfo.WorkingSetSize/1024);
#else
            sMemUsage.Format(_T("%lu"), meminfo.WorkingSetSize/1024);
#endif 
            eri.m_sMemUsage = sMemUsage;
        }

        // Determine the period of time the process is working.
        FILETIME CreationTime, ExitTime, KernelTime, UserTime;
        /*BOOL bGetTimes = */GetProcessTimes(hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime);
        /*ATLASSERT(bGetTimes);*/
        SYSTEMTIME AppStartTime;
        FileTimeToSystemTime(&CreationTime, &AppStartTime);

        SYSTEMTIME CurTime;
        GetSystemTime(&CurTime);
        ULONG64 uCurTime = Utility::SystemTimeToULONG64(CurTime);
        ULONG64 uStartTime = Utility::SystemTimeToULONG64(AppStartTime);

        // Check that the application works for at least one minute before crash.
        // This might help to avoid cyclic error report generation when the applciation
        // crashes on startup.
        double dDiffTime = (double)(uCurTime-uStartTime)*10E-08;
        //if(dDiffTime<60)
        //{
        //    m_bAppRestart = FALSE; // Disable restart.
        //} 
    }

    // Get operating system friendly name from registry.
    Utility::GetOSFriendlyName(eri.m_sOSName);

    // Determine if Windows is 64-bit.
    eri.m_bOSIs64Bit = Utility::IsOS64Bit();

    // Get geographic location.
    Utility::GetGeoLocation(eri.m_sGeoLocation);  
}
Ejemplo n.º 15
0
int mainTest(int argNumber, char* argString[])
{
    //Init Logger
    Logger::getInstance()->setLoggingLevel(eINFO);

    //We create a folder for background substraction configuration file. BGSLib will crash if that folder doesn't exist.
    boost::filesystem::create_directory("config");

    //We load the tracking configuration
    po::options_description fileConfig("Configuration file options");
    po::variables_map vm = LoadConfigurationSettings(argNumber, argString, fileConfig);
    if(vm.count("logging-level") >0)
    {
        unsigned int level = vm["logging-level"].as<unsigned int>();
        if(level >= 0 && level <= eNONE)
            Logger::getInstance()->setLoggingLevel(ELoggingLevel(level));
    }


    //We load the video
    bool overrideTotalNbFrame = false;
    unsigned int lastFrame = -1;
    InputFrameProviderIface* vfm = LoadVideo(vm, overrideTotalNbFrame, lastFrame);
    try
    {
        if(vfm && vfm->isOpen())
        {
            LOGINFO("Starting tracker");

            bool success = true;
            DrawableTimer dt;


            float pixelByMeter = 1;
            if(vm.count("scaleratio-filename") > 0 && vm["scaleratio-filename"].as<std::string>() != "none" && vm["scaleratio-filename"].as<std::string>() != "None")
            {
                success = Utils::IO::LoadScalar<float>(vm["scaleratio-filename"].as<std::string>(), pixelByMeter);
                if(!success)
                {
                    pixelByMeter = 1;
                    LOGWARNING("Can't load scale ratio file. Using 1px/m ratio");
                }
            }

            cv::Mat homography = cv::Mat::eye(3,3, CV_32FC1);
            if(vm.count("homography-filename") > 0 && vm["homography-filename"].as<std::string>() != "none" && vm["homography-filename"].as<std::string>() != "None")
            {
                success = Utils::IO::LoadMatrix<double>(vm["homography-filename"].as<std::string>(), homography);
                if(!success)
                {
                    homography = cv::Mat::eye(3,3, CV_32FC1);
                    LOGWARNING("Can't load homography file. Using identity.");
                }
            }
            cv::Mat mask;

            if(vm.count("mask-filename") > 0 && vm["mask-filename"].as<std::string>() != "none" && vm["mask-filename"].as<std::string>() != "None")
            {
                mask = cv::imread(vm["mask-filename"].as<std::string>());
                cv::cvtColor(mask, mask, CV_BGR2GRAY);
            }
            else
            {
                mask = cv::Mat(vfm->getHeight(), vfm->getWidth(), CV_8UC1);
                mask.setTo(cv::Scalar(255,255,255));
            }


            /*if(vm.count("aerialview-filename") > 0)
            {
                std::string aerialfn(vm["aerialview-filename"].as<std::string>());
                const cv::Mat aerialView = cv::imread(aerialfn);
            }*/


            DrawingFlags drawFlags = LoadDrawingFlags(vm);
            BlobTrackerAlgorithmParams algoParams = LoadTrackerParams(vm);
            DisplayInstruction();

            ApplicationContext context(mask, homography,(float)vfm->getNbFPS(), pixelByMeter, drawFlags, algoParams, vm["record-bgs"].as<bool>(), vfm);
            TrackerPersistance op(&context, vm["object-sqlite-filename"].as<std::string>());
            op.init();
            std::string bgsRecord = vm["bgs-filepath"].as<std::string>();
            context.setBGSPath(bgsRecord);
            std::string bgsType = vm["bgs-type"].as<std::string>();

            Tracker t(&context, bgsType);
            if(bgsType == "PlaybackBGS" && vm.count("bgs-filepath") > 0)
            {
                IBGS* bgs = t.getBlobDetector()->getBGS();
                PlaybackBGS* pbBGS = dynamic_cast<PlaybackBGS*>(bgs);
                if(pbBGS)
                    pbBGS->setPath(bgsRecord);
//                std::cout<<"remove playBackBgs\n";
//                exit(-1);
            }

            //bgs-filepath
            cv::Mat m;
            bool stepByStep = false;
            bool quit = false;
            bool displayMemory = vm["draw-memory"].as<bool>();


            if(!vfm->isOpen())
            {
                LOGERROR("Can't open video file");
                return 0;
            }
            int nbFrameProcess = 0;
            while(vfm->getNextFrame(m) && !quit && (!overrideTotalNbFrame || vfm->getNextFramePos() <= vfm->getNbFrame()) &&  (vfm->getNextFramePos() <= lastFrame || lastFrame == -1))
            {
                context.setCurrentFrame(m);
                dt.start();
                t.processFrame(m);
                dt.stop();
                if(context.getRefDrawingFlags()->mDrawFPS)
                    dt.drawFPS(m);

                cv::Mat trajectoryPictureClone = m.clone();
                if(drawFlags.mDrawPerspective)
                {
                    t.draw(m);
                    #ifdef _WIN32
                    if(displayMemory)
                    {
                        PROCESS_MEMORY_COUNTERS memCounter;
                        bool result = GetProcessMemoryInfo(GetCurrentProcess(), &memCounter, sizeof( memCounter ));
                        float nbMeg = memCounter.WorkingSetSize/(1048576.f);
                        cv::putText(m, Utils::String::toString(nbMeg)+ " Mo", cv::Point(0,m.rows-5), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0,255,255),2);
                    }
                    #endif
                    cv::imshow("Video", m);
                    int key;
                    if(stepByStep)
                    {
                        key = cv::waitKey();
                    }
                    else
                        key = cv::waitKey(1);

                    if(key == 's')
                    {
                        stepByStep = !stepByStep;
                    }
                    else if(key == 'm')
                    {
                        displayMemory = !displayMemory;
                    }
                    else if(key == 'q')
                    {
                        std::cout << "Quit was requested. Exiting...";
                        quit = true;
                    }
                    else
                        UpdateContextFromKeys(&context, key);
                }
                ++nbFrameProcess;
                if(nbFrameProcess %50 == 0)
                    std::cout << "Frame " << nbFrameProcess << std::endl;
            }
            delete vfm;
        }
        else
        {
            LOGWARNING("Config file not loaded");
            LOGINFO("Loaded options:\n" << getParameterDescription(fileConfig, vm));

            if (vm.count("help"))
            {
                std::cout << fileConfig << std::endl;
            }
        }
    }
    catch(std::exception& e)
    {
        LOGASSERT(false, "Unhandled exception: " << e.what());
    }



    Logger::getInstance()->cleanUp();
    return 0;
}
Ejemplo n.º 16
0
void getProcessInfo(const char * name, cgmProcessInfo * procInfo)
{
	NTSTATUS rc = 0;
	DWORD len = MAX_PATH;
	ULONG retLen = 0;

	char * p= 0;
	char * start=0;

//	PROCESS_BASIC_INFORMATION pbInfo;
//	PEB pebInfo;
//	pfnNtQueryInformationProcess gNtQueryInformationProcess;
//	HMODULE hNtDll;
//	RTL_USER_PROCESS_PARAMETERS rtl;
	//UNICODE_STRING commandLine;
	//UNICODE_STRING imagePath;

	//WCHAR *commandLineContents;
	//WCHAR *imagePathContents;

	PROCESS_MEMORY_COUNTERS memoryCounters;
	HANDLE hProcess = NULL;

	DWORD werFault = 0;

	DWORD processID = 0;

	if (procInfo == NULL)
	{
		debug_log(LOG_ERR, "getProcessInfo(): Invalid procInfo handle.");
		return;
	}

	memset(procInfo, 0, sizeof(cgmProcessInfo));

	werFault = getProcessID("WerFault.exe");
	processID = getProcessID(name);

	procInfo->processID = processID;
	procInfo->werFaultID = werFault;

	if (procInfo->processID == 0)
	{
		debug_log(LOG_SVR, "getProcessInfo(): unable to find process: %s, processId: %d, werFault: %d", name, procInfo->processID, procInfo->werFaultID);
		return;
	}

    //hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID );
	hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processID );

	
	if (hProcess != NULL)
	{
		strcpy_s(procInfo->szProcessName, sizeof(procInfo->szProcessName), name);

		// -----------------
		// Get Handle Count.
		// -----------------
		procInfo->handleCount = 0;
		rc = GetProcessHandleCount(hProcess, &procInfo->handleCount);
		if (rc == 0)
		{
			debug_log(LOG_ERR, "getProcessInfo(): unable to retrieve handle count for process: \'%s\', rc: %d", name, GetLastError());
			procInfo->handleCount = 0;
			CloseHandle(hProcess);
			return;
		}

		// --------------------------------
		// Get the size of the Working Set.
		// --------------------------------
		procInfo->workingSetSize = 0;
		memset(&memoryCounters, 0, sizeof(memoryCounters));
		rc = GetProcessMemoryInfo(hProcess, &memoryCounters, sizeof(memoryCounters));
		if (rc == 0)
		{
			debug_log(LOG_ERR, "getProcessInfo(): unable to retrieve the size of the working set for process: \'%s\', rc: %d", name, GetLastError());
			procInfo->workingSetSize = 0;
			CloseHandle(hProcess);
			return;
		}

		procInfo->workingSetSize = memoryCounters.WorkingSetSize;
/*
		hNtDll = LoadLibrary(_T("ntdll.dll"));
		if (hNtDll == NULL) 
		{
			debug_log("getProcessInfo(): Unable to load ntdll.dll");
			CloseHandle(hProcess);
			return;
		}

		gNtQueryInformationProcess = (pfnNtQueryInformationProcess) GetProcAddress(hNtDll, "NtQueryInformationProcess");

		if(gNtQueryInformationProcess == NULL) 
		{
			debug_log("getProcessInfo(): NtQueryInformationProcess() call failed.");
			FreeLibrary(hNtDll);
			CloseHandle(hProcess);
			return ;
		}

		rc = gNtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbInfo, sizeof(pbInfo), &retLen);
		if(pbInfo.PebBaseAddress == NULL)
		{
			debug_log("getProcessInfo(): PEB address is null.");
			FreeLibrary(hNtDll);
			CloseHandle(hProcess);
			return;
		}

		// ------------------------------------------------------------------------------
		// We need to read PEB of the process to find out the command line and full path.
		// ------------------------------------------------------------------------------
		if(pbInfo.PebBaseAddress)
		{
			if(ReadProcessMemory(hProcess, pbInfo.PebBaseAddress, &pebInfo, sizeof(pebInfo) , NULL))
			{
				if(ReadProcessMemory(hProcess, pebInfo.ProcessParameters, &rtl, sizeof(rtl) , NULL))
				{
					rc = ReadProcessMemory(hProcess, &rtl.CommandLine, &commandLine, sizeof(commandLine), NULL);
				
					if(rc != 0 || (rc == 0 && GetLastError() == ERROR_PARTIAL_COPY))
					{
						// allocate memory to hold the command line 
						commandLineContents = (WCHAR *)malloc(rtl.CommandLine.Length);

						// read the command line 
						if (!ReadProcessMemory(hProcess, rtl.CommandLine.Buffer,
							commandLineContents, rtl.CommandLine.Length, NULL))
						{
							debug_log("getProcessInfo(): Could not read the command line string!");
							free(commandLineContents);
							FreeLibrary(hNtDll);
							CloseHandle(hProcess);
							return ;
						}

						if (rtl.CommandLine.Length < sizeof(procInfo->szCmd))
							wcstombs(procInfo->szCmd, commandLineContents, rtl.CommandLine.Length);

						free(commandLineContents);
					} else
					{
						debug_log("getProcessInfo(): Failed to read PEBs command line, rc: %d", GetLastError());
					}

					rc = ReadProcessMemory(hProcess, &rtl.ImagePathName, &imagePath, sizeof(imagePath), NULL);
					if(rc != 0 || (rc == 0 && GetLastError() == ERROR_PARTIAL_COPY))
					{
						// allocate memory to hold the image path 
						imagePathContents = (WCHAR *)malloc(rtl.ImagePathName.Length);

						// read the path 
						if (!ReadProcessMemory(hProcess, rtl.ImagePathName.Buffer,
							imagePathContents, rtl.ImagePathName.Length, NULL))
						{
							debug_log("getProcessInfo(): Could not read the image path line string!");
							free(imagePathContents);
							FreeLibrary(hNtDll);
							CloseHandle(hProcess);
							return ;
						}

						if (rtl.ImagePathName.Length < sizeof(procInfo->szImage))
							wcstombs(procInfo->szImage, imagePathContents, rtl.ImagePathName.Length);

						free(imagePathContents);

						start = procInfo->szImage;
						p = strstr(procInfo->szImage, name);
						if (p != NULL)
							strncpy(procInfo->szCWD, start, p-start);
					} else
					{
						debug_log("getProcessInfo(): Failed to read PEBs image path line, rc: %d", GetLastError());
					}
				}
			}
		}

		FreeLibrary(hNtDll);		
	*/

		CloseHandle(hProcess);
	} else
	{
		debug_log(LOG_ERR, "getProcessInfo(): unable to open process: \'%s\', rc: %d", name, GetLastError());
		return;
	}
}
Ejemplo n.º 17
0
BOOL CProcessTool::GetProcessExtendInfo(PSYSTEM_PROCESS_INFORMATION pSPI,PPROCESS_EXTEND_INFO pExtendInfo)
{
	HANDLE hProcess;
	TCHAR szBuf[2048] ={0};

	memset(pExtendInfo,0,sizeof(PPROCESS_EXTEND_INFO));

	hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pSPI->UniqueProcessId);
	if(hProcess==NULL)return FALSE;

	//Get Exe Path,Description,Company Name
	if(GetModuleFileNameEx(hProcess,NULL,szBuf,MAX_PATH)!=0)
	{
		pExtendInfo->strExeFilePath = szBuf;
		GetFileDescription(szBuf,pExtendInfo->strDescription,
			pExtendInfo->strCompanyName);
	}

	//Get Virtual Memory Size
	PROCESS_MEMORY_COUNTERS pmc;
	if(GetProcessMemoryInfo(hProcess,&pmc,sizeof(PROCESS_MEMORY_COUNTERS)))
	{
		pExtendInfo->dwVirtualMemorySize = pmc.PagefileUsage;
	}


	//Get Parent Process File Path
	HANDLE hParent =NULL;
	hParent = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION,
		FALSE,pSPI->InheritedFromUniqueProcessId);
	if(hParent!=NULL)
	{
		memset(szBuf,0,sizeof(szBuf));
		if(GetModuleFileNameEx(hParent,NULL,szBuf,MAX_PATH)!=0)
		{
			pExtendInfo->strParentFilePath = szBuf;
		}
	}

	//Get Username
	if(WinStationGetProcessSid&&CachedGetUserFromSid)
	{
		wchar_t wcsUserName[100]={0};
		char mbsUserName[100]={0};
		size_t NumOfCharConverted;

		DWORD dwSize = sizeof(szBuf)/sizeof(TCHAR);
		FILETIME ftStartTime;
		CopyMemory(&ftStartTime,&pSPI->CreateTime,sizeof(FILETIME));
		if(WinStationGetProcessSid(NULL,pSPI->UniqueProcessId,ftStartTime,
			(LPBYTE)szBuf,&dwSize))
		{
			CachedGetUserFromSid(szBuf,wcsUserName,&dwSize);
#ifdef _UNICODE
			pExtendInfo->strUserName = wcsUserName;
#else
			wcstombs_s(&NumOfCharConverted,mbsUserName,wcsUserName,
				sizeof(mbsUserName));
			pExtendInfo->strUserName = mbsUserName;
#endif
		}

	}
	//Get Start time
	{
		SYSTEMTIME st;
		ZeroMemory(&st,sizeof(SYSTEMTIME));
		FileTimeToSystemTime((FILETIME *)&pSPI->CreateTime,&st);
		CTime Time(st);

		Time +=CTimeSpan(0,8,0,0);
		pExtendInfo->strStartTime = Time.Format(TEXT("%Y-%m-%d %H:%M:%S"));
	}
	


	return TRUE;
}
Ejemplo n.º 18
0
int CollectorWin::preCollect(const CollectorHints& hints, uint64_t /* iTick */)
{
    LogFlowThisFuncEnter();

    uint64_t user, kernel, idle, total;
    int rc = getRawHostCpuLoad(&user, &kernel, &idle);
    if (RT_FAILURE(rc))
        return rc;
    total = user + kernel + idle;

    DWORD dwError;
    const CollectorHints::ProcessList& processes = hints.getProcessFlags();
    CollectorHints::ProcessList::const_iterator it;

    mProcessStats.clear();

    for (it = processes.begin(); it != processes.end() && RT_SUCCESS(rc); ++it)
    {
        RTPROCESS process = it->first;
        HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                               FALSE, process);

        if (!h)
        {
            dwError = GetLastError();
            Log (("OpenProcess() -> 0x%x\n", dwError));
            rc = RTErrConvertFromWin32(dwError);
            break;
        }

        VMProcessStats vmStats;
        RT_ZERO(vmStats);
        if ((it->second & COLLECT_CPU_LOAD) != 0)
        {
            FILETIME ftCreate, ftExit, ftKernel, ftUser;
            if (!GetProcessTimes(h, &ftCreate, &ftExit, &ftKernel, &ftUser))
            {
                dwError = GetLastError();
                Log (("GetProcessTimes() -> 0x%x\n", dwError));
                rc = RTErrConvertFromWin32(dwError);
            }
            else
            {
                vmStats.cpuKernel = FILETTIME_TO_100NS(ftKernel);
                vmStats.cpuUser   = FILETTIME_TO_100NS(ftUser);
                vmStats.cpuTotal  = total;
            }
        }
        if (RT_SUCCESS(rc) && (it->second & COLLECT_RAM_USAGE) != 0)
        {
            PROCESS_MEMORY_COUNTERS pmc;
            if (!GetProcessMemoryInfo(h, &pmc, sizeof(pmc)))
            {
                dwError = GetLastError();
                Log (("GetProcessMemoryInfo() -> 0x%x\n", dwError));
                rc = RTErrConvertFromWin32(dwError);
            }
            else
                vmStats.ramUsed = pmc.WorkingSetSize;
        }
        CloseHandle(h);
        mProcessStats[process] = vmStats;
    }

    LogFlowThisFuncLeave();

    return rc;
}
Ejemplo n.º 19
0
int main ( int argc, char ** argv )
{
	if ( argc==2 )
		COMMIT_STEP = atoi ( argv[1] );

	// threads should be initialized before memory allocations
	char cTopOfMainStack;
	sphThreadInit();
	MemorizeStack ( &cTopOfMainStack );

	CSphString sError;
	CSphDictSettings tDictSettings;
	tDictSettings.m_bWordDict = false;

	ISphTokenizer * pTok = sphCreateUTF8Tokenizer();
	CSphDict * pDict = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt1", sError );
	CSphSource_MySQL * pSrc = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, "
		"title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=0", pTok, pDict );

	ISphTokenizer * pTok2 = sphCreateUTF8Tokenizer();
	CSphDict * pDict2 = sphCreateDictionaryCRC ( tDictSettings, NULL, pTok, "rt2", sError );
	CSphSource_MySQL * pSrc2 = SpawnSource ( "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, "
		"title, UNCOMPRESS(content) content FROM posting WHERE id<=10000 AND id%2=1", pTok2, pDict2 );

	CSphSchema tSrcSchema;
	if ( !pSrc->UpdateSchema ( &tSrcSchema, sError ) )
		sphDie ( "update-schema failed: %s", sError.cstr() );

	CSphSchema tSchema; // source schema must be all dynamic attrs; but index ones must be static
	tSchema.m_dFields = tSrcSchema.m_dFields;
	for ( int i=0; i<tSrcSchema.GetAttrsCount(); i++ )
		tSchema.AddAttr ( tSrcSchema.GetAttr(i), false );
	g_iFieldsCount = tSrcSchema.m_dFields.GetLength();

	CSphConfigSection tRTConfig;
	sphRTInit ( tRTConfig, true );
	sphRTConfigure ( tRTConfig, true );
	SmallStringHash_T< CSphIndex * > dTemp;
	sphReplayBinlog ( dTemp, 0 );
	ISphRtIndex * pIndex = sphCreateIndexRT ( tSchema, "testrt", 32*1024*1024, "data/dump", false );
	pIndex->SetTokenizer ( pTok ); // index will own this pair from now on
	pIndex->SetDictionary ( pDict );
	if ( !pIndex->Prealloc ( false ) )
		sphDie ( "prealloc failed: %s", pIndex->GetLastError().cstr() );
	pIndex->PostSetup();
	g_pIndex = pIndex;

	// initial indexing
	int64_t tmStart = sphMicroTimer();

	SphThread_t t1, t2;
	sphThreadCreate ( &t1, IndexingThread, pSrc );
	sphThreadCreate ( &t2, IndexingThread, pSrc2 );
	sphThreadJoin ( &t1 );
	sphThreadJoin ( &t2 );

#if 0
	// update
	tParams.m_sQuery = "SELECT id, channel_id, UNIX_TIMESTAMP(published) published, title, "
		"UNCOMPRESS(content) content FROM rt2 WHERE id<=10000";
	SetupIndexing ( pSrc, tParams );
	DoIndexing ( pSrc, pIndex );
#endif

	// search
	DoSearch ( pIndex );

	// shutdown index (should cause dump)
	int64_t tmShutdown = sphMicroTimer();

#if SPH_ALLOCS_PROFILER
	printf ( "pre-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() );
#endif
	SafeDelete ( pIndex );
#if SPH_ALLOCS_PROFILER
	printf ( "post-shutdown allocs=%d, bytes=" INT64_FMT "\n", sphAllocsCount(), sphAllocBytes() );
#endif

	int64_t tmEnd = sphMicroTimer();
	printf ( "shutdown done in %d.%03d sec\n", (int)((tmEnd-tmShutdown)/1000000), (int)(((tmEnd-tmShutdown)%1000000)/1000) );
	printf ( "total with shutdown %d.%03d sec, %.2f MB/sec\n",
		(int)((tmEnd-tmStart)/1000000), (int)(((tmEnd-tmStart)%1000000)/1000),
		g_fTotalMB*1000000.0f/(tmEnd-tmStart) );

#if SPH_DEBUG_LEAKS || SPH_ALLOCS_PROFILER
	sphAllocsStats();
#endif
#if USE_WINDOWS
	PROCESS_MEMORY_COUNTERS pmc;
	HANDLE hProcess = OpenProcess ( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
	if ( hProcess && GetProcessMemoryInfo ( hProcess, &pmc, sizeof(pmc)) )
	{
		printf ( "--- peak-wss=%d, peak-pagefile=%d\n", (int)pmc.PeakWorkingSetSize, (int)pmc.PeakPagefileUsage );
	}
#endif

	SafeDelete ( pIndex );
	sphRTDone ();
}
Ejemplo n.º 20
0
    void DebugActor::render(RenderState const& parentRS)
    {
        timeMS tm = getTimeMS();

        static int fps = 0;
        ++_frames;
        if (_frames > 50)
        {
            if (tm != _startTime)
            {
                fps = int(((float)_frames / (tm - _startTime)) * 1000);
            }
            _startTime = tm;
            _frames = 0;
        }

        std::stringstream s;
        s << "fps=" << fps << std::endl;



#ifdef __S3E__
        int mem_used = -1;
        int mem_free = -1;

        mem_used = s3eMemoryGetInt(S3E_MEMORY_USED);
        mem_free = s3eMemoryGetInt(S3E_MEMORY_FREE);

        s << "mfree=" << mem_free << " mem=" << mem_used << std::endl;
#endif

        const IVideoDriver::Stats& vstats = IVideoDriver::_stats;

#ifdef OXYGINE_DEBUG_TRACE_LEAKS
        s << "objects=" << (int)ObjectBase::__getCreatedObjects().size() << std::endl;
#endif

#if OXYGINE_TRACE_VIDEO_STATS
        int primitives = 0;
        primitives += vstats.elements[IVideoDriver::PT_TRIANGLES] / 3;
        if (vstats.elements[IVideoDriver::PT_TRIANGLE_STRIP])
            primitives += vstats.elements[IVideoDriver::PT_TRIANGLE_STRIP] - 2;
        s << "batches=" << aligned(vstats.batches, 3) << " primitives=" << aligned(primitives, 3) << std::endl;
#endif

        s << "update=" << aligned(getStage()->_statUpdate, 2) << "ms ";
        s << "render=" << aligned(vstats.duration, 2) << "ms ";
        s << "textures=" << aligned(NativeTexture::created, 2) << " ";

#ifdef __APPLE__
        size_t mem;
        iosGetMemoryUsage(mem);
        s << "memory=" << mem / 1024 << "kb ";
#endif

#ifdef _WIN32
        PROCESS_MEMORY_COUNTERS_EX pmc;
        GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*) &pmc, sizeof(pmc));
        s << "memory=" << pmc.PrivateUsage / 1024 << "kb ";

#endif

        if (!_debugText.empty())
        {
            s << "\n";
            s << _debugText;
        }
        _debugText = "";

        _text->setText(s.str());


        setHeight(_text->getTextRect().size.y + _text->getY() + 3);
        _bg->setSize(getSize());


        Vector2 ds = core::getDisplaySize();

        Vector2 pos(0, 0);

        switch (_corner)
        {
            case 1:
                pos.x = ds.x;
                break;
            case 2:
                pos = ds;
                break;
            case 3:
                pos.y = ds.y;
                break;
        }

        pos = getStage()->parent2local(pos);

        Vector2 realSize = getScaledSize();
        switch (_corner)
        {
            case 1:
                pos.x -= realSize.x;
                break;
            case 2:
                pos -= realSize;
                break;
            case 3:
                pos.y -= realSize.y;
                break;
        }

        //setPosition(pos);
        setScale(1.0f / getStage()->getScaleX());

        RenderState rs = parentRS;
        parentRS.material->finish();

        STDRenderer renderer;
        STDMaterial mat(&renderer);
        mat.apply(0);


        IVideoDriver* driver = renderer.getDriver();


        Rect vp(Point(0, 0), core::getDisplaySize());
        driver->setViewport(vp);
        renderer.initCoordinateSystem(vp.getWidth(), vp.getHeight());
        renderer.resetSettings();
        rs.material = &mat;
        Actor::render(rs);
        renderer.drawBatch();

        mat.finish();

        Material::setCurrent(0);

        timeMS dur = getTimeMS() - tm;

        IVideoDriver::_stats.start += dur;
    }