Exemple #1
0
static void _err_vformat(const char *format, va_list args) {
	char *ptr = err_message;
	err_frame_t *frame = _err_top;

	if(frame)
		ptr = frame->context(frame->userdata, ptr, endof(err_message));

	safe_vsnprintf(ptr, endof(err_message) - ptr, format, args);
}
Exemple #2
0
int
main(int argc, char *argv[])
{
    int i;
    int ar_file;
    size_t len;
    unsigned long crc = 0;
    char *path;
    char buf[4096], arbuf[4096];
    FILE *fp;

    for (i = 1; i < argc; i++) {
	crc = crc32(0L, Z_NULL, 0);
	path = argv[i];
	ar_file = !strcmp(endof(path) - 2, ".a");
	if (ar_file) {
	    snprintf(arbuf, sizeof(arbuf), "ar -p %s", path);
	    if ((fp = popen(arbuf, "r"))) {
		while ((len = fread(buf, 1, sizeof(buf), fp))) {
		    crc = crc32(crc, buf, len);
		}
		pclose(fp);
	    }
#ifdef	WIN32
	} else if (!strcmp(endof(path) - 4, ".obj")) {
	    DWORD origsum;
	    DWORD rc;

	    rc = MapFileAndCheckSum(path, &origsum, &crc);
	    if (rc != CHECKSUM_SUCCESS) {
		fprintf(stderr, "Error: %s: %ld\n", path, rc);
	    }
	    fp = stdin;		// HACK
#endif	/*WIN32*/
	} else {
	    if ((fp = fopen(path, "r"))) {
		while ((len = fread(buf, 1, sizeof(buf), fp))) {
		    crc = crc32(crc, buf, len);
		}
		fclose(fp);
	    }
	}
	if (!fp) {
	    fprintf(stderr, "Error: %s: %s\n", path, strerror(errno));
	    continue;
	}
	fprintf(stdout, "Zlib CRC32 of %s is %lu\n", path, crc);
    }
    return(0);
}
Exemple #3
0
/**
 * Set debugging levels by parsing the text in \a s.
 * For setting individual levels a string like \c "net=3,grf=6" should be used.
 * If the string starts with a number, the number is used as global debugging level.
 * @param s Text describing the wanted debugging levels.
 */
void SetDebugString(const char *s)
{
	int v;
	char *end;
	const char *t;

	/* global debugging level? */
	if (*s >= '0' && *s <= '9') {
		const DebugLevel *i;

		v = strtoul(s, &end, 0);
		s = end;

		for (i = debug_level; i != endof(debug_level); ++i) *i->level = v;
	}

	/* individual levels */
	for (;;) {
		const DebugLevel *i;
		int *p;

		/* skip delimiters */
		while (*s == ' ' || *s == ',' || *s == '\t') s++;
		if (*s == '\0') break;

		t = s;
		while (*s >= 'a' && *s <= 'z') s++;

		/* check debugging levels */
		p = NULL;
		for (i = debug_level; i != endof(debug_level); ++i) {
			if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
				p = i->level;
				break;
			}
		}

		if (*s == '=') s++;
		v = strtoul(s, &end, 0);
		s = end;
		if (p != NULL) {
			*p = v;
		} else {
			ShowInfoF("Unknown debug level '%.*s'", (int)(s - t), t);
			return;
		}
	}
}
Exemple #4
0
/** Initialize the highscore table to 0 and if any file exists, load in values */
void LoadFromHighScore()
{
	FILE *fp = fopen(_highscore_file, "rb");

	memset(_highscore_table, 0, sizeof(_highscore_table));

	if (fp != NULL) {
		uint i;
		HighScore *hs;

		for (i = 0; i < SP_SAVED_HIGHSCORE_END; i++) {
			for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
				byte length;
				if (fread(&length, sizeof(length), 1, fp)                              !=  1 ||
						fread(hs->company, min<int>(lengthof(hs->company), length), 1, fp) >   1 || // Yes... could be 0 bytes too
						fread(&hs->score, sizeof(hs->score), 1, fp)                        !=  1 ||
						fseek(fp, 2, SEEK_CUR)                                             == -1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
					DEBUG(misc, 1, "Highscore corrupted");
					i = SP_SAVED_HIGHSCORE_END;
					break;
				}
				str_validate(hs->company, lastof(hs->company), SVS_NONE);
				hs->title = EndGameGetPerformanceTitleFromValue(hs->score);
			}
		}
		fclose(fp);
	}
}
Exemple #5
0
static uint32 ConvertAllegroKeyIntoMy(WChar *character)
{
	int scancode;
	int unicode = ureadkey(&scancode);

	const VkMapping *map;
	uint key = 0;

	for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
		if ((uint)(scancode - map->vk_from) <= map->vk_count) {
			key = scancode - map->vk_from + map->map_to;
			break;
		}
	}

	if (key_shifts & KB_SHIFT_FLAG) key |= WKC_SHIFT;
	if (key_shifts & KB_CTRL_FLAG)  key |= WKC_CTRL;
	if (key_shifts & KB_ALT_FLAG)   key |= WKC_ALT;
#if 0
	DEBUG(driver, 0, "Scancode character pressed %u", scancode);
	DEBUG(driver, 0, "Unicode character pressed %u", unicode);
#endif

	*character = unicode;
	return key;
}
/**
 * Entry point for the crash handler.
 * @note Not static so it shows up in the backtrace.
 * @param signum the signal that caused us to crash.
 */
static void CDECL HandleCrash(int signum)
{
	/* Disable all handling of signals by us, so we don't go into infinite loops. */
	for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
		signal(*i, SIG_DFL);
	}

	if (GamelogTestEmergency()) {
		printf("A serious fault condition occurred in the game. The game will shut down.\n");
		printf("As you loaded an emergency savegame no crash information will be generated.\n");
		abort();
	}

	if (SaveloadCrashWithMissingNewGRFs()) {
		printf("A serious fault condition occurred in the game. The game will shut down.\n");
		printf("As you loaded an savegame for which you do not have the required NewGRFs\n");
		printf("no crash information will be generated.\n");
		abort();
	}

	CrashLogUnix log(signum);
	log.MakeCrashLog();

	CrashLog::AfterCrashLogCleanup();
	abort();
}
void bstr_machine(struct parmac *p,const char *src) {
  static const struct parmac_state
    state_start={"start",NULL,NULL},
    state_lbrace={"lbrace",NULL,NULL},
    state_rbrace={"rbrace",NULL,NULL},
    state_char={"char",char_enter,NULL},
    state_bstr={"bstr",NULL,NULL},
    state_end={"end",NULL,NULL};

  static const struct parmac_transition trsns[]={
    {&state_start, &state_lbrace, parse_lbrace,  NULL},

    {&state_lbrace, &state_rbrace, parse_rbrace, NULL},
    {&state_lbrace, &state_bstr,   NULL,         bstr_machine},
    {&state_lbrace, &state_char,   parse_any,    NULL},

    {&state_char, &state_rbrace, parse_rbrace, NULL},
    {&state_char, &state_bstr,   NULL,         bstr_machine},
    {&state_char, &state_char,   parse_any,    NULL},

    {&state_bstr, &state_rbrace, parse_rbrace, NULL},
    {&state_bstr, &state_bstr,   NULL,         bstr_machine},
    {&state_bstr, &state_char,   parse_any,    NULL},

    {&state_rbrace, &state_end, NULL, NULL},
  };

  parmac_set(p,"bstr",src,&state_start,&state_end,trsns,endof(trsns));
}
Exemple #8
0
/** Save HighScore table to file */
void SaveToHighScore()
{
	FILE *fp = fopen(_highscore_file, "wb");

	if (fp != NULL) {
		uint i;
		HighScore *hs;

		for (i = 0; i < SP_SAVED_HIGHSCORE_END; i++) {
			for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
				/* First character is a command character, so strlen will fail on that */
				byte length = min(sizeof(hs->company), StrEmpty(hs->company) ? 0 : (int)strlen(&hs->company[1]) + 1);

				if (fwrite(&length, sizeof(length), 1, fp)       != 1 || // write away string length
						fwrite(hs->company, length, 1, fp)           >  1 || // Yes... could be 0 bytes too
						fwrite(&hs->score, sizeof(hs->score), 1, fp) != 1 ||
						fwrite("  ", 2, 1, fp)                       != 1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
					DEBUG(misc, 1, "Could not save highscore.");
					i = SP_SAVED_HIGHSCORE_END;
					break;
				}
			}
		}
		fclose(fp);
	}
}
/** Initialize the highscore table to 0 and if any file exists, load in values */
void LoadFromHighScore()
{
	FILE *fp = fopen(_highscore_file, "rb");

	memset(_highscore_table, 0, sizeof(_highscore_table));

	if (fp != NULL) {
		uint i;
		HighScore *hs;

		for (i = 0; i < LAST_HS_ITEM; i++) { // don't load network highscores
			for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
				byte length;
				if (fread(&length, sizeof(length), 1, fp)       !=  1 ||
						fread(hs->company, length, 1, fp)           >   1 || // Yes... could be 0 bytes too
						fread(&hs->score, sizeof(hs->score), 1, fp) !=  1 ||
						fseek(fp, 2, SEEK_CUR)                      == -1) { // XXX - placeholder for hs->title, not saved anymore; compatibility
					DEBUG(misc, 1, "Highscore corrupted");
					i = LAST_HS_ITEM;
					break;
				}
				*lastof(hs->company) = '\0';
				hs->title = EndGameGetPerformanceTitleFromValue(hs->score);
			}
		}
		fclose(fp);
	}
}
Exemple #10
0
static void set_language_standard(char const *const name)
{
	typedef struct name_std_t {
		char const     *name;
		lang_standard_t std;
	} name_std_t;
	static name_std_t const stds[] = {
		{ "c++",            STANDARD_CXX98   },
		{ "c++98",          STANDARD_CXX98   },
		{ "c11",            STANDARD_C11     },
		{ "c1x",            STANDARD_C11     }, // deprecated
		{ "c89",            STANDARD_C89     },
		{ "c90",            STANDARD_C89     },
		{ "c99",            STANDARD_C99     },
		{ "c9x",            STANDARD_C99     }, // deprecated
		{ "gnu++98",        STANDARD_GNUXX98 },
		{ "gnu11",          STANDARD_GNU11   },
		{ "gnu1x",          STANDARD_GNU11   }, // deprecated
		{ "gnu89",          STANDARD_GNU89   },
		{ "gnu99",          STANDARD_GNU99   },
		{ "gnu9x",          STANDARD_GNU99   }, // deprecated
		{ "iso9899:1990",   STANDARD_C89     },
		{ "iso9899:199409", STANDARD_C89AMD1 },
		{ "iso9899:1999",   STANDARD_C99     },
		{ "iso9899:199x",   STANDARD_C99     }, // deprecated
		{ "iso9899:2011",   STANDARD_C11     },
	};
	for (name_std_t const *i = stds; i != endof(stds); ++i) {
		if (streq(i->name, name)) {
			standard = i->std;
			return;
		}
	}
	errorf(NULL, "unknown language standard '%s' for '-std'", name);
}
Exemple #11
0
	/**
	 * Gets a pointer to the last data element stored in this wrapper.
	 * @note needed because endof does not work properly for pointers.
	 * @return the 'endof' pointer.
	 */
	FORCEINLINE T *EndOf()
	{
#if !defined(__NDS__)
		return endof(data);
#else
		return &data[len];
#endif
	}
/*
 * ScanECPGKeywordLookup - see if a given word is a keyword
 *
 * Returns a pointer to the ScanKeyword table entry, or NULL if no match.
 *
 * The match is done case-insensitively.  Note that we deliberately use a
 * dumbed-down case conversion that will only translate 'A'-'Z' into 'a'-'z',
 * even if we are in a locale where tolower() would produce more or different
 * translations.  This is to conform to the SQL99 spec, which says that
 * keywords are to be matched in this way even though non-keyword identifiers
 * receive a different case-normalization mapping.
 */
ScanKeyword *
ScanECPGKeywordLookup(char *text)
{
	int			len,
				i;
	char		word[NAMEDATALEN];
	ScanKeyword *low;
	ScanKeyword *high;

	len = strlen(text);
	/* We assume all keywords are shorter than NAMEDATALEN. */
	if (len >= NAMEDATALEN)
		return NULL;

	/*
	 * Apply an ASCII-only downcasing.	We must not use tolower() since it
	 * may produce the wrong translation in some locales (eg, Turkish),
	 * and we don't trust isupper() very much either.  In an ASCII-based
	 * encoding the tests against A and Z are sufficient, but we also
	 * check isupper() so that we will work correctly under EBCDIC.  The
	 * actual case conversion step should work for either ASCII or EBCDIC.
	 */
	for (i = 0; i < len; i++)
	{
		char		ch = text[i];

		if (ch >= 'A' && ch <= 'Z' && isupper((unsigned char) ch))
			ch += 'a' - 'A';
		word[i] = ch;
	}
	word[len] = '\0';

	/*
	 * Now do a binary search using plain strcmp() comparison.
	 */
	low = &ScanKeywords[0];
	high = endof(ScanKeywords) - 1;
	while (low <= high)
	{
		ScanKeyword *middle;
		int			difference;

		middle = low + (high - low) / 2;
		difference = strcmp(middle->name, word);
		if (difference == 0)
			return middle;
		else if (difference < 0)
			low = middle + 1;
		else
			high = middle - 1;
	}

	return NULL;
}
void qstr_machine(struct parmac *p,const char *src) {
  static const struct parmac_state
    state_start={"start",NULL,NULL},
    state_lquote={"lquote",NULL,NULL},
    state_rquote={"rquote",NULL,NULL},
    state_char={"char",char_enter,sub_str_leave},

    state_dollar={"dollar",char_enter,NULL},
    state_dchar={"dchar",NULL,sub_str_leave},
    state_vstr={"vstr",NULL,NULL},

    state_cmd={"cmd",NULL,NULL},
    state_end={"end",NULL,NULL};

  static const struct parmac_transition trsns[]={
    {&state_start, &state_lquote, parse_lquote, NULL},

    {&state_lquote, &state_rquote, parse_rquote, NULL},
    {&state_lquote, &state_dollar, parse_dollar, NULL},
    {&state_lquote, &state_cmd,    NULL,         cmd_machine},
    {&state_lquote, &state_char,   parse_any,    NULL},

    {&state_dollar, &state_vstr,  NULL, vstr_machine},
    {&state_dollar, &state_dchar, NULL, NULL},

    {&state_dchar, &state_rquote, parse_rquote, NULL},
    {&state_dchar, &state_dollar, parse_dollar, NULL},
    {&state_dchar, &state_cmd,    NULL, cmd_machine},
    {&state_dchar, &state_char,   parse_any, NULL},

    {&state_vstr, &state_rquote, parse_rquote, NULL},
    {&state_vstr, &state_dollar, parse_dollar, NULL},
    {&state_vstr, &state_cmd,    NULL,         cmd_machine},
    {&state_vstr, &state_char,   parse_any,  NULL},

    {&state_cmd, &state_rquote, parse_rquote, NULL},
    {&state_cmd, &state_dollar, parse_dollar, NULL},
    {&state_cmd, &state_cmd,    NULL,         cmd_machine},
    {&state_cmd, &state_char,   parse_any,    NULL},

    {&state_char, &state_rquote, parse_rquote, NULL},
    {&state_char, &state_dollar, parse_dollar, NULL},
    {&state_char, &state_cmd,    NULL,         cmd_machine},
    {&state_char, &state_char,   parse_any,    NULL},

    {&state_rquote, &state_end, NULL, NULL}
  };

  parmac_set(p,"qstr",src,&state_start,&state_end,trsns, endof(trsns));
}
Exemple #14
0
/*
 * ScanKeywordLookup - see if a given word is a keyword
 *
 * Returns a pointer to the ScanKeyword table entry, or NULL if no match.
 *
 * The match is done case-insensitively.  Note that we deliberately use a
 * dumbed-down case conversion that will only translate 'A'-'Z' into 'a'-'z',
 * even if we are in a locale where tolower() would produce more or different
 * translations.  This is to conform to the SQL99 spec, which says that
 * keywords are to be matched in this way even though non-keyword identifiers
 * receive a different case-normalization mapping.
 */
const ScanKeyword *
ScanKeywordLookup(const char *text)
{
	int			len,
				i;
	char		word[NAMEDATALEN];
	const ScanKeyword *low;
	const ScanKeyword *high;

	len = strlen(text);
	/* We assume all keywords are shorter than NAMEDATALEN. */
	if (len >= NAMEDATALEN)
		return NULL;

	/*
	 * Apply an ASCII-only downcasing.	We must not use tolower() since it may
	 * produce the wrong translation in some locales (eg, Turkish).
	 */
	for (i = 0; i < len; i++)
	{
		char		ch = text[i];

		if (ch >= 'A' && ch <= 'Z')
			ch += 'a' - 'A';
		word[i] = ch;
	}
	word[len] = '\0';

	/*
	 * Now do a binary search using plain strcmp() comparison.
	 */
	low = &ScanKeywords[0];
	high = endof(ScanKeywords) - 1;
	while (low <= high)
	{
		const ScanKeyword *middle;
		int			difference;

		middle = low + (high - low) / 2;
		difference = strcmp(middle->name, word);
		if (difference == 0)
			return middle;
		else if (difference < 0)
			low = middle + 1;
		else
			high = middle - 1;
	}

	return NULL;
}
Exemple #15
0
/**
 ** Analogue: fputs().
 ** Sends two commands to the child: first the "real command", then the
 ** "tag (trivial) command".
 ** Uses a "lazy fork" concept; we don't actually start the child
 ** at the time of the child_open() call but instead when the first cmd
 ** is sent. This means a program which employs a dispatcher, for instance,
 ** can do a child_open() in the main function, pass the handle off to
 ** all the routines it dispatches to, and child_close() before exiting
 ** without worrying about which of those functions will actually need
 ** the coprocess.  If some of them don't need it, they won't send it
 ** any commands and will incur no fork/exec overhead.
 **/
int
child_puts(char *s, CHILD *handle, AV* perl_out_array, AV* perl_err_array)
{
   int n;

   if (handle == NULL)
      handle = mru_handle;
   if ((mru_handle = handle) == NULL)
      return 0;
   if (handle->cph_pid == 0) {
      if (_cp_start_child(handle) != 0) {
	 fprintf(stderr, "can't start child %s\n",  handle->cph_cmd);
	 exit(1);
      }
      /* Add file descriptors to poll vector. */
      poll_add_fd( fileno(handle->cph_back),
                   NPOLL_TXT, bck_read, NULL, handle );
      poll_add_fd( fileno(handle->cph_err),
                   NPOLL_TXT, err_read, NULL, handle );
   }

   /* Save Perl array references for access from callbacks. */
   handle->cph_out_array = perl_out_array;
   handle->cph_err_array = perl_err_array;

   _dbg(F,L,1, "-->> %s", s);

   /** set error count to 0 for new command **/
   handle->cph_errs = 0;

   /** send the cmd down the pipe to the child **/
   if ((n = fputs(s, handle->cph_down)) == EOF)
      return EOF;
   /** be helpful and add a newline if there isn't one **/
   if (strrchr(s, '\n') != endof(s) - 1)
      if (fputc('\n', handle->cph_down) == EOF)
	 return EOF;
   /** send the tag cmd **/
   _dbg(F,L,4, "-->> [TAG]");
   if (fputs(handle->cph_tag, handle->cph_down) == EOF)
      return EOF;
   handle->cph_pending = TRUE;
   _dbg(F,L,4, "pending ...");

   /** poll **/
   poll_rcv( NPOLL_NO_TIMEOUT ); 

   return n;
}
static bool check_unique(const std::string& config, const std::string& prefix) {
    int retval = false;

    std::string data;
    if (!android::base::ReadFileToString(config, &data)) return retval;

    const fs_path_config_from_file* pc =
        reinterpret_cast<const fs_path_config_from_file*>(data.c_str());
    size_t len = data.size();

    std::vector<const char*> paths_tmp;
    size_t entry_number = 0;
    while (len > 0) {
        uint16_t host_len = (len >= endof(pc, len)) ? pc->len : INT16_MAX;
        if (host_len > len) {
            GTEST_LOG_(WARNING) << config << ": truncated at entry " << entry_number << " ("
                                << host_len << " > " << len << ")";
            const std::string unknown("?");
            GTEST_LOG_(WARNING)
                << config << ": entry[" << entry_number << "]={ "
                << "len=" << ((len >= endof(pc, len))
                                  ? android::base::StringPrintf("%" PRIu16, pc->len)
                                  : unknown)
                << ", mode=" << ((len >= endof(pc, mode))
                                     ? android::base::StringPrintf("0%" PRIo16, pc->mode)
                                     : unknown)
                << ", uid=" << ((len >= endof(pc, uid))
                                    ? android::base::StringPrintf("%" PRIu16, pc->uid)
                                    : unknown)
                << ", gid=" << ((len >= endof(pc, gid))
                                    ? android::base::StringPrintf("%" PRIu16, pc->gid)
                                    : unknown)
                << ", capabilities="
                << ((len >= endof(pc, capabilities))
                        ? android::base::StringPrintf("0x%" PRIx64, pc->capabilities)
                        : unknown)
                << ", prefix="
                << ((len >= offsetof(fs_path_config_from_file, prefix))
                        ? android::base::StringPrintf(
                              "\"%.*s...", (int)(len - offsetof(fs_path_config_from_file, prefix)),
                              pc->prefix)
                        : unknown)
                << " }";
            retval = true;
            break;
        }
        paths_tmp.push_back(pc->prefix);

        pc = reinterpret_cast<const fs_path_config_from_file*>(reinterpret_cast<const char*>(pc) +
                                                               host_len);
        len -= host_len;
        ++entry_number;
    }

    return check_unique(paths_tmp, config, prefix) || retval;
}
Exemple #17
0
static DWORD WINAPI SoundThread(LPVOID arg)
{
	do {
		for (WAVEHDR *hdr = _wave_hdr; hdr != endof(_wave_hdr); hdr++) {
			if ((hdr->dwFlags & WHDR_INQUEUE) != 0) continue;
			MxMixSamples(hdr->lpData, hdr->dwBufferLength / 4);
			if (waveOutWrite(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR) {
				MessageBox(NULL, _T("Sounds are disabled until restart."), _T("waveOutWrite failed"), MB_ICONINFORMATION);
				return 0;
			}
		}
		WaitForSingleObject(_event, INFINITE);
	} while (_waveout != NULL);

	return 0;
}
Exemple #18
0
/**
 * Tries to find a suitable destination for the given source and cargo.
 * @param cid      Subsidized cargo.
 * @param src_type Type of \a src.
 * @param src      Index of source.
 * @return True iff the subsidy was created.
 */
bool FindSubsidyCargoDestination(CargoID cid, SourceType src_type, SourceID src)
{
	/* Choose a random destination. Only consider towns if they can accept the cargo. */
	SourceType dst_type = (HasBit(_town_cargoes_accepted, cid) && Chance16(1, 2)) ? ST_TOWN : ST_INDUSTRY;

	SourceID dst;
	switch (dst_type) {
		case ST_TOWN: {
			/* Select a random town. */
			const Town *dst_town = Town::GetRandom();

			/* Check if the town can accept this cargo. */
			if (!HasBit(dst_town->cargo_accepted_total, cid)) return false;

			dst = dst_town->index;
			break;
		}

		case ST_INDUSTRY: {
			/* Select a random industry. */
			const Industry *dst_ind = Industry::GetRandom();
			if (dst_ind == NULL) return false;

			/* The industry must accept the cargo */
			bool valid = std::find(dst_ind->accepts_cargo, endof(dst_ind->accepts_cargo), cid) != endof(dst_ind->accepts_cargo);
			if (!valid) return false;

			dst = dst_ind->index;
			break;
		}

		default: NOT_REACHED();
	}

	/* Check that the source and the destination are not the same. */
	if (src_type == dst_type && src == dst) return false;

	/* Check distance between source and destination. */
	if (!CheckSubsidyDistance(src_type, src, dst_type, dst)) return false;

	/* Avoid duplicate subsidies. */
	if (CheckSubsidyDuplicate(cid, src_type, src, dst_type, dst)) return false;

	CreateSubsidy(cid, src_type, src, dst_type, dst);

	return true;
}
Exemple #19
0
/** Print out the current debug-level
 * Just return a string with the values of all the debug categorites
 * @return string with debug-levels
 */
const char *GetDebugString()
{
	const DebugLevel *i;
	static char dbgstr[150];
	char dbgval[20];

	memset(dbgstr, 0, sizeof(dbgstr));
	i = debug_level;
	snprintf(dbgstr, sizeof(dbgstr), "%s=%d", i->name, *i->level);

	for (i++; i != endof(debug_level); i++) {
		snprintf(dbgval, sizeof(dbgval), ", %s=%d", i->name, *i->level);
		strecat(dbgstr, dbgval, lastof(dbgstr));
	}

	return dbgstr;
}
Exemple #20
0
static uint MapWindowsKey(uint sym)
{
	const VkMapping *map;
	uint key = 0;

	for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
		if ((uint)(sym - map->vk_from) <= map->vk_count) {
			key = sym - map->vk_from + map->map_to;
			break;
		}
	}

	if (GetAsyncKeyState(VK_SHIFT)   < 0) key |= WKC_SHIFT;
	if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
	if (GetAsyncKeyState(VK_MENU)    < 0) key |= WKC_ALT;
	return key;
}
Exemple #21
0
/**
 * Dump the available debug facility names in the help text.
 * @param buf Start address for storing the output.
 * @param last Last valid address for storing the output.
 * @return Next free position in the output.
 */
char *DumpDebugFacilityNames(char *buf, char *last)
{
	size_t length = 0;
	for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
		if (length == 0) {
			buf = strecpy(buf, "List of debug facility names:\n", last);
		} else {
			buf = strecpy(buf, ", ", last);
			length += 2;
		}
		buf = strecpy(buf, i->name, last);
		length += strlen(i->name);
	}
	if (length > 0) {
		buf = strecpy(buf, "\n\n", last);
	}
	return buf;
}
void vstr_machine(struct parmac *p,const char *src) {
  static const struct parmac_state
    state_start={"start",NULL,NULL},
    state_idn={"idn",char_enter,NULL},
    state_bstr={"bstr",NULL,NULL},
    state_end={"end",NULL,var_leave};

  static const struct parmac_transition trsns[]={
    {&state_start, &state_bstr, NULL,      bstr_machine},
    {&state_start, &state_idn,  parse_idn, NULL},

    {&state_bstr, &state_end, NULL, NULL},

    {&state_idn, &state_idn, parse_idn, NULL},
    {&state_idn, &state_end, NULL,      NULL}
  };

  parmac_set(p,"vstr",src,&state_start,&state_end,trsns,endof(trsns));
}
void word_machine(struct parmac *p,const char *src) {
  static const struct parmac_state
    state_start={"start",NULL,NULL},
    state_bstr={"bstr",NULL,sub_str_leave},
    state_qstr={"qstr",NULL,NULL},
    state_sstr={"sstr",NULL,NULL},
    state_end={"end",NULL,NULL};

  static const struct parmac_transition trsns[]={
    {&state_start, &state_qstr, NULL, qstr_machine},
    {&state_start, &state_bstr, NULL, bstr_machine},
    {&state_start, &state_sstr, NULL, sstr_machine},

    {&state_qstr, &state_end, NULL, NULL},
    {&state_bstr, &state_end, NULL, NULL},
    {&state_sstr, &state_end, NULL, NULL}
  };

  parmac_set(p,"word",src,&state_start,&state_end,trsns,endof(trsns));
}
void cmd_machine(struct parmac *p,const char *src) {
  static const struct parmac_state
    state_start={"start",NULL,NULL},
    state_lsqr={"lsqr",NULL,NULL},
    state_rsqr={"rsqr",NULL,NULL},
    state_main={"main",NULL,NULL},
    state_end={"end",NULL,NULL};

  static const struct parmac_transition trsns[]={
    {&state_start, &state_lsqr, parse_lsqr, NULL},

    {&state_lsqr, &state_rsqr, parse_rsqr, NULL},
    {&state_lsqr, &state_main, NULL,       main_machine},

    {&state_main, &state_rsqr, parse_rsqr, NULL},

    {&state_rsqr, &state_end, NULL, NULL}
  };

  parmac_set(p,"cmd",src,&state_start,&state_end,trsns, endof(trsns));
}
Exemple #25
0
/// Sets the command-line field for the CmdAction object. The string
/// passed in may be freed afterward since a copy is held.
/// The 'ccode' attribute is set as a side effect since it's derived
/// from the command line.
/// @param[in] ca       the object pointer
/// @param[in] line     the new command line
void
ca_set_line(ca_o ca, CCS line)
{
    putil_free(ca->ca_line);

    if (line) {
        CS l1, l2;
        size_t nlen;

        // Turn newline tokens back into actual newlines.
        ca->ca_line = (CCS)putil_malloc((strlen(line) + 1) * CHARSIZE);
        nlen = strlen(CSV_NEWLINE_TOKEN);
        for (l1 = (CS)line, l2 = (CS)ca->ca_line; *l1; ) {
            if (l1[0] == CSV_NEWLINE_TOKEN[0] &&
                    !strncmp(l1, CSV_NEWLINE_TOKEN, nlen)) {
                l1 += nlen;
                *l2++ = '\n';
            } else {
                *l2++ = *l1++;
            }
        }
        *l2 = '\0';
    } else {
        ca->ca_line = NULL;
    }

    // Determine the "command code" (aka ccode).
    if (ca->ca_line) {
        char ccbuf[CODE_IDENTITY_HASH_MAX_LEN];

        (void)code_from_str(ca->ca_line, ccbuf, sizeof(ccbuf));
        if (ccbuf[0]) {
            snprintf(endof(ccbuf), leftlen(ccbuf),
                     "+%lu", (unsigned long)strlen(ca->ca_line));
            ca->ca_ccode = putil_strdup(ccbuf);
        } else {
            ca->ca_ccode = NULL;
        }
    }
}
Exemple #26
0
/// Generates the 'pathcode' - a hash of all pathnames opened by this cmd.
/// The combination of command line and pathcode is believed
/// sufficent to uniquely identify any given command, because
/// if two commands with identical textual representations operate on the
/// same set of files, they must be functionally identical.
/// In other words the command line says what to do and the pathcode
/// says who it's done to. Thus 'touch foo' might be repeated in different
/// places but it's only the *same command* if the 'foo' it touches
/// is at the same absolute path. Similarly, 'make' might occur all
/// over in a recursive-make build but it's not the same make unless it
/// opens the same Makefile. Another way of putting it: if a cmd addresses
/// any files relative to CWD, this will be seen in the absolute paths
/// of the files it opens. If it doesn't then the CWD doesn't matter.
/// Of course there can still be semantically identical cmds which look
/// different: consider "rm foo bar" and "rm bar foo". But these cases
/// would be very rare in real life and don't break anything - we would
/// just miss a potential recycle opportunity.
/// @param[in] ca       the object pointer
void
ca_derive_pathcode(ca_o ca)
{
    pathcode_accumulator_s pca;

    pca.pca_buf = NULL;
    pca.pca_buflen = 0;
    pca.pca_count = 0;

    (void)ca_foreach_cooked_pa(ca, _ca_add_to_pathcode, &pca);

    if (pca.pca_buf) {
        char pcbuf[CODE_IDENTITY_HASH_MAX_LEN];

        (void)code_from_str(pca.pca_buf, pcbuf, charlen(pcbuf));
        putil_free(pca.pca_buf);
        snprintf(endof(pcbuf), leftlen(pcbuf), "-%d", pca.pca_count);
        ca_set_pathcode(ca, pcbuf);
    } else {
        ca_set_pathcode(ca, NULL);
    }
}
Exemple #27
0
static uint ConvertSdlKeyIntoMy(SDL_keysym *sym, WChar *character)
{
	const VkMapping *map;
	uint key = 0;

	for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
		if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
			key = sym->sym - map->vk_from + map->map_to;
			break;
		}
	}

	/* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
#if defined(WIN32) || defined(__OS2__)
	if (sym->scancode == 41) key = WKC_BACKQUOTE;
#elif defined(__APPLE__)
	if (sym->scancode == 10) key = WKC_BACKQUOTE;
#elif defined(__MORPHOS__)
	if (sym->scancode == 0)  key = WKC_BACKQUOTE;  // yes, that key is code '0' under MorphOS :)
#elif defined(__BEOS__)
	if (sym->scancode == 17) key = WKC_BACKQUOTE;
#elif defined(__SVR4) && defined(__sun)
	if (sym->scancode == 60) key = WKC_BACKQUOTE;
	if (sym->scancode == 49) key = WKC_BACKSPACE;
#elif defined(__sgi__)
	if (sym->scancode == 22) key = WKC_BACKQUOTE;
#else
	if (sym->scancode == 49) key = WKC_BACKQUOTE;
#endif

	/* META are the command keys on mac */
	if (sym->mod & KMOD_META)  key |= WKC_META;
	if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
	if (sym->mod & KMOD_CTRL)  key |= WKC_CTRL;
	if (sym->mod & KMOD_ALT)   key |= WKC_ALT;

	*character = sym->unicode;
	return key;
}
ScanKeyword *
ScanCKeywordLookup(char *text)
{
	ScanKeyword *low = &ScanKeywords[0];
	ScanKeyword *high = endof(ScanKeywords) - 1;
	ScanKeyword *middle;
	int			difference;

	while (low <= high)
	{
		middle = low + (high - low) / 2;
		difference = strcmp(middle->name, text);
		if (difference == 0)
			return middle;
		else if (difference < 0)
			low = middle + 1;
		else
			high = middle - 1;
	}

	return NULL;
}
void
timed_print(register const u_char *bp)
{
#define endof(x) ((u_char *)&(x) + sizeof (x))
	struct tsp *tsp = (struct tsp *)bp;
	long sec, usec;
	const u_char *end;

	if (endof(tsp->tsp_type) > snapend) {
		fputs("[|timed]", stdout);
		return;
	}
	if (tsp->tsp_type < TSPTYPENUMBER)
		printf("TSP_%s", tsptype[tsp->tsp_type]);
	else
		printf("(tsp_type %#x)", tsp->tsp_type);

	if (endof(tsp->tsp_vers) > snapend) {
		fputs(" [|timed]", stdout);
		return;
	}
	printf(" vers %d", tsp->tsp_vers);

	if (endof(tsp->tsp_seq) > snapend) {
		fputs(" [|timed]", stdout);
		return;
	}
	printf(" seq %d", tsp->tsp_seq);

	if (tsp->tsp_type == TSP_LOOP) {
		if (endof(tsp->tsp_hopcnt) > snapend) {
			fputs(" [|timed]", stdout);
			return;
		}
		printf(" hopcnt %d", tsp->tsp_hopcnt);
	} else if (tsp->tsp_type == TSP_SETTIME ||
	  tsp->tsp_type == TSP_ADJTIME ||
	  tsp->tsp_type == TSP_SETDATE ||
	  tsp->tsp_type == TSP_SETDATEREQ) {
		if (endof(tsp->tsp_time) > snapend) {
			fputs(" [|timed]", stdout);
			return;
		}
		sec = EXTRACT_32BITS(&tsp->tsp_time.tv_sec);
		usec = EXTRACT_32BITS(&tsp->tsp_time.tv_usec);
		if (usec < 0)
			/* corrupt, skip the rest of the packet */
			return;
		fputs(" time ", stdout);
		if (sec < 0 && usec != 0) {
			sec++;
			if (sec == 0)
				fputc('-', stdout);
			usec = 1000000 - usec;
		}
		printf("%ld.%06ld", sec, usec);
	}

	end = memchr(tsp->tsp_name, '\0', snapend - (u_char *)tsp->tsp_name);
	if (end == NULL)
		fputs(" [|timed]", stdout);
	else {
		fputs(" name ", stdout);
		fwrite(tsp->tsp_name, end - (u_char *)tsp->tsp_name, 1, stdout);
	}
}
Exemple #30
0
/* Do a simple uri parse: return 0 if fail, 1 otherwise*/
int
ncuriparse(const char* uri0, NCURI** durip)
{
    NCURI* duri = NULL;
    char* uri = NULL;
    char* p;
    struct NC_ProtocolInfo* proto;
    int i,nprotos;

    /* accumulate parse points*/
    char* protocol = NULL;
    char* host = NULL;
    char* port = NULL;
    char* constraint = NULL;
    char* user = NULL;
    char* pwd = NULL;
    char* file = NULL;
    char* prefixparams = NULL;
    char* suffixparams = NULL;

    if(uri0 == NULL || strlen(uri0) == 0)
	{THROW(1); goto fail;}

    duri = (NCURI*)calloc(1,sizeof(NCURI));
    if(duri == NULL)
	{THROW(2); goto fail;}
	
    /* save original uri */
    duri->uri = nulldup(uri0);

    /* make local copy of uri */
    uri = (char*)malloc(strlen(uri0)+1+PADDING); /* +1 for trailing null,
                                                    +PADDING for shifting */
    if(uri == NULL)
	{THROW(3); goto fail;}

    /* strings will be broken into pieces with intermixed '\0; characters;
       first char is guaranteed to be '\0' */

    duri->strings = uri;
    uri++; 

    /* dup the incoming url */
    strcpy(uri,uri0);

    /* Walk the uri and do the following:
	1. remove all whitespace
	2. remove all '\\' (Temp hack to remove escape characters
                            inserted by Windows or MinGW)
    */
    for(p=uri;*p;p++) {
	if(*p == '\\' || *p < ' ')
	    nclshift1(p); /* compress out */
    }	

    p = uri;

    /* break up the uri string into big chunks: prefixparams, protocol,
       host section, and the file section (i.e. remainder)
    */

    /* collect any prefix bracketed parameters */
    if(*p == LBRACKET) {
	prefixparams = p+1;
	/* find end of the clientparams; convert LB,RB to '&' */
        for(;*p;p++) {
	    if(p[0] == RBRACKET && p[1] == LBRACKET) {
		p[0] = '&';
		nclshift1(p+1);
	    } else if(p[0] == RBRACKET && p[1] != LBRACKET)
		break;
	}
	if(*p == 0)
	    {THROW(4); goto fail; /* malformed client params*/}
        terminate(p); /* nul term the prefixparams (overwrites
                         the final RBRACKET) */
	p++; /* move past the final RBRACKET */
    }

    /* Tag the protocol */
    protocol = p;    
    p = strchr(p,':');
    if(!p)
	{THROW(5); goto fail;}
    terminate(p); /*overwrite colon*/
    p++; /* skip the colon */

    /* verify that the uri starts with an acceptable protocol*/
    nprotos = (sizeof(legalprotocols)/sizeof(struct NC_ProtocolInfo));
    proto = NULL;
    for(i=0;i<nprotos;i++) {
        if(strcmp(protocol,legalprotocols[i].name)==0) {
	    proto = &legalprotocols[i];
	    break;	    
	}
    }
    if(proto == NULL)
	{THROW(6); goto fail; /* illegal protocol*/}

    /* skip // */
    if(p[0] != '/' && p[1] != '/')
	{THROW(7); goto fail;}
    p += 2;

    /* If this is all we have (proto://) then fail */
    if(*p == EOFCHAR)
	{THROW(8); goto fail;}

    /* establish the start of the file section */
    if(proto->filelike) {/* everything after proto:// */
	file = p;
	host = NULL; /* and no host section */
    } else { /*!proto->filelike => This means there should be a host section */
        /* locate the end of the host section and therefore the start
           of the file section */
	host = p;
        p  = nclocate(p,"/?#");
	if(p == NULL) {
	    file = endof(host); /* there is no file section */
	} else {
	    ncrshift1(p); /* make room to terminate the host section
                             without overwriting the leading character */
	    terminate(p); /* terminate the host section */
	    file = p+1; /* +1 becauseof the shift */
	}
    }
    
    /* If you shift in the code below, you must reset file beginning */

    if(host != NULL) {/* Parse the host section */
	/* Check for leading user:pwd@ */
        p = strchr(host,'@');
        if(p) {
	    if(p == host)
		{THROW(9); goto fail; /* we have proto://@ */}
	    user = host;
	    terminate(p); /* overwrite '@' */
	    host = p+1; /* start of host ip name */
	    p = strchr(user,':');
 	    if(p == NULL)
		{THROW(10); goto fail; /* malformed */}
	    terminate(p); /*overwrite colon */
	    pwd = p+1;
	}

        /* extract host and port */
	p = host;
        p = strchr(p,':');
        if(p != NULL) {
	    terminate(p);
	    p++;
	    port = p;
	    if(*port == EOFCHAR)
		{THROW(11); goto fail; /* we have proto://...:/ */}
	    /* The port must look something like a number */
	    for(;*p;p++) {
	        if(strchr("0123456789-",*p) == NULL)
		    {THROW(12); goto fail;  /* probably not a real port, fail */}
	    }
	} /* else *p == NULL */


        /* check for empty host section */
	if(*host == EOFCHAR)
	    {THROW(13); goto fail;}

    }

    assert(file != NULL);
    p = file;

    /* find the end of the file section and the start of the
       constraints and/or suffixparams
    */
    p = nclocate(p,"?#");
    if(p != NULL) { /* we have constraint and/or suffixparams */
	char* fileend = p; /* save the end of the file section */
	char* constraintend = NULL; 
	if(*p == '?')
            constraint = p+1;
	else
	    constraint = NULL;
	p = strchr(p,'#'); /* may repeat effect of nclocate above */
	if(p != NULL) {
	    constraintend = p;
	    suffixparams = p+1;
	} else
	    suffixparams = NULL;
	/* Ok, terminate the pieces */
	terminate(fileend); /* terminate file section */
	if(constraint != NULL && constraintend != NULL)
	    terminate(constraintend);
	/* Suffix params are already terminated
           since they should be the last section
           of the original url
        */
    }

    /* check for empty sections */
    if(file != NULL && *file == EOFCHAR)
	file = NULL; /* empty file section */
    if(constraint != NULL && *constraint == EOFCHAR)
	constraint = NULL; /* empty constraint section */
    if(suffixparams != NULL && *suffixparams == EOFCHAR)
	suffixparams = NULL; /* empty suffixparams section */

    if(suffixparams != NULL) {
	/* there really are suffix params; so rebuild the suffix params */
	if(*suffixparams == LBRACKET) suffixparams++;
        p = suffixparams;
	/* convert RBRACKET LBRACKET to '&' */
        for(;*p;p++) {
	    if(p[0] == RBRACKET && p[1] == LBRACKET) {
	        p[0] = '&';
		nclshift1(p+1);
	    } else if(p[0] == RBRACKET && p[1] != LBRACKET) {
		/* terminate suffixparams */
		*p = EOFCHAR;
		break;
	    }
	}
	if(*suffixparams == EOFCHAR)
	    suffixparams = NULL; /* suffixparams are empty */
    }

    /* do last minute empty check */
    
    if(protocol != NULL && *protocol == EOFCHAR) protocol = NULL;
    if(user != NULL && *user == EOFCHAR) user = NULL;
    if(pwd != NULL && *pwd == EOFCHAR) pwd = NULL;
    if(host != NULL && *host == EOFCHAR) host = NULL;
    if(port != NULL && *port == EOFCHAR) port = NULL;
    if(file != NULL && *file == EOFCHAR) file = NULL;
    if(constraint != NULL && *constraint == EOFCHAR) constraint = NULL;

    /* assemble the component pieces */
    duri->protocol = protocol;
    duri->user = user;
    duri->password = pwd;
    duri->host = host;
    duri->port = port;
    duri->file = file;

    ncurisetconstraints(duri,constraint);

    /* concat suffix and prefix params */
    if(prefixparams != NULL || suffixparams != NULL) {
	int plen = prefixparams ? strlen(prefixparams) : 0;
	int slen = suffixparams ? strlen(suffixparams) : 0;
	int space = plen + slen + 1;
	/* add 1 for an extra ampersand if both are defined */
        space++;
        duri->params = (char*)malloc(space);
	duri->params[0] = EOFCHAR; /* so we can use strcat */
	if(plen > 0) {
            strcat(duri->params,prefixparams);
	    if(slen > 0)
		strcat(duri->params,"&");
	}
	if(slen > 0)
            strcat(duri->params,suffixparams);
    }

#ifdef NCXDEBUG
	{
        fprintf(stderr,"duri:");
        fprintf(stderr," params=|%s|",FIX(duri->params));
        fprintf(stderr," protocol=|%s|",FIX(duri->protocol));
        fprintf(stderr," host=|%s|",FIX(duri->host));
        fprintf(stderr," port=|%s|",FIX(duri->port));
        fprintf(stderr," file=|%s|",FIX(duri->file));
        fprintf(stderr," constraint=|%s|",FIX(duri->constraint));
        fprintf(stderr,"\n");
    }
#endif
    if(durip != NULL) 
      *durip = duri;
    else
      ncurifree(duri);

    return 1;

fail:
    if(duri != NULL) {
	ncurifree(duri);
    }
    return 0;
}