Example #1
0
int main(int argc, char *argv[]) {

  if (argc != 3) {
    printf ("\nUsage: gcd <num 1> <num 2>\n");
    return 0;
  }

  printf ("\ngcd(%s, %s) = %lld", 
    argv[1], argv[2], 
    gcd (_strtoui64(argv[1], NULL, 10), 
      _strtoui64(argv[2], NULL, 10)));
  return 0;
}
Example #2
0
	vuint64_t atou64_test(const AString& string, bool& success)
	{
		char* endptr = 0;
		vuint64_t result = _strtoui64(string.Buffer(), &endptr, 10);
		success = endptr == string.Buffer() + string.Length() && u64toa(result) == string;
		return result;
	}
Example #3
0
// =================================================================================
// Parser
// =================================================================================
int ini_natives_parser(void* pCustom, const char* sSection, const char* sName, const char* sValue)
{
	// find category
	Natives::eNativeCategory eCategory = Natives::FindCategoryByName(const_cast<char*>(sSection));

	// check
	if (eCategory == Natives::NATIVE_UNKNOWN)
	{
		printf("[natives.ini] Unknown category %s\n", sSection);
		return 1;
	}

	// add to registered natives
	Natives::NativeReg* reg = new Natives::NativeReg();
	reg->bValid = true;
	reg->hHash = _strtoui64(sValue, NULL, 0);
	reg->sName = _strdup(sName);
	reg->sCategory = Natives::CategoryNames[eCategory]; // as they are static no need to copy anything
	reg->bHasCallLayout = false;
	reg->sCallLayout = NULL;

	// register
	Natives::Registered[eCategory].push_back(reg);
	return 1;
} 
Example #4
0
Bool
StrUtil_StrToSizet(size_t *out,     // OUT: The output value
                   const char *str) // IN : String to parse
{
   char *ptr;

   ASSERT(out);
   ASSERT(str);

   errno = 0;
#if defined VM_X86_64
   ASSERT_ON_COMPILE(sizeof *out == sizeof(uint64));
#   if defined(_WIN32)
   *out = _strtoui64(str, &ptr, 0);
#   elif defined(__FreeBSD__)
   *out = strtouq(str, &ptr, 0);
#   else
   *out = strtoull(str, &ptr, 0);
#   endif
#else
   ASSERT_ON_COMPILE(sizeof *out == sizeof(uint32));
   *out = strtoul(str, &ptr, 0);
#endif

   return *ptr == '\0' && errno != ERANGE;
}
Example #5
0
    static unsigned long long str_to_int(const char* str) {
#ifdef _MSC_VER
        return _strtoui64(str, nullptr, 10);
#else
        return std::strtoull(str, nullptr, 10);
#endif
    }
Example #6
0
uint64 Str2UInt64(const char* str)
{
#ifdef __WINDOWS
	return str != NULL ? _strtoui64(str, NULL, 10) : 0;
#else
	return str != NULL ? strtol(str, NULL, 10) : 0;
#endif
}
Example #7
0
int main(int argc, char *argv[]) {
  
  uint64_t result=0;
  
  if (argc != 4) {
    printf ("\nUsage: modexp <base> <exponent> <modulus>\n");
    return 0;
  }
  
  result = modexp (_strtoui64(argv[1], NULL, 10), 
    _strtoui64(argv[2], NULL, 10),
    _strtoui64(argv[3], NULL, 10)); 

  printf ("\n%llu = %s ^ %s %% %s", 
    result, argv[1], argv[2], argv[3]);
  return 0;
}
Example #8
0
SAWYER_EXPORT boost::uint64_t
strtoull(const char *input, char **rest, int base) {
#ifdef _MSC_VER
    return _strtoui64(input, rest, base);
#else
    return ::strtoull(input, rest, base);
#endif
}
Example #9
0
u64 CInifile::r_u64(LPCSTR S, LPCSTR L)
{
    LPCSTR		C = r_string(S,L);
#ifndef _EDITOR
    return		_strtoui64(C,NULL,10);
#else
    return		(u64)_atoi64(C);
#endif
}
Example #10
0
	static inline unsigned long long hexStrToU64(const char *s)
		throw()
	{
#ifdef __WINDOWS__
		return (unsigned long long)_strtoui64(s,(char **)0,16);
#else
		return strtoull(s,(char **)0,16);
#endif
	}
Example #11
0
bool to_uint64(char const * s, uint64_t & i)
{
  char * stop;
#ifdef OMIM_OS_WINDOWS_NATIVE
  i = _strtoui64(s, &stop, 10);
#else
  i = strtoull(s, &stop, 10);
#endif
  return *stop == 0 && s != stop;
}
Example #12
0
UINT64 YamlLoadHelper::LoadUint64(const std::string key)
{
	bool bFound;
	std::string value = m_yamlHelper.GetMapValue(*m_pMapYaml, key, bFound);
	if (value == "")
	{
		m_bDoGetMapRemainder = false;
		throw std::string(m_currentMapName + ": Missing: " + key);
	}
	return _strtoui64(value.c_str(), NULL, 0);
}
Example #13
0
  bool parse( sim_t*, const std::string& n, const std::string& v ) const override
  {
    if ( n != name() )
      return false;
#if defined( SC_WINDOWS ) && defined( SC_VS )
    _ref = _strtoui64( v.c_str(), nullptr, 10 );
#else
    _ref = strtoull( v.c_str(), nullptr, 10 );
#endif
    return true;
  }
Example #14
0
/**
 * Converts a string representing a number into an unsigned 64 bit number and
 * raises an exception if the conversion fails.
 *
 * The string must have a format of 123456789 or 0xFFAB. A leading 0 without the
 * following X will cause the string to be interpreted as an octal number, which
 * may or may not trigger a failure.  It is not the intent that this function be
 * used for octal numbers.
 *
 * Note that it is the use of 0 as the third argument that allows _strtoui64()
 * to interpret the string as decimal or hexadecimal based.
 *
 * @param c       Method context we are operating in.
 * @param str     String to convert.
 * @param number  [OUT]  Converted number is returned here.
 * @param pos     Argument position.  Used for exception.
 *
 * @return True if the number was converted, false if an exceptions is raised.
 *
 * @note  There is no way to tell the difference between a valid _UI64_MAX
 *        number and an error.  The function simply assumes a return of
 *        _UI64_MAX is an error signal.
 */
bool rxStr2Number(RexxMethodContext *c, CSTRING str, uint64_t *number, size_t pos)
{
    char *end;
    *number = _strtoui64(str, &end, 0);
    if ( (end - str != strlen(str)) || errno == EINVAL || *number == _UI64_MAX )
    {
        invalidTypeException(c->threadContext, pos, " number");
        return false;
    }
    return true;
}
Example #15
0
/*
 * pg_strtouint64
 *		Converts 'str' into an unsigned 64-bit integer.
 *
 * This has the identical API to strtoul(3), except that it will handle
 * 64-bit ints even where "long" is narrower than that.
 *
 * For the moment it seems sufficient to assume that the platform has
 * such a function somewhere; let's not roll our own.
 */
uint64
pg_strtouint64(const char *str, char **endptr, int base)
{
#ifdef _MSC_VER					/* MSVC only */
	return _strtoui64(str, endptr, base);
#elif defined(HAVE_STRTOULL) && SIZEOF_LONG < 8
	return strtoull(str, endptr, base);
#else
	return strtoul(str, endptr, base);
#endif
}
Example #16
0
static VOID
__ReadDiskInfo(
    IN  PXENVBD_FRONTEND        Frontend
    )
{
    NTSTATUS    Status;
    PCHAR       Buffer;
    BOOLEAN     Updated = FALSE;

    Status = StoreRead(NULL, Frontend->BackendPath, 
                        "info", &Buffer);
    if (NT_SUCCESS(Status)) {
        Frontend->DiskInfo = strtoul(Buffer, NULL, 10);
        AustereFree(Buffer);
        Updated = TRUE;
    }

    Status = StoreRead(NULL, Frontend->BackendPath, 
                        "sector-size", &Buffer);
    if (NT_SUCCESS(Status)) {
        Frontend->SectorSize = strtoul(Buffer, NULL, 10);
        AustereFree(Buffer);
        Updated = TRUE;
    }

    Status = StoreRead(NULL, Frontend->BackendPath, 
                        "sectors", &Buffer);
    if (NT_SUCCESS(Status)) {
        Frontend->SectorCount = _strtoui64(Buffer, NULL, 10);
        AustereFree(Buffer);
        Updated = TRUE;
    }

    if (Frontend->SectorCount == 0) {
        LogError("Invalid SectorCount!\n");
    }
    if (Frontend->SectorSize == 0) {
        LogError("Invalid SectorSize!\n");
    }
    if (Updated) {
        LogVerbose("DiskInfo: %08x, %lld sectors of %d bytes (%lld KB or %lld MB)\n", 
                    Frontend->DiskInfo, Frontend->SectorCount, Frontend->SectorSize, 
                    (Frontend->SectorSize * Frontend->SectorCount) / 1024,
                    (Frontend->SectorSize * Frontend->SectorCount) / (1024 * 1024));
    }
    if (Frontend->DiskInfo & VDISK_READONLY) {
        LogWarning("DiskInfo contains VDISK_READONLY flag!\n");
    }
    if (Frontend->DiskInfo & VDISK_CDROM) {
        LogWarning("DiskInfo contains VDISK_CDROM flag!\n");
    }
}
Example #17
0
BOOL CBuildProgram::UpdatedDbCheckSumInfo(PSNODEINFO psInfo)
{
    ICluster* pCluster = nullptr;
    m_pGlobalObj->m_ouClusterConfig->GetDBService(m_eBus, 0, 0, &pCluster);
    if (nullptr != pCluster)
    {
        std::string strChecksum;
        pCluster->GetDBFileChecksum(strChecksum);
        psInfo->m_ouLastDBChecksum = _strtoui64(strChecksum.c_str(), nullptr, 16);
    }

    return TRUE;
}
Example #18
0
File: odr_mem.c Project: nla/yaz
Odr_int odr_strtol(const char *nptr, char **endptr, int base)
{
#if NMEM_64
#if WIN32
    return _strtoui64(nptr, endptr, base);
#else
    return strtoll(nptr, endptr, base);
#endif

#else
    return strtol(nptr, endptr, base);
#endif
}
Example #19
0
bool RakNetGUID::FromString(const char *source)
{
	if (source==0)
		return false;

#if defined(_XBOX) || defined(_X360)
                   
#elif defined(WIN32)
	g=_strtoui64(source, (char **)NULL, 10);
#else
	g=strtoull (source, (char **)NULL, 10);
#endif
	return true;

}
Example #20
0
Bool
StrUtil_StrToUint64(uint64 *out,     // OUT: The output value
                    const char *str) // IN : String to parse
{
   char *ptr;

   ASSERT(out);
   ASSERT(str);

   errno = 0;

#if defined(_WIN32)
   *out = _strtoui64(str, &ptr, 0);
#elif defined(__FreeBSD__)
   *out = strtouq(str, &ptr, 0);
#else
   *out = strtoull(str, &ptr, 0);
#endif

   return ptr[0] == '\0' && errno != ERANGE && errno != EINVAL;
}
Example #21
0
uint64_t TRI_UInt64String (char const* str) {
  uint64_t result;
  char* endptr;

#if defined(TRI_HAVE_STRTOULL_R)
  struct reent buffer;
#elif defined(TRI_HAVE__STRTOULL_R)
  struct reent buffer;
#endif

  TRI_set_errno(TRI_ERROR_NO_ERROR);

#if defined(TRI_HAVE_STRTOULL_R)
  result = strtoull_r(&buffer, str, &endptr, 10);
#elif defined(TRI_HAVE__STRTOULL_R)
  result = _strtoull_r(&buffer, str, &endptr, 10);
#elif defined(TRI_HAVE_STRTOUI64)
  result = _strtoui64(str, &endptr, 10);
#elif defined(TRI_HAVE_STRTOULL)
  result = strtoull(str, &endptr, 10);
#else
#warning cannot convert string to int64
#endif

  while (isspace(*endptr)) {
    ++endptr;
  }

  if (*endptr != '\0') {
    TRI_set_errno(TRI_ERROR_ILLEGAL_NUMBER);
  }

  if (errno == ERANGE && (result == 0 || result == UINT64_MAX)) {
    TRI_set_errno(TRI_ERROR_NUMERIC_OVERFLOW);
  }

  return result;
}
Example #22
0
/*
 * Parse string as uint64
 * valid range: 0 ~ (2^64-1)
 */
bool
parse_uint64(const char *value, uint64 *result)
{
	uint64	val;
	char   *endptr;

	if (strcmp(value, INFINITE_STR) == 0)
	{
#if defined(HAVE_LONG_INT_64)
		*result = ULONG_MAX;
#elif defined(HAVE_LONG_LONG_INT_64)
		*result = ULLONG_MAX;
#else
		*result = ULONG_MAX;
#endif
		return true;
	}

	errno = 0;
#ifdef WIN32
	val = _strtoui64(value, &endptr, 0);
#elif defined(HAVE_LONG_INT_64)
	val = strtoul(value, &endptr, 0);
#elif defined(HAVE_LONG_LONG_INT_64)
	val = strtoull(value, &endptr, 0);
#else
	val = strtoul(value, &endptr, 0);
#endif
	if (endptr == value || *endptr)
		return false;

	if (errno == ERANGE)
		return false;

	*result = val;

	return true;
}
Example #23
0
int main(int argc, char** argv)
{
	const char* cmd;
	uint64_t tai;
	const char* iso;

	if (argc < 3) {
		usage();
		return(1);
	}

	cmd = argv[1];

	if (strcmp(cmd, "taiToIso") == 0) {
		struct caltime ct;
		struct tai t;
		char buf[128];
		int len;
		tai = _strtoui64(argv[2], NULL, 10);
		t.x = tai;
		caltime_utc(&ct, &t, 0, 0);
		len = caltime_fmt(buf, &ct);
		buf[len] = '\0';
		printf("ISO: %s\n", buf);
	}
	else if (strcmp(cmd, "isoToTai") == 0) {
		iso = argv[2];
	}
	else {
		usage();
		return(1);
	}



	return(0);
}
Example #24
0
int CCrashInfoReader::Init(CString sCrashInfoFileName)
{ 
  strconv_t strconv;
  ErrorReportInfo eri;
  
  TiXmlDocument doc;
  bool bOpen = doc.LoadFile(strconv.t2a(sCrashInfoFileName));
  if(!bOpen)
    return 1;

  TiXmlHandle hRoot = doc.FirstChild("CrashRptInternal");
  if(hRoot.ToElement()==NULL)
    return 1;

  {    
    TiXmlHandle hUnsentCrashReportsFolder = hRoot.FirstChild("UnsentCrashReportsFolder");
    if(hUnsentCrashReportsFolder.FirstChild().ToText()!=NULL)
    {      
      const char* szUnsentCrashReportsFolder = hUnsentCrashReportsFolder.FirstChild().ToText()->Value();
      if(szUnsentCrashReportsFolder!=NULL)
      {
        m_sUnsentCrashReportsFolder = strconv.utf82t(szUnsentCrashReportsFolder);
        Utility::CreateFolder(m_sUnsentCrashReportsFolder);
        
        m_sINIFile = m_sUnsentCrashReportsFolder + _T("\\~CrashRpt.ini");        
      }
    }
  }  
  
  {
    TiXmlHandle hReportFolder = hRoot.FirstChild("ReportFolder");
    if(hReportFolder.FirstChild().ToText()!=NULL)
    {
      const char* szReportFolder = hReportFolder.FirstChild().ToText()->Value();
      if(szReportFolder!=NULL)
        eri.m_sErrorReportDirName = strconv.utf82t(szReportFolder);
    }
  }

  {
    m_bQueueEnabled = FALSE;
    TiXmlHandle hQueueEnabled = hRoot.FirstChild("QueueEnabled");
    if(hQueueEnabled.FirstChild().ToText()!=NULL)
    {      
      const char* szQueueEnabled = hQueueEnabled.FirstChild().ToText()->Value();
      if(szQueueEnabled!=NULL)
      {
        m_bQueueEnabled = atoi(szQueueEnabled);        
      }
    }
  }  

  {
    m_bSendRecentReports = FALSE;
    TiXmlHandle hSendRecentReports = hRoot.FirstChild("SendRecentReports");
    if(hSendRecentReports.FirstChild().ToText()!=NULL)
    {      
      const char* szSendRecentReports = hSendRecentReports.FirstChild().ToText()->Value();
      if(szSendRecentReports!=NULL)
      {
        m_bSendRecentReports = atoi(szSendRecentReports);        
      }
    }
  }  


  {
    TiXmlHandle hCrashGUID = hRoot.FirstChild("CrashGUID");
    if(hCrashGUID.FirstChild().ToText()!=NULL)
    {
      const char* szCrashGUID = hCrashGUID.FirstChild().ToText()->Value();
      if(szCrashGUID!=NULL)
        eri.m_sCrashGUID = strconv.utf82t(szCrashGUID);
    }
  }

  {
    TiXmlHandle hAppName = hRoot.FirstChild("AppName");
    if(hAppName.FirstChild().ToText()!=NULL)
    {
      const char* szAppName = hAppName.FirstChild().ToText()->Value();
      if(szAppName!=NULL)
        m_sAppName = strconv.utf82t(szAppName);
    }
  }

  {
    TiXmlHandle hLangFileName = hRoot.FirstChild("LangFileName");
    if(hLangFileName.FirstChild().ToText()!=NULL)
    {
      const char* szLangFileName = hLangFileName.FirstChild().ToText()->Value();
      if(szLangFileName!=NULL)
        m_sLangFileName = strconv.utf82t(szLangFileName);
    }
  }

  {
    TiXmlHandle hDbgHelpPath = hRoot.FirstChild("DbgHelpPath");
    if(hDbgHelpPath.FirstChild().ToText()!=NULL)
    {
      const char* szDbgHelpPath = hDbgHelpPath.FirstChild().ToText()->Value();
      if(szDbgHelpPath!=NULL)
        m_sDbgHelpPath = strconv.utf82t(szDbgHelpPath);
    }
  }

  {
    m_bGenerateMinidump = TRUE;
    TiXmlHandle hGenerateMinidump = hRoot.FirstChild("GenerateMinidump");
    if(hGenerateMinidump.FirstChild().ToText()!=NULL)
    {
      const char* szGenerateMinidump = hGenerateMinidump.FirstChild().ToText()->Value();
      if(szGenerateMinidump!=NULL)
        m_bGenerateMinidump = (MINIDUMP_TYPE)atol(szGenerateMinidump);      
    }    
  }

  {
    TiXmlHandle hMinidumpType = hRoot.FirstChild("MinidumpType");
    if(hMinidumpType.FirstChild().ToText()!=NULL)
    {
      const char* szMinidumpType = hMinidumpType.FirstChild().ToText()->Value();
      if(szMinidumpType!=NULL)
        m_MinidumpType = (MINIDUMP_TYPE)atol(szMinidumpType);
      else
        m_MinidumpType = MiniDumpNormal;
    }
    else
      m_MinidumpType = MiniDumpNormal;
  }

  {
    TiXmlHandle hUrl = hRoot.FirstChild("Url");
    if(hUrl.FirstChild().ToText()!=NULL)
    {
      const char* szUrl = hUrl.FirstChild().ToText()->Value();
      if(szUrl!=NULL)
        m_sUrl = strconv.utf82t(szUrl);
    }
  }

  {
    TiXmlHandle hEmailTo = hRoot.FirstChild("EmailTo");
    if(hEmailTo.FirstChild().ToText()!=NULL)
    {
      const char* szEmailTo = hEmailTo.FirstChild().ToText()->Value();
      if(szEmailTo!=NULL)
        m_sEmailTo = strconv.utf82t(szEmailTo);
    }
  }

  {
    m_nSmtpPort = 25;
    TiXmlHandle hSmtpPort = hRoot.FirstChild("SmtpPort");
    if(hSmtpPort.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpPort = hSmtpPort.FirstChild().ToText()->Value();
      if(szSmtpPort!=NULL)
        m_nSmtpPort = atoi(szSmtpPort);
    }
  }

  {
    TiXmlHandle hEmailSubject = hRoot.FirstChild("EmailSubject");
    if(hEmailSubject.FirstChild().ToText()!=NULL)
    {
      const char* szEmailSubject = hEmailSubject.FirstChild().ToText()->Value();
      if(szEmailSubject!=NULL)
        m_sEmailSubject = strconv.utf82t(szEmailSubject);
    }
  }

  {
    TiXmlHandle hEmailText = hRoot.FirstChild("EmailText");
    if(hEmailText.FirstChild().ToText()!=NULL)
    {
      const char* szEmailText = hEmailText.FirstChild().ToText()->Value();
      if(szEmailText!=NULL)
        m_sEmailText = strconv.utf82t(szEmailText);
    }
  }

  {
    TiXmlHandle hPrivacyPolicyUrl = hRoot.FirstChild("PrivacyPolicyUrl");    
    if(hPrivacyPolicyUrl.FirstChild().ToText()!=NULL)
    {
      const char* szPrivacyPolicyUrl = hPrivacyPolicyUrl.FirstChild().ToText()->Value();
      if(szPrivacyPolicyUrl!=NULL)
        m_sPrivacyPolicyURL = strconv.utf82t(szPrivacyPolicyUrl);
    }
  }

  {
    TiXmlHandle hHttpPriority = hRoot.FirstChild("HttpPriority");
    if(hHttpPriority.FirstChild().ToText()!=NULL)
    {
      const char* szHttpPriority = hHttpPriority.FirstChild().ToText()->Value();
      if(szHttpPriority!=NULL)
        m_uPriorities[CR_HTTP] = atoi(szHttpPriority);
      else
        m_uPriorities[CR_HTTP] = 0;
    }
  }

  {
    TiXmlHandle hSmtpPriority = hRoot.FirstChild("SmtpPriority");
    if(hSmtpPriority.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpPriority = hSmtpPriority.FirstChild().ToText()->Value();
      if(szSmtpPriority!=NULL)
        m_uPriorities[CR_SMTP] = atoi(szSmtpPriority);
      else
        m_uPriorities[CR_SMTP] = 0;
    }
  }

  {
    TiXmlHandle hMapiPriority = hRoot.FirstChild("MapiPriority");
    if(hMapiPriority.FirstChild().ToText()!=NULL)
    {
      const char* szMapiPriority = hMapiPriority.FirstChild().ToText()->Value();
      if(szMapiPriority!=NULL)
        m_uPriorities[CR_SMAPI] = atoi(szMapiPriority);
      else
        m_uPriorities[CR_SMAPI] = 0;
    }
  }

  {
    TiXmlHandle hProcessId = hRoot.FirstChild("ProcessId");
    if(hProcessId.FirstChild().ToText()!=NULL)
    {
      const char* szProcessId = hProcessId.FirstChild().ToText()->Value();
      if(szProcessId!=NULL)
        m_dwProcessId = strtoul(szProcessId, NULL, 10);
      else
        m_dwProcessId = 0;
    }
  }

  {
    TiXmlHandle hThreadId = hRoot.FirstChild("ThreadId");
    if(hThreadId.FirstChild().ToText()!=NULL)
    {
      const char* szThreadId = hThreadId.FirstChild().ToText()->Value();
      if(szThreadId!=NULL)
        m_dwThreadId = strtoul(szThreadId, NULL, 10);
      else 
        m_dwThreadId = 0;
    }
  }

  {
    m_pExInfo = NULL;
    TiXmlHandle hExceptionPointersAddress = hRoot.FirstChild("ExceptionPointersAddress");
    if(hExceptionPointersAddress.FirstChild().ToText()!=NULL)
    {
      const char* szExceptionPointersAddress = hExceptionPointersAddress.FirstChild().ToText()->Value();
      if(szExceptionPointersAddress!=NULL)
        m_pExInfo = (PEXCEPTION_POINTERS)_strtoui64(szExceptionPointersAddress, NULL, 16);     
    }    
  }

  {
    TiXmlHandle hAddScreenshot = hRoot.FirstChild("AddScreenshot");
    if(hAddScreenshot.FirstChild().ToText()!=NULL)
    {
      const char* szAddScreenshot = hAddScreenshot.FirstChild().ToText()->Value();
      if(szAddScreenshot!=NULL)
        m_bAddScreenshot = strtol(szAddScreenshot, NULL, 10);
      else
        m_bAddScreenshot = FALSE;
    }
  }

  {
    m_dwScreenshotFlags = 0;
    TiXmlHandle hScreenshotFlags = hRoot.FirstChild("ScreenshotFlags");
    if(hScreenshotFlags.FirstChild().ToText()!=NULL)
    {
      const char* szScreenshotFlags = hScreenshotFlags.FirstChild().ToText()->Value();
      if(szScreenshotFlags!=NULL)
        m_dwScreenshotFlags = strtoul(szScreenshotFlags, NULL, 10);        
    }
  }

  {
    m_ptCursorPos.SetPoint(0, 0);
    TiXmlHandle hCursorPos = hRoot.FirstChild("CursorPos");
    if(hCursorPos.ToElement()!=NULL)
    {
      const char* szX = hCursorPos.ToElement()->Attribute("x");
      const char* szY = hCursorPos.ToElement()->Attribute("y");
      if(szX && szY)
      {
        m_ptCursorPos.x = atoi(szX);
        m_ptCursorPos.y = atoi(szY);
      }
    }
  }

  {
    m_rcAppWnd.SetRectEmpty();
    TiXmlHandle hAppWndRect = hRoot.FirstChild("AppWindowRect");
    if(hAppWndRect.ToElement()!=NULL)
    {
      const char* szLeft = hAppWndRect.ToElement()->Attribute("left");
      const char* szTop = hAppWndRect.ToElement()->Attribute("top");
      const char* szRight = hAppWndRect.ToElement()->Attribute("right");
      const char* szBottom = hAppWndRect.ToElement()->Attribute("bottom");

      if(szLeft && szTop && szRight && szBottom)
      {
        m_rcAppWnd.left = atoi(szLeft);
        m_rcAppWnd.top = atoi(szTop);
        m_rcAppWnd.right = atoi(szRight);
        m_rcAppWnd.bottom = atoi(szBottom);
      }
    }
  }

  {
    m_bHttpBinaryEncoding = FALSE;    
    TiXmlHandle hHttpBinaryEncoding = hRoot.FirstChild("HttpBinaryEncoding");
    if(hHttpBinaryEncoding.FirstChild().ToText()!=NULL)
    {
      const char* szHttpBinaryEncoding = hHttpBinaryEncoding.FirstChild().ToText()->Value();
      if(szHttpBinaryEncoding!=NULL)
        m_bHttpBinaryEncoding = atoi(szHttpBinaryEncoding);
    }      
  }

  {
    m_bSilentMode = FALSE;    
    TiXmlHandle hSilentMode = hRoot.FirstChild("SilentMode");
    if(hSilentMode.FirstChild().ToText()!=NULL)
    {
      const char* szSilentMode = hSilentMode.FirstChild().ToText()->Value();
      if(szSilentMode!=NULL)
        m_bSilentMode = atoi(szSilentMode);
    }      
  }

  {
    m_bSendErrorReport = FALSE;    
    TiXmlHandle hSendErrorReport = hRoot.FirstChild("SendErrorReport");
    if(hSendErrorReport.FirstChild().ToText()!=NULL)
    {
      const char* szSendErrorReport = hSendErrorReport.FirstChild().ToText()->Value();
      if(szSendErrorReport!=NULL)
        m_bSendErrorReport = atoi(szSendErrorReport);     
    }      
  }

  {
    m_bAppRestart = FALSE;    
    TiXmlHandle hAppRestart = hRoot.FirstChild("AppRestart");
    if(hAppRestart.FirstChild().ToText()!=NULL)
    {
      const char* szAppRestart = hAppRestart.FirstChild().ToText()->Value();
      if(szAppRestart!=NULL)
        m_bAppRestart = atoi(szAppRestart);     
    }      
  }

  {    
    TiXmlHandle hRestartCmdLine = hRoot.FirstChild("RestartCmdLine");
    if(hRestartCmdLine.FirstChild().ToText()!=NULL)
    {
      const char* szRestartCmdLine = hRestartCmdLine.FirstChild().ToText()->Value();
      if(szRestartCmdLine!=NULL)
        m_sRestartCmdLine = strconv.utf82t(szRestartCmdLine);     
    }      
  }

  {    
    TiXmlHandle hSmtpProxyServer = hRoot.FirstChild("SmtpProxyServer");
    if(hSmtpProxyServer.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpProxyServer = hSmtpProxyServer.FirstChild().ToText()->Value();
      if(szSmtpProxyServer!=NULL)
        m_sSmtpProxyServer = strconv.utf82t(szSmtpProxyServer);     
    }      
  }

  {    
    m_nSmtpProxyPort = 25;
    TiXmlHandle hSmtpProxyPort = hRoot.FirstChild("SmtpProxyPort");
    if(hSmtpProxyPort.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpProxyPort = hSmtpProxyPort.FirstChild().ToText()->Value();
      if(szSmtpProxyPort!=NULL)
        m_nSmtpProxyPort = atoi(szSmtpProxyPort);     
    }      
  }

  if(!m_bSendRecentReports)
  {    
    // Get the list of files that should be included to report
    ParseFileList(hRoot, eri);

    // Get some info from crashrpt.xml
    CString sXmlName = eri.m_sErrorReportDirName + _T("\\crashrpt.xml");
    ParseCrashDescription(sXmlName, FALSE, eri);    
    
    m_Reports.push_back(eri);
  }  
  else
  {
    // Look for unsent error reports
    CString sSearchPattern = m_sUnsentCrashReportsFolder + _T("\\*");
    CFindFile find;
    BOOL bFound = find.FindFile(sSearchPattern);
    while(bFound)
    {
      if(find.IsDirectory() && !find.IsDots())
      {
        CString sErrorReportDirName = m_sUnsentCrashReportsFolder + _T("\\") + 
          find.GetFileName();
        CString sFileName = sErrorReportDirName + _T("\\crashrpt.xml");
        ErrorReportInfo eri;
        eri.m_sErrorReportDirName = sErrorReportDirName;
        if(0==ParseCrashDescription(sFileName, TRUE, eri))
        {          
          eri.m_uTotalSize = GetUncompressedReportSize(eri);
          m_Reports.push_back(eri);
        }
      }

      bFound = find.FindNextFile();
    }
  }
  
  return 0;
}
Example #25
0
unsigned __int64  __stdcall Str264(LPSTR pszString, int base){
	//supports - but doesnt seem to work with 0x prefix? so had to include base arg..
	unsigned __int64 ret = _strtoui64(pszString, NULL, base);
	return ret;
}
Example #26
0
int main(int argc, char *argv[]) {
  DWORD  error;
  HANDLE process;
  ULONG64 module_base;
  int i;
  char* search;
  char buf[256];   /* Enough to hold one hex address, I trust! */
  int rv = 0;
  /* We may add SYMOPT_UNDNAME if --demangle is specified: */
  DWORD symopts = SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES;
  char* filename = "a.out";         /* The default if -e isn't specified */
  int print_function_name = 0;      /* Set to 1 if -f is specified */

  for (i = 1; i < argc; i++) {
    if (strcmp(argv[i], "--functions") == 0 || strcmp(argv[i], "-f") == 0) {
      print_function_name = 1;
    } else if (strcmp(argv[i], "--demangle") == 0 ||
               strcmp(argv[i], "-C") == 0) {
      symopts |= SYMOPT_UNDNAME;
    } else if (strcmp(argv[i], "-e") == 0) {
      if (i + 1 >= argc) {
        fprintf(stderr, "FATAL ERROR: -e must be followed by a filename\n");
        return 1;
      }
      filename = argv[i+1];
      i++;     /* to skip over filename too */
    } else if (strcmp(argv[i], "--help") == 0) {
      usage();
      exit(0);
    } else {
      usage();
      exit(1);
    }
  }

  process = GetCurrentProcess();

  if (!SymInitialize(process, NULL, FALSE)) {
    error = GetLastError();
    fprintf(stderr, "SymInitialize returned error : %d\n", error);
    return 1;
  }

  search = malloc(SEARCH_CAP);
  if (SymGetSearchPath(process, search, SEARCH_CAP)) {
    if (strlen(search) + sizeof(";" WEBSYM) > SEARCH_CAP) {
      fprintf(stderr, "Search path too long\n");
      SymCleanup(process);
      return 1;
    }
    strcat(search, ";" WEBSYM);
  } else {
    error = GetLastError();
    fprintf(stderr, "SymGetSearchPath returned error : %d\n", error);
    rv = 1;                   /* An error, but not a fatal one */
    strcpy(search, WEBSYM);   /* Use a default value */
  }
  if (!SymSetSearchPath(process, search)) {
    error = GetLastError();
    fprintf(stderr, "SymSetSearchPath returned error : %d\n", error);
    rv = 1;                   /* An error, but not a fatal one */
  }

  SymSetOptions(symopts);
  module_base = SymLoadModuleEx(process, NULL, filename, NULL, 0, 0, NULL, 0);
  if (!module_base) {
    /* SymLoadModuleEx failed */
    error = GetLastError();
    fprintf(stderr, "SymLoadModuleEx returned error : %d for %s\n",
            error, filename);
    SymCleanup(process);
    return 1;
  }

  buf[sizeof(buf)-1] = '\0';  /* Just to be safe */
  while (fgets(buf, sizeof(buf)-1, stdin)) {
    /* GNU addr2line seems to just do a strtol and ignore any
     * weird characters it gets, so we will too.
     */
    unsigned __int64 addr = _strtoui64(buf, NULL, 16);
    ULONG64 buffer[(sizeof(SYMBOL_INFO) +
                    MAX_SYM_NAME*sizeof(TCHAR) +
                    sizeof(ULONG64) - 1)
                   / sizeof(ULONG64)];
    PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
    IMAGEHLP_LINE64 line;
    DWORD dummy;
    pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
    pSymbol->MaxNameLen = MAX_SYM_NAME;
    if (print_function_name) {
      if (SymFromAddr(process, (DWORD64)addr, NULL, pSymbol)) {
        printf("%s\n", pSymbol->Name);
      } else {
        printf("??\n");
      }
    }
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    if (SymGetLineFromAddr64(process, (DWORD64)addr, &dummy, &line)) {
      printf("%s:%d\n", line.FileName, (int)line.LineNumber);
    } else {
      printf("??:0\n");
    }
  }
  SymUnloadModule64(process, module_base);
  SymCleanup(process);
  return rv;
}
Example #27
0
int 
main(int argc, char **argv)
{
    int res=0,
        run=0,
        dump=0,
        reset=0,
        detachall=0,
        detachpid=0,
        all=0,                  /* applies to all running processes */
        pid=-1,                 /* applies to pid, -1 means -all */
        hotp_nudge_pid=0,
        hotp_modes_nudge_pid=0,
        hotp_nudge_all=0,
        hotp_modes_nudge_all=0,
        nudge=0,                /* generic nudge with argument */
        nudge_action_mask=0,    /* generic nudge action mask */
        delay_ms_all=           /* delay between acting on processes */
                NUDGE_NO_DELAY,         
        timeout_ms=             /* timeout for finishing a nudge on a single process */
                DETACH_RECOMMENDED_TIMEOUT,
        runval=0,
        canary_default=0,
        canary_run = CANARY_RUN_FLAGS_DEFAULT,
        canary_fault_run = 0,
        exists = 0,
        destroy = 0,
        free_eventlog = 0;

    uint64 nudge_client_arg=0;     /* client nudge argument */

    int verbose = 0;

    char *create=NULL,
        *addapp=NULL, 
        *appdump=NULL, 
        *removeapp=NULL, 
        *opstring=NULL,
        *drdll=NULL,
        *preinject=NULL,
        *logdir=NULL,
        *sharedcache=NULL,
        *appname=NULL,
        *drhome=NULL,
        *modes=NULL,
        *defs=NULL,
        *detach_exename=NULL,
        *load=NULL,
        *save=NULL,
        *eventlog=NULL,
        *canary_process=NULL,
        *scratch_folder=NULL,
        *canary_fault_ops=NULL;

    dr_platform_t dr_platform = DR_PLATFORM_DEFAULT;
    
    int argidx=1;

    WCHAR wbuf[MAX_PATH];
    ConfigGroup *policy = NULL, *working_group;

    if (argc < 2) 
        usage();

    while (argidx < argc) {

        if (!strcmp(argv[argidx], "-help")) {
  	    help();
	}
        /* ******************** actions on active processes ******************** */
	else if (!strcmp(argv[argidx], "-detachall")) {
	    detachall=1;
	}
	else if (!strcmp(argv[argidx], "-detach")) {
            if (++argidx >= argc)
                usage();
	    detachpid=atoi(argv[argidx]);
	}
	else if (!strcmp(argv[argidx], "-detachexe")) {
            if (++argidx >= argc)
                usage();
	    detach_exename=argv[argidx];
	}
        else if (!strcmp(argv[argidx], "-pid") || !strcmp(argv[argidx], "-p")) {
            if (++argidx >= argc)
                usage();
            pid=atoi(argv[argidx]);
        }
	else if (!strcmp(argv[argidx], "-all")) {
	    all=1;
	}
        else if (!strcmp(argv[argidx], "-delay")) {
            /* in milliseconds */
            if (++argidx >= argc)
                usage();
            delay_ms_all=atoi(argv[argidx]);
        }
        else if (!strcmp(argv[argidx], "-timeout")) {
            /* in milliseconds */
            if (++argidx >= argc)
                usage();
            timeout_ms=atoi(argv[argidx]);
        }
	else if (!strcmp(argv[argidx], "-hot_patch_nudge")) {
            if (++argidx >= argc)
                usage();
	    hotp_nudge_pid=atoi(argv[argidx]);
	}
	else if (!strcmp(argv[argidx], "-hot_patch_modes_nudge")) {
            if (++argidx >= argc)
                usage();
	    hotp_modes_nudge_pid=atoi(argv[argidx]);
	}
	else if (!strcmp(argv[argidx], "-hot_patch_nudge_all")) {
	    hotp_nudge_all = 1;
	}
	else if (!strcmp(argv[argidx], "-verbose")) {
	    verbose = 1;
	}
	else if (!strcmp(argv[argidx], "-hot_patch_modes_nudge_all")) {
	    hotp_modes_nudge_all = 1;
	}
	else if (!strcmp(argv[argidx], "-drpop")) {
	    nudge = 1;
            /* allow composition */
	    nudge_action_mask |= NUDGE_GENERIC(opt) | NUDGE_GENERIC(reset);
	}
	else if (!strcmp(argv[argidx], "-nudge")) {
            int nudge_numeric;
            if (++argidx >= argc)
                usage();
            nudge_numeric = atoi(argv[argidx]); /* 0 if fails */
            nudge_action_mask |= nudge_numeric;

            /* compare against numeric new code, or against symbolic names */
            /* -nudge opt -nudge reset -nudge stats -nudge 30000 */
            {
                int found = 0;
#define NUDGE_DEF(name, comment) if (strcmp(#name, argv[argidx]) == 0) { found = 1; nudge_action_mask |= NUDGE_GENERIC(name);}
                NUDGE_DEFINITIONS();
#undef NUDGE_DEF
                if (!found && nudge_numeric == 0) {
                    printf("unknown -nudge %s\n", argv[argidx]);
                    usage();
                }
            }   

	    nudge=1;
	}
        else if (!strcmp(argv[argidx], "-client_nudge")) {
            if (++argidx >= argc)
                usage();
            nudge_client_arg = _strtoui64(argv[argidx], NULL, 16);
            nudge_action_mask |= NUDGE_GENERIC(client);
            nudge = 1;
        }
        /* ******************** configuration actions ******************** */
	else if (!strcmp(argv[argidx], "-reset")) {
	    reset=1;
	}
	else if (!strcmp(argv[argidx], "-create")) {
            if (++argidx >= argc)
                usage();
	    create = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-destroy")) {
            destroy = 1;
	}
	else if (!strcmp(argv[argidx], "-exists")) {
            exists = 1;
	}
	else if (!strcmp(argv[argidx], "-run")) {
            run = 1;
            if (++argidx >= argc)
                usage();
            runval = atoi(argv[argidx]);
	}
	else if (!strcmp(argv[argidx], "-app")) {
            if (++argidx >= argc)
                usage();
            appname = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-add")) {
            if (++argidx >= argc)
                usage();
	    addapp = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-remove")) {
            if (++argidx >= argc)
                usage();
	    removeapp = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-options")) {
            if (++argidx >= argc)
                usage();
	    opstring = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-drlib")) {
            if (++argidx >= argc)
                usage();
	    drdll = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-preinject")) {
            if (++argidx >= argc)
                usage();
            preinject = argv[argidx];
	}
        else if (!strcmp(argv[argidx], "-create_eventlog")) {
            if (++argidx >= argc)
                usage();
            eventlog = argv[argidx];
        }
	else if (!strcmp(argv[argidx], "-destroy_eventlog")) {
            free_eventlog = 1;
	}
	else if (!strcmp(argv[argidx], "-drhome")) {
            if (++argidx >= argc)
                usage();
            drhome = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-modes")) {
            if (++argidx >= argc)
                usage();
            modes = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-defs")) {
            if (++argidx >= argc)
                usage();
            defs = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-logdir")) {
            if (++argidx >= argc)
                usage();
	    logdir = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-sharedcache")) {
            if (++argidx >= argc)
                usage();
	    sharedcache = argv[argidx];
	}
	else if (!strcmp(argv[argidx], "-load")) {
            if (++argidx >= argc)
                usage();
	    load = argv[argidx];
	}
        else if (!strcmp(argv[argidx], "-save")) {
            if (++argidx >= argc)
                usage();
            save = argv[argidx];
        }
	else if (!strcmp(argv[argidx], "-dump")) {
	    dump = 1;
	}
	else if (!strcmp(argv[argidx], "-appdump")) {
            if (++argidx >= argc)
                usage();
            appdump = argv[argidx];	    
	}
	else if (!strcmp(argv[argidx], "-fulldump")) {
	    dump = 1;
	}
	else if (!strcmp(argv[argidx], "-v")) {
#ifdef BUILD_NUMBER
	  printf("DRcontrol.exe build %d -- %s", BUILD_NUMBER, __DATE__);
#else
	  printf("DRcontrol.exe custom build -- %s, %s", __DATE__, __TIME__);
#endif
	} else if (!strcmp(argv[argidx], "-canary_default")) {
            canary_default = 1;
	} else if (!strcmp(argv[argidx], "-canary")) {
            if (++argidx >= argc)
                usage();
	    canary_process=argv[argidx];
            if (++argidx >= argc)
                usage();
	    scratch_folder=argv[argidx];
	} else if (!strcmp(argv[argidx], "-canary_run")) {
            if (++argidx >= argc)
                usage();
	    canary_run = strtol(argv[argidx], NULL, 0);
	} else if (!strcmp(argv[argidx], "-canary_fault")) {
            char *dummy;
            if (++argidx >= argc)
                usage();
            canary_fault_run = strtol(argv[argidx], &dummy, 0);
            if (++argidx >= argc)
                usage();
            canary_fault_ops = argv[argidx];
	} else if (!strcmp(argv[argidx], "-32")) {
	    dr_platform = DR_PLATFORM_32BIT;
	} else if (!strcmp(argv[argidx], "-64")) {
	    dr_platform = DR_PLATFORM_64BIT;
	} else {
	    fprintf(stderr, "Unknown option: %s\n", argv[argidx]);
	    usage();
	}
	argidx++;
    }
  
    /* PR 244206: set the registry view before any registry access */
    set_dr_platform(dr_platform);

    if (canary_process != NULL || canary_default != 0) {
        BOOL result = TRUE;
        WCHAR canary_fault_args[MAX_PATH];
        CANARY_INFO info = {0};

        info.run_flags = canary_run;
        info.info_flags = CANARY_INFO_FLAGS_DEFAULT;
        info.fault_run = canary_fault_run;
        _snwprintf(canary_fault_args, BUFFER_SIZE_ELEMENTS(canary_fault_args),
                   L"%S", canary_fault_ops);
        NULL_TERMINATE_BUFFER(canary_fault_args);
        info.canary_fault_args = canary_fault_args;

        if (canary_process != NULL && *canary_process != '\0' &&
            scratch_folder != NULL && *scratch_folder != '\0') {
            wchar_t canary[MAX_PATH], scratch[MAX_PATH], out[MAX_PATH];
            FILE *out_file;
            _snwprintf(canary, BUFFER_SIZE_ELEMENTS(canary), L"%S", canary_process);
            NULL_TERMINATE_BUFFER(canary);
            _snwprintf(scratch, BUFFER_SIZE_ELEMENTS(scratch), L"%S\\canary_test",
                       scratch_folder);
            NULL_TERMINATE_BUFFER(scratch);
            CreateDirectory(scratch, NULL);
            _snwprintf(out, BUFFER_SIZE_ELEMENTS(out), L"%S\\canary_report.crep",
                       scratch_folder);
            out_file = _wfopen(out, L"wb");
            /* FIXME - check directory, out_file, and canary proc exist */
            result = run_canary_test_ex(out_file, &info, scratch, canary);
        } else if (canary_default != 0) {
            result = run_canary_test(&info, L_EXPAND_LEVEL(STRINGIFY(BUILD_NUMBER)));
            printf("See report file \"%S\"\n", info.report);
        }
        printf("Canary test - %s enable protection - code 0x%08x\n"
               "  msg=\"%S\"\n  url=\"%S\"\n", result ? "do" : "don\'t",
               info.canary_code, info.msg, info.url);
        return info.canary_code;
    }

    if (exists) {
        if (get_dynamorio_home() != NULL) {
            printf("Registry setup exists\n");
            return 0;
        }
        printf("Registry setup doesn't exist\n");
        return 1;
    }    

    if (save) {
        _snwprintf(wbuf, MAX_PATH, L"%S", save);
        NULL_TERMINATE_BUFFER(wbuf);
        checked_operation("save policy", save_policy(wbuf));
    }

    if (destroy) {
        checked_operation("delete product key", destroy_root_key());
        if (!load && create == NULL)
            return 0;
    }

    if (load) {
        _snwprintf(wbuf, MAX_PATH, L"%S", load);
        NULL_TERMINATE_BUFFER(wbuf);
        checked_operation("load policy", load_policy(wbuf, FALSE, NULL));
    }

    if (create != NULL) {
        _snwprintf(wbuf, MAX_PATH, L"%S", create);
        NULL_TERMINATE_BUFFER(wbuf);
        /* FALSE: do not overwrite (preserves old behavior) */
        checked_operation("create registry", setup_installation(wbuf, FALSE));
    }

    /* ensure we init dynamorio_home, case 4009 */
    get_dynamorio_home(); /* ignore return value */

    if (nudge) {
        if (verbose)
            printf("-nudge %d -pid %d %s\n", nudge_action_mask, pid, all ? "all" : "");
        if (pid == -1)           /* explicitly set */
            all = 1;

        if (all)
            checked_operation("nudge all", 
                              generic_nudge_all(nudge_action_mask, nudge_client_arg,
                                                timeout_ms, delay_ms_all));
        else
            checked_operation("nudge", 
                              generic_nudge(pid, TRUE,
                                            nudge_action_mask,
                                            0, /* client ID (ignored here) */
                                            nudge_client_arg,
                                            timeout_ms));
        goto finished;
    }

    if (detachall) {
        checked_operation("detach all", 
                          detach_all(timeout_ms));
        goto finished;
    }
    if (detachpid) {
        checked_operation("detach", 
                          detach(detachpid, TRUE, timeout_ms));
        goto finished;
    }

    if (detach_exename) {
        _snwprintf(wbuf, MAX_PATH, L"%S", detach_exename);
        NULL_TERMINATE_BUFFER(wbuf);
        checked_operation("detach-exe", 
                          detach_exe(wbuf, timeout_ms));
        goto finished;
    }

    
    if (hotp_nudge_pid) {
        checked_operation("hot patch update", 
                          hotp_notify_defs_update(hotp_nudge_pid, TRUE,
                                                  timeout_ms));
        goto finished;
    }

    if (hotp_modes_nudge_pid) {
        checked_operation("hot patch modes update", 
                          hotp_notify_modes_update(hotp_modes_nudge_pid, TRUE,
                                                   timeout_ms));
        goto finished;
    }

    if (hotp_nudge_all) {
        checked_operation("hot patch nudge all", 
                          hotp_notify_all_defs_update(timeout_ms));
        goto finished;
    }

    if (hotp_modes_nudge_all) {
        checked_operation("hot patch modes nudge all", 
                          hotp_notify_all_modes_update(timeout_ms));
        goto finished;
    }

    checked_operation("read config",
                      read_config_group(&policy, L_PRODUCT_NAME, TRUE));
    
    if (reset) {
        remove_children(policy);
        policy->should_clear = TRUE;
        checked_operation("write registry", write_config_group(policy));
    }

    working_group = policy;

    if (dump || appdump)
        goto dumponly;

    if (preinject) {
        if (0 == strcmp(preinject, "OFF")) {
            checked_operation("unset autoinject", unset_autoinjection());
        }
        else if (0 == strcmp(preinject, "ON")) {
            checked_operation("set autoinject", set_autoinjection());
        }
        else if (0 == strcmp(preinject, "CLEAR")) {
            checked_operation("clear autoinject", 
                              set_autoinjection_ex(FALSE, 
                                                   APPINIT_USE_WHITELIST,
                                                   NULL,
                                                   L"",
                                                   NULL,
                                                   NULL,
                                                   NULL,
                                                   0));
        }
        else if (0 == strcmp(preinject, "LIST")) {
            WCHAR list[MAX_PARAM_LEN];
            checked_operation("read appinit",
                              get_config_parameter(INJECT_ALL_KEY_L, 
                                                   TRUE, 
                                                   INJECT_ALL_SUBKEY_L, 
                                                   list, 
                                                   MAX_PARAM_LEN));
            printf("%S\n", list);
            if (is_vista()) {
                printf("LoadAppInit is %s\n",
                       is_loadappinit_set() ? "on" : "off");
            }
        }
        else if (0 == strcmp(preinject, "REPORT")) {
            WCHAR list[MAX_PARAM_LEN], *entry, *sep;
            checked_operation("read appinit",
                              get_config_parameter(INJECT_ALL_KEY_L, 
                                                   TRUE, 
                                                   INJECT_ALL_SUBKEY_L, 
                                                   list, 
                                                   MAX_PARAM_LEN));
            entry = get_entry_location(list, L_EXPAND_LEVEL(INJECT_DLL_8_3_NAME),
                                       APPINIT_SEPARATOR_CHAR);
            if (NULL != entry) {
                sep = wcschr(entry, APPINIT_SEPARATOR_CHAR);
                if (NULL != sep)
                    *sep = L'\0';
                printf("%S\n", entry);
                if (is_vista()) {
                    printf("LoadAppInit is %s\n",
                           is_loadappinit_set() ? "on" : "off");
                }
            }
        }
        else if (0 == strcmp(preinject, "LOAD_OFF")) {
            checked_operation("unset load autoinject", unset_loadappinit());
        }
        else if (0 == strcmp(preinject, "LOAD_ON")) {
            checked_operation("set load autoinject", set_loadappinit());
        }
        else {
            _snwprintf(wbuf, MAX_PATH, L"%S", preinject);
            NULL_TERMINATE_BUFFER(wbuf);
            checked_operation("set custom autoinject", 
                              set_autoinjection_ex(TRUE, APPINIT_OVERWRITE,
                                                   NULL, NULL, NULL, wbuf,
                                                   NULL, 0));
        }

        if (0 != strcmp(preinject, "LIST") &&
            0 != strcmp(preinject, "REPORT") &&
            using_system32_for_preinject(NULL)) {
            DWORD platform;
            if (get_platform(&platform) == ERROR_SUCCESS &&
                platform == PLATFORM_WIN_NT_4) {
                fprintf(stderr, "Warning! On NT4, new AppInit_DLLs setting will not take effect until reboot!\n");
            }
        }

    }

    if (free_eventlog) {
        checked_operation("free eventlog", destroy_eventlog());
    }

    if (eventlog) {
        _snwprintf(wbuf, BUFFER_SIZE_ELEMENTS(wbuf), L"%S", eventlog);
        NULL_TERMINATE_BUFFER(wbuf);
        checked_operation("create eventlog", create_eventlog(wbuf));
    }

    /* configuration */


    if (addapp) {
        _snwprintf(wbuf, MAX_PATH, L"%S", addapp);
        NULL_TERMINATE_BUFFER(wbuf);
        if (NULL == get_child(wbuf, policy)) {
            add_config_group(policy, new_config_group(wbuf));
        }
    }

    if (removeapp) {
        _snwprintf(wbuf, MAX_PATH, L"%S", removeapp);
        NULL_TERMINATE_BUFFER(wbuf);
        remove_child(wbuf, policy);
        policy->should_clear = TRUE;
    }

    if (appname) {
        _snwprintf(wbuf, MAX_PATH, L"%S", appname);
        NULL_TERMINATE_BUFFER(wbuf);
        working_group = get_child(wbuf, policy);

        if (NULL == working_group) {
            working_group = new_config_group(wbuf);
            add_config_group(policy, working_group);
        }
    }
    
    if (run) {
        _snwprintf(wbuf, MAX_PATH, L"%d", runval);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_RUNUNDER, wbuf);
    }

    if (opstring) {
        _snwprintf(wbuf, MAX_PATH, L"%S", opstring);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group,
                                   L_DYNAMORIO_VAR_OPTIONS, wbuf);
    }
    
    if (drdll) {
        _snwprintf(wbuf, MAX_PATH, L"%S", drdll);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_AUTOINJECT, wbuf);
    }

    if (drhome) {
        _snwprintf(wbuf, MAX_PATH, L"%S", drhome);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_HOME, wbuf);
    }

    if (modes) {
        _snwprintf(wbuf, MAX_PATH, L"%S", modes);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_HOT_PATCH_MODES, wbuf);
    }

    if (defs) {
        _snwprintf(wbuf, MAX_PATH, L"%S", defs);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_HOT_PATCH_POLICIES, wbuf);
    }

    if (logdir) {
        _snwprintf(wbuf, MAX_PATH, L"%S", logdir);
        NULL_TERMINATE_BUFFER(wbuf);
        set_config_group_parameter(working_group, 
                                   L_DYNAMORIO_VAR_LOGDIR, wbuf);
    }

    if (sharedcache) {
        /* note if the sharedcache root directory doesn't exist it should be
         * created before calling this function */
        _snwprintf(wbuf, MAX_PATH, L"%S", sharedcache);
        NULL_TERMINATE_BUFFER(wbuf);

        res = setup_cache_shared_directories(wbuf);
        if (res != ERROR_SUCCESS) {
            fprintf(stderr, "error %d creating directories!\n", res);
        }
        setup_cache_shared_registry(wbuf, working_group);
    }

    checked_operation("write policy", write_config_group(policy));

 dumponly:

    if (appdump) {
        _snwprintf(wbuf, MAX_PATH, L"%S", appdump);
        NULL_TERMINATE_BUFFER(wbuf);
        working_group = get_child(wbuf, policy);
    }
    else {
        working_group = policy;
    }

    if (dump || appdump) {
        if (NULL == working_group)
            fprintf(stderr, "No Configuration Exists!\n");
        else
            dump_config_group("","  ",working_group,FALSE);
    }

 finished:
    if (policy != NULL)
        free_config_group(policy);

    return 0;

}
Example #28
0
std::string CXMLParser::XmlDecode(const std::string& sString, bool a_decodeHtmlEntities)
{
	std::wstring swStr;
	swStr.reserve(sString.size());

	std::string::size_type p = sString.find('&'), pPrev = 0, pStartRemain = 0;

	do
	{
		if(p == std::string::npos)
		{
			// handle rest of the str...
			swStr += CUtil::ToWideStr(sString.substr(pStartRemain), CP_UTF8);
			break;
		}
		else
		{
			swStr += CUtil::ToWideStr(sString.substr(pPrev, p - pPrev), CP_UTF8);
		}

		bool bIgnore = true;

		std::string::size_type pEnd = sString.find(';', p);
		if(pEnd != std::string::npos)
		{
			const std::string sEntity = sString.substr(p + 1, pEnd - p - 1);

			if(sEntity.size() >= 2 && sEntity[0] == '#')
			{
				bool bHex = (sEntity[1] == 'x' || sEntity[1] == 'X');
				bool bOk = true;

				for(std::string::size_type ep = 2; bOk && ep < sEntity.size(); ep++)
				{
					bOk = (bHex ? FAST_ISDIGITX(sEntity[ep]) : FAST_ISDIGIT(sEntity[ep]));
				}

				if(bOk && (!bHex || sEntity.size() >= 3))
				{
					const unsigned long long lle = _strtoui64(sEntity.c_str() + (bHex ? 2 : 1), NULL, (bHex ? 16 : 10));

					if(lle > 0 && lle <= std::numeric_limits<wchar_t>::max())
					{
						swStr += (wchar_t)lle;
						bIgnore = false;
					}
				}
			}
			else if(!_stricmp(sEntity.c_str(), "amp")) { swStr += '&'; bIgnore = false; }
			else if(!_stricmp(sEntity.c_str(), "gt")) { swStr += '>'; bIgnore = false; }
			else if(!_stricmp(sEntity.c_str(), "lt")) { swStr += '<'; bIgnore = false; }
			else if(!_stricmp(sEntity.c_str(), "quot")) { swStr += '"'; bIgnore = false; }
			else if(!_stricmp(sEntity.c_str(), "apos")) { swStr += '\''; bIgnore = false; }
			else if(a_decodeHtmlEntities)
			{
				const wchar_t* l_tmp = html_entities::translate(sEntity.c_str());

				if(l_tmp)
				{
					swStr += l_tmp;
					bIgnore = false;
				}
			}
		}
		else
			pEnd = p + 1;

		if(!bIgnore)
		{
			pPrev = pEnd + 1;
		}

		p = sString.find('&', pEnd + 1);

		pStartRemain = pEnd + 1;

	} while(true);

	return CUtil::FromWideStr(swStr, CP_UTF8);
}
Example #29
0
/**
* \brief      Extracts the signal data from the given Line and populates
              message structure.
* \param[in]  char *pcLine
* \param[out] None
* \return     int
* \authors    Mahesh.B.S
* \date       15.11.2004
*/
int CSignal::Format(char *pcLine)
{
    char *pcToken;
    char acTemp[defCON_MAX_TOKN_LEN],*pcTemp;
    pcTemp = acTemp;

    // get signal name
    pcToken = strtok(pcLine,","); // get upto colon

    // now get the signal name
    m_sName = pcToken; // copy the name to the signal's data member

    if(m_sName.GetLength() > defCON_MAX_MSGN_LEN)
        Truncate_str("Signal name",m_sName,true);

    // Signal length
    pcToken = strtok(NULL,",");
    m_ucLength = atoi(pcToken); // store signal length

    // get which byte
    pcToken = strtok(NULL,",");
    m_ucWhichByte = atoi(pcToken);

    // get start bit
    UCHAR ucStartBit;
    pcToken = strtok(NULL,",");
    m_ucStartBit = atoi(pcToken);
    ucStartBit = m_ucStartBit + (m_ucWhichByte - 1) * 8;

    //get Data type
    pcToken = strtok(NULL,",");
    m_ucType = *pcToken;

    // get MAX
    pcToken = strtok(NULL,",");
    // now store as double until we parse till SIG_VALTYPE_

    m_MaxValue.ui64Value = _strtoui64(pcToken, NULL, 10);

    // get MIN value
    pcToken = strtok(NULL,",");

    //venkat - unsiged __int64 is enough to store any value
    m_MinValue.ui64Value = _strtoui64(pcToken, NULL, 10);

    // get DATA_FORMAT (intel or motorola)
    pcToken = strtok(NULL,",");
    m_ucDataFormat = *pcToken;

    if(m_ucDataFormat == '0')
    {
        UINT unByteIndex = m_ucWhichByte - 1;
        UINT nByte = (m_ucLength/8) + ((m_ucLength % 8)?1:0);
        UINT nStartBit = (m_ucWhichByte - nByte) * 8;
        UINT nBitSize = m_ucLength - (8 * (nByte - 1))+ m_ucStartBit;
        if(nBitSize == 0)
        {
            ucStartBit = ucStartBit + m_ucLength;
        }
        else
        {
            ucStartBit = nStartBit + nBitSize-1;
        }
    }
    m_ucStartBit = ucStartBit;
    // next token - (SCALE_FACTOR,OFFSET)
    pcToken = strtok(NULL,",");
    m_fOffset = (float)atof(pcToken); // store scale factor

    // Get offset
    pcToken = strtok(NULL,",");
    m_fScaleFactor = (float)atof(pcToken); // store Offset

    // next token -- "UNIT", ""
    pcTemp = acTemp;
    pcToken = strtok(NULL,"");
    //pcToken++;
    // copy everything, but not including the last <">
    while(*pcToken && *pcToken != ',' && *pcToken != 0xa)
    {
        *pcTemp++ = *pcToken++;
    }
    *pcTemp='\0';
    CString strUnit_Temp = acTemp;
    m_sUnit = "\"";
    m_sUnit = m_sUnit + acTemp; // copy UNIT to corresponding data member.
    m_sUnit = m_sUnit.Left(defCON_MAX_MSGN_LEN + 1);
    m_sUnit = m_sUnit + "\"";
    if(strUnit_Temp.GetLength() > defCON_MAX_MSGN_LEN + 2)
    {
        char logmsg[defCON_MAX_LINE_LEN];
        sprintf(logmsg,"unit %s changed to %s\n",strUnit_Temp,m_sUnit);
        CConverter::fileLog.WriteString(logmsg);
        CConverter::bLOG_ENTERED = true;
    }
    //for multiplexing field
    CString strTemp = pcToken;
    int nIndex = strTemp.Find(',');
    if(nIndex != -1)
    {
        int nLength = strTemp.GetLength();
        strTemp = strTemp.Right(nLength - nIndex -1);
        nIndex = strTemp.Find(',');
        if(nIndex != -1)
        {
            if(nIndex != 0)
            {
                strTemp = strTemp.Left(nIndex);
            }
            else
            {
                strTemp.Empty();
            }
            m_sMultiplex = strTemp;
        }
    }


    //rx'ing nodes
    pcToken = strtok(pcToken,",");
    pcToken = strtok(NULL,",");
    pcToken = strtok(NULL,"\n");
    if(pcToken)
        m_sNode = pcToken;
    else
        m_sNode = "Vector__XXX";

    return 1;
}
Example #30
0
void processline(char *line) {
    int rc;
    int async = ((line[0] == 'a') && !(startsWith(line, "addauth ")));
    if (async) {
        line++;
    }
    if (startsWith(line, "help")) {
      fprintf(stderr, "    create [+[e|s]] <path>\n");
      fprintf(stderr, "    create2 [+[e|s]] <path>\n");
      fprintf(stderr, "    delete <path>\n");
      fprintf(stderr, "    set <path> <data>\n");
      fprintf(stderr, "    get <path>\n");
      fprintf(stderr, "    ls <path>\n");
      fprintf(stderr, "    ls2 <path>\n");
      fprintf(stderr, "    sync <path>\n");
      fprintf(stderr, "    exists <path>\n");
      fprintf(stderr, "    wexists <path>\n");
      fprintf(stderr, "    myid\n");
      fprintf(stderr, "    verbose\n");
      fprintf(stderr, "    addauth <id> <scheme>\n");
      fprintf(stderr, "    config\n");
      fprintf(stderr, "    reconfig [-file <path> | -members <serverId=host:port1:port2;port3>,... | "
                          " -add <serverId=host:port1:port2;port3>,... | -remove <serverId>,...] [-version <version>]\n");
      fprintf(stderr, "    quit\n");
      fprintf(stderr, "\n");
      fprintf(stderr, "    prefix the command with the character 'a' to run the command asynchronously.\n");
      fprintf(stderr, "    run the 'verbose' command to toggle verbose logging.\n");
      fprintf(stderr, "    i.e. 'aget /foo' to get /foo asynchronously\n");
    } else if (startsWith(line, "verbose")) {
      if (verbose) {
        verbose = 0;
        zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
        fprintf(stderr, "logging level set to WARN\n");
      } else {
        verbose = 1;
        zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
        fprintf(stderr, "logging level set to DEBUG\n");
      }
    } else if (startsWith(line, "get ")) {
        line += 4;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }

        rc = zoo_aget(zh, line, 1, my_data_completion, strdup(line));
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (strcmp(line, "config") == 0) {
       gettimeofday(&startTime, 0);
        rc = zoo_agetconfig(zh, 1, my_data_completion, strdup(ZOO_CONFIG_NODE));
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
   } else if (startsWith(line, "reconfig ")) {
           int syntaxError = 0;
           char* p = NULL;
           char* joining = NULL;
           char* leaving = NULL;
           char* members = NULL;
           size_t members_size = 0;

           int mode = 0; // 0 = not set, 1 = incremental, 2 = non-incremental
           int64_t version = -1;

           line += 9;
           p = strtok (strdup(line)," ");
           while (p != NULL) {
               if (strcmp(p, "-add")==0) {
                   p = strtok (NULL," ");
                   if (mode == 2 || p == NULL) {
                       syntaxError = 1;
                       break;
                   }
                   mode = 1;
                   joining = strdup(p);
               } else if (strcmp(p, "-remove")==0){
                   p = strtok (NULL," ");
                   if (mode == 2 || p == NULL) {
                       syntaxError = 1;
                       break;
                   }
                   mode = 1;
                   leaving = strdup(p);
               } else if (strcmp(p, "-members")==0) {
                   p = strtok (NULL," ");
                   if (mode == 1 || p == NULL) {
                       syntaxError = 1;
                       break;
                   }
                   mode = 2;
                   members = strdup(p);
               } else if (strcmp(p, "-file")==0){
                   FILE *fp = NULL;
                   p = strtok (NULL," ");
                   if (mode == 1 || p == NULL) {
                       syntaxError = 1;
                       break;
                   }
                   mode = 2;
                   fp = fopen(p, "r");
                   if (fp == NULL) {
                       fprintf(stderr, "Error reading file: %s\n", p);
                       syntaxError = 1;
                       break;
                   }
                   fseek(fp, 0L, SEEK_END);  /* Position to end of file */
                   members_size = ftell(fp);     /* Get file length */
                   rewind(fp);               /* Back to start of file */
                   members = calloc(members_size + 1, sizeof(char));
                   if(members == NULL )
                   {
                       fprintf(stderr, "\nInsufficient memory to read file: %s\n", p);
                       syntaxError = 1;
                       fclose(fp);
                       break;
                   }

                   /* Read the entire file into members
                    * NOTE: -- fread returns number of items successfully read
                    * not the number of bytes. We're requesting one item of
                    * members_size bytes. So we expect the return value here
                    * to be 1.
                    */
                   if (fread(members, members_size, 1, fp) != 1){
                       fprintf(stderr, "Error reading file: %s\n", p);
                       syntaxError = 1;
                       fclose(fp);
                        break;
                   }
                   fclose(fp);
               } else if (strcmp(p, "-version")==0){
                   p = strtok (NULL," ");
                   if (version != -1 || p == NULL){
                       syntaxError = 1;
                       break;
                   }
#ifdef WIN32
                   version = _strtoui64(p, NULL, 16);
#else
                   version = strtoull(p, NULL, 16);
#endif
                   if (version < 0) {
                       syntaxError = 1;
                       break;
                   }
               } else {
                   syntaxError = 1;
                   break;
               }
               p = strtok (NULL," ");
           }
           if (syntaxError) return;

           rc = zoo_areconfig(zh, joining, leaving, members, version, my_data_completion, strdup(line));
           free(joining);
           free(leaving);
           free(members);
           if (rc) {
               fprintf(stderr, "Error %d for %s\n", rc, line);
           }

   } else if (startsWith(line, "set ")) {
        char *ptr;
        line += 4;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        ptr = strchr(line, ' ');
        if (!ptr) {
            fprintf(stderr, "No data found after path\n");
            return;
        }
        *ptr = '\0';
        ptr++;
        if (async) {
            rc = zoo_aset(zh, line, ptr, strlen(ptr), -1, my_stat_completion,
                    strdup(line));
        } else {
            struct Stat stat;
            rc = zoo_set2(zh, line, ptr, strlen(ptr), -1, &stat);
        }
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "ls ")) {
        line += 3;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        gettimeofday(&startTime, 0);
        rc= zoo_aget_children(zh, line, 1, my_strings_completion, strdup(line));
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "ls2 ")) {
        line += 4;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        gettimeofday(&startTime, 0);
        rc= zoo_aget_children2(zh, line, 1, my_strings_stat_completion, strdup(line));
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "create ") || startsWith(line, "create2 ")) {
        int flags = 0;
        int is_create2 = startsWith(line, "create2 ");
        line += is_create2 ? 8 : 7;
        if (line[0] == '+') {
            line++;
            if (line[0] == 'e') {
                flags |= ZOO_EPHEMERAL;
                line++;
            }
            if (line[0] == 's') {
                flags |= ZOO_SEQUENCE;
                line++;
            }
            line++;
        }
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        fprintf(stderr, "Creating [%s] node\n", line);
//        {
//            struct ACL _CREATE_ONLY_ACL_ACL[] = {{ZOO_PERM_CREATE, ZOO_ANYONE_ID_UNSAFE}};
//            struct ACL_vector CREATE_ONLY_ACL = {1,_CREATE_ONLY_ACL_ACL};
//            rc = zoo_acreate(zh, line, "new", 3, &CREATE_ONLY_ACL, flags,
//                    my_string_completion, strdup(line));
//        }
        if (is_create2) {
          rc = zoo_acreate2(zh, line, "new", 3, &ZOO_OPEN_ACL_UNSAFE, flags,
                my_string_stat_completion_free_data, strdup(line));
        } else {
          rc = zoo_acreate(zh, line, "new", 3, &ZOO_OPEN_ACL_UNSAFE, flags,
                my_string_completion_free_data, strdup(line));
        }
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "delete ")) {
        line += 7;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        if (async) {
            rc = zoo_adelete(zh, line, -1, my_void_completion, strdup(line));
        } else {
            rc = zoo_delete(zh, line, -1);
        }
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "sync ")) {
        line += 5;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
        rc = zoo_async(zh, line, my_string_completion_free_data, strdup(line));
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "wexists ")) {
#ifdef THREADED
        struct Stat stat;
#endif
        line += 8;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
#ifndef THREADED
        rc = zoo_awexists(zh, line, watcher, (void*) 0, my_stat_completion, strdup(line));
#else
        rc = zoo_wexists(zh, line, watcher, (void*) 0, &stat);
#endif
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (startsWith(line, "exists ")) {
#ifdef THREADED
        struct Stat stat;
#endif
        line += 7;
        if (line[0] != '/') {
            fprintf(stderr, "Path must start with /, found: %s\n", line);
            return;
        }
#ifndef THREADED
        rc = zoo_aexists(zh, line, 1, my_stat_completion, strdup(line));
#else
        rc = zoo_exists(zh, line, 1, &stat);
#endif
        if (rc) {
            fprintf(stderr, "Error %d for %s\n", rc, line);
        }
    } else if (strcmp(line, "myid") == 0) {
        printf("session Id = %llx\n", _LL_CAST_ zoo_client_id(zh)->client_id);
    } else if (strcmp(line, "reinit") == 0) {
        zookeeper_close(zh);
        // we can't send myid to the server here -- zookeeper_close() removes
        // the session on the server. We must start anew.
        zh = zookeeper_init(hostPort, watcher, 30000, 0, 0, 0);
    } else if (startsWith(line, "quit")) {
        fprintf(stderr, "Quitting...\n");
        shutdownThisThing=1;
    } else if (startsWith(line, "od")) {
        const char val[]="fire off";
        fprintf(stderr, "Overdosing...\n");
        rc = zoo_aset(zh, "/od", val, sizeof(val)-1, -1, od_completion, 0);
        if (rc)
            fprintf(stderr, "od command failed: %d\n", rc);
    } else if (startsWith(line, "addauth ")) {
      char *ptr;
      line += 8;
      ptr = strchr(line, ' ');
      if (ptr) {
        *ptr = '\0';
        ptr++;
      }
      zoo_add_auth(zh, line, ptr, ptr ? strlen(ptr) : 0, NULL, NULL);
    }
}