Changeset - r11870:92eb16f6d311
[Not reviewed]
master
0 21 0
smatz - 15 years ago 2009-05-10 17:27:25
smatz@openttd.org
(svn r16269) -Codechange: use gcc's ability to check parameters sent to printf-like functions
-Fix: wrong number of parameters or wrong parameter types sent to printf-like functions at several places
21 files changed with 69 insertions and 58 deletions:
0 comments (0 inline, 0 general)
src/console.cpp
Show inline comments
 
@@ -107,31 +107,31 @@ void IConsolePrint(ConsoleColour colour_
 
		return;
 
	}
 

	
 
	IConsoleWriteToLogFile(str);
 
	IConsoleGUIPrint(colour_code, str);
 
}
 

	
 
/**
 
 * Handle the printing of text entered into the console or redirected there
 
 * by any other means. Uses printf() style format, for more information look
 
 * at IConsolePrint()
 
 */
 
void CDECL IConsolePrintF(ConsoleColour colour_code, const char *s, ...)
 
void CDECL IConsolePrintF(ConsoleColour colour_code, const char *format, ...)
 
{
 
	va_list va;
 
	char buf[ICON_MAX_STREAMSIZE];
 

	
 
	va_start(va, s);
 
	vsnprintf(buf, sizeof(buf), s, va);
 
	va_start(va, format);
 
	vsnprintf(buf, sizeof(buf), format, va);
 
	va_end(va);
 

	
 
	IConsolePrint(colour_code, buf);
 
}
 

	
 
/**
 
 * It is possible to print debugging information to the console,
 
 * which is achieved by using this function. Can only be used by
 
 * debug() in debug.cpp. You need at least a level 2 (developer) for debugging
 
 * messages to show up
 
 * @param dbg debugging category
 
 * @param string debugging message
src/console_cmds.cpp
Show inline comments
 
@@ -1200,25 +1200,25 @@ DEF_CONSOLE_CMD(ConInfoVar)
 
	}
 

	
 
	if (argc < 2) return false;
 

	
 
	var = IConsoleVarGet(argv[1]);
 
	if (var == NULL) {
 
		IConsoleError("the given variable was not found");
 
		return true;
 
	}
 

	
 
	IConsolePrintF(CC_DEFAULT, "variable name: %s", var->name);
 
	IConsolePrintF(CC_DEFAULT, "variable type: %s", _icon_vartypes[var->type]);
 
	IConsolePrintF(CC_DEFAULT, "variable addr: 0x%X", var->addr);
 
	IConsolePrintF(CC_DEFAULT, "variable addr: %p", var->addr);
 

	
 
	if (var->hook.access) IConsoleWarning("variable is access hooked");
 
	if (var->hook.pre) IConsoleWarning("variable is pre hooked");
 
	if (var->hook.post) IConsoleWarning("variable is post hooked");
 
	return true;
 
}
 

	
 

	
 
DEF_CONSOLE_CMD(ConInfoCmd)
 
{
 
	const IConsoleCmd *cmd;
 

	
 
@@ -1227,25 +1227,25 @@ DEF_CONSOLE_CMD(ConInfoCmd)
 
		return true;
 
	}
 

	
 
	if (argc < 2) return false;
 

	
 
	cmd = IConsoleCmdGet(argv[1]);
 
	if (cmd == NULL) {
 
		IConsoleError("the given command was not found");
 
		return true;
 
	}
 

	
 
	IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
 
	IConsolePrintF(CC_DEFAULT, "command proc: 0x%X", cmd->proc);
 
	IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
 

	
 
	if (cmd->hook.access) IConsoleWarning("command is access hooked");
 
	if (cmd->hook.pre) IConsoleWarning("command is pre hooked");
 
	if (cmd->hook.post) IConsoleWarning("command is post hooked");
 

	
 
	return true;
 
}
 

	
 
DEF_CONSOLE_CMD(ConDebugLevel)
 
{
 
	if (argc == 0) {
 
		IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
 
@@ -1432,25 +1432,25 @@ DEF_CONSOLE_CMD(ConCompanies)
 
	NetworkPopulateCompanyStats(company_stats);
 

	
 
	FOR_ALL_COMPANIES(c) {
 
		/* Grab the company name */
 
		char company_name[NETWORK_COMPANY_NAME_LENGTH];
 
		SetDParam(0, c->index);
 
		GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
 

	
 
		char buffer[512];
 
		const NetworkCompanyStats *stats = &company_stats[c->index];
 

	
 
		GetString(buffer, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(buffer));
 
		IConsolePrintF(CC_INFO, "#:%d(%s) Company Name: '%s'  Year Founded: %d  Money: %" OTTD_PRINTF64 "d  Loan: %" OTTD_PRINTF64 "d  Value: %" OTTD_PRINTF64 "d  (T:%d, R:%d, P:%d, S:%d) %sprotected",
 
		IConsolePrintF(CC_INFO, "#:%d(%s) Company Name: '%s'  Year Founded: %d  Money: " OTTD_PRINTF64 "  Loan: " OTTD_PRINTF64 "  Value: " OTTD_PRINTF64 "  (T:%d, R:%d, P:%d, S:%d) %sprotected",
 
			c->index + 1, buffer, company_name, c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
 
			/* trains      */ stats->num_vehicle[0],
 
			/* lorry + bus */ stats->num_vehicle[1] + stats->num_vehicle[2],
 
			/* planes      */ stats->num_vehicle[3],
 
			/* ships       */ stats->num_vehicle[4],
 
			/* protected   */ StrEmpty(_network_company_states[c->index].password) ? "un" : "");
 
	}
 

	
 
	return true;
 
}
 

	
 
DEF_CONSOLE_CMD(ConSayCompany)
src/console_func.h
Show inline comments
 
@@ -8,21 +8,21 @@
 
#include "console_type.h"
 

	
 
/* console modes */
 
extern IConsoleModes _iconsole_mode;
 

	
 
/* console functions */
 
void IConsoleInit();
 
void IConsoleFree();
 
void IConsoleClose();
 

	
 
/* console output */
 
void IConsolePrint(ConsoleColour colour_code, const char *string);
 
void CDECL IConsolePrintF(ConsoleColour colour_code, const char *s, ...);
 
void CDECL IConsolePrintF(ConsoleColour colour_code, const char *format, ...) WARN_FORMAT(2, 3);
 
void IConsoleDebug(const char *dbg, const char *string);
 
void IConsoleWarning(const char *string);
 
void IConsoleError(const char *string);
 

	
 
/* Parser */
 
void IConsoleCmdExec(const char *cmdstr);
 

	
 
#endif /* CONSOLE_FUNC_H */
src/core/alloc_func.cpp
Show inline comments
 
@@ -2,23 +2,23 @@
 

	
 
/** @file alloc_func.cpp Functions to 'handle' memory allocation errors */
 

	
 
#include "../stdafx.h"
 
#include "alloc_func.hpp"
 

	
 
/**
 
 * Function to exit with an error message after malloc() or calloc() have failed
 
 * @param size number of bytes we tried to allocate
 
 */
 
void NORETURN MallocError(size_t size)
 
{
 
	error("Out of memory. Cannot allocate %i bytes", size);
 
	error("Out of memory. Cannot allocate " PRINTF_SIZE " bytes", size);
 
}
 

	
 
/**
 
 * Function to exit with an error message after realloc() have failed
 
 * @param size number of bytes we tried to allocate
 
 */
 
void NORETURN ReallocError(size_t size)
 
{
 
	error("Out of memory. Cannot reallocate %i bytes", size);
 
	error("Out of memory. Cannot reallocate " PRINTF_SIZE " bytes", size);
 
}
src/debug.cpp
Show inline comments
 
@@ -83,33 +83,31 @@ static void debug_print(const char *dbg,
 
		fprintf(stderr, "dbg: [%s] %s\n", dbg, buf);
 
#endif
 
		IConsoleDebug(dbg, buf);
 
	} else {
 
		static FILE *f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
 
		if (f == NULL) return;
 

	
 
		fprintf(f, "%s", buf);
 
		fflush(f);
 
	}
 
}
 

	
 
void CDECL debug(const char *dbg, ...)
 
void CDECL debug(const char *dbg, const char *format, ...)
 
{
 
	va_list va;
 
	va_start(va, dbg);
 
	const char *s;
 
	char buf[1024];
 

	
 
	s = va_arg(va, const char*);
 
	vsnprintf(buf, lengthof(buf), s, va);
 
	va_list va;
 
	va_start(va, format);
 
	vsnprintf(buf, lengthof(buf), format, va);
 
	va_end(va);
 

	
 
	debug_print(dbg, buf);
 
}
 
#endif /* NO_DEBUG_MESSAGES */
 

	
 
void SetDebugString(const char *s)
 
{
 
	int v;
 
	char *end;
 
	const char *t;
 

	
 
@@ -140,25 +138,25 @@ void SetDebugString(const char *s)
 
		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'", s - t, t);
 
			ShowInfoF("Unknown debug level '%.*s'", (int)(s - t), t);
 
			return;
 
		}
 
	}
 
}
 

	
 
/** 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;
src/debug.h
Show inline comments
 
@@ -41,37 +41,30 @@
 
	extern int _debug_net_level;
 
	extern int _debug_sprite_level;
 
	extern int _debug_oldloader_level;
 
	extern int _debug_ntp_level;
 
	extern int _debug_npf_level;
 
	extern int _debug_yapf_level;
 
	extern int _debug_freetype_level;
 
	extern int _debug_sl_level;
 
	extern int _debug_station_level;
 
	extern int _debug_gamelog_level;
 
	extern int _debug_desync_level;
 

	
 
	void CDECL debug(const char *dbg, ...);
 
	void CDECL debug(const char *dbg, const char *format, ...) WARN_FORMAT(2, 3);
 
#endif /* NO_DEBUG_MESSAGES */
 

	
 
void SetDebugString(const char *s);
 
const char *GetDebugString();
 

	
 
/* MSVCRT of course has to have a different syntax for long long *sigh* */
 
#if defined(_MSC_VER) || defined(__MINGW32__)
 
	#define OTTD_PRINTF64 "I64"
 
#else
 
	#define OTTD_PRINTF64 "ll"
 
#endif
 

	
 
/* Used for profiling
 
 *
 
 * Usage:
 
 * TIC();
 
 *   --Do your code--
 
 * TOC("A name", 1);
 
 *
 
 * When you run the TIC() / TOC() multiple times, you can increase the '1'
 
 *  to only display average stats every N values. Some things to know:
 
 *
 
 * for (int i = 0; i < 5; i++) {
 
 *   TIC();
 
@@ -91,15 +84,15 @@ const char *GetDebugString();
 
	static uint32 __i__ = 0;
 

	
 
#define TOC(str, count)\
 
	__sum__ += ottd_rdtsc() - _xxx_;\
 
	if (++__i__ == count) {\
 
		DEBUG(misc, 0, "[%s] %" OTTD_PRINTF64 "u [avg: %.1f]\n", str, __sum__, __sum__/(double)__i__);\
 
		__i__ = 0;\
 
		__sum__ = 0;\
 
	}\
 
}
 

	
 
void ShowInfo(const char *str);
 
void CDECL ShowInfoF(const char *str, ...);
 
void CDECL ShowInfoF(const char *str, ...) WARN_FORMAT(1, 2);
 

	
 
#endif /* DEBUG_H */
src/fileio.cpp
Show inline comments
 
@@ -586,44 +586,44 @@ bool TarListAddFile(const char *filename
 
			len = strlen(name);
 
			name[len] = PATHSEPCHAR;
 
			len++;
 
		}
 

	
 
		/* Copy the name of the file in a safe way at the end of 'name' */
 
		memcpy(&name[len], th.name, sizeof(th.name));
 
		name[len + sizeof(th.name)] = '\0';
 

	
 
		/* Calculate the size of the file.. for some strange reason this is stored as a string */
 
		memcpy(buf, th.size, sizeof(th.size));
 
		buf[sizeof(th.size)] = '\0';
 
		int skip = strtol(buf, &end, 8);
 
		size_t skip = strtoul(buf, &end, 8);
 

	
 
		switch (th.typeflag) {
 
			case '\0':
 
			case '0': { // regular file
 
				/* Ignore empty files */
 
				if (skip == 0) break;
 

	
 
				if (strlen(name) == 0) break;
 

	
 
				/* Store this entry in the list */
 
				TarFileListEntry entry;
 
				entry.tar_filename = dupped_filename;
 
				entry.size         = skip;
 
				entry.position     = pos;
 

	
 
				/* Convert to lowercase and our PATHSEPCHAR */
 
				SimplifyFileName(name);
 

	
 
				DEBUG(misc, 6, "Found file in tar: %s (%d bytes, %d offset)", name, skip, pos);
 
				DEBUG(misc, 6, "Found file in tar: %s (" PRINTF_SIZE " bytes, " PRINTF_SIZE " offset)", name, skip, pos);
 
				if (_tar_filelist.insert(TarFileList::value_type(name, entry)).second) num++;
 

	
 
				break;
 
			}
 

	
 
			case '1': // hard links
 
			case '2': { // symbolic links
 
				/* Copy the destination of the link in a safe way at the end of 'linkname' */
 
				memcpy(link, th.linkname, sizeof(th.linkname));
 
				link[sizeof(th.linkname)] = '\0';
 

	
 
				if (strlen(name) == 0 || strlen(link) == 0) break;
 
@@ -693,25 +693,25 @@ bool TarListAddFile(const char *filename
 

	
 
			default:
 
				/* Ignore other types */
 
				break;
 
		}
 

	
 
		/* Skip to the next block.. */
 
		skip = Align(skip, 512);
 
		fseek(f, skip, SEEK_CUR);
 
		pos += skip;
 
	}
 

	
 
	DEBUG(misc, 1, "Found tar '%s' with %d new files", filename, num);
 
	DEBUG(misc, 1, "Found tar '%s' with " PRINTF_SIZE " new files", filename, num);
 
	fclose(f);
 

	
 
	/* Resolve file links and store directory links.
 
	 * We restrict usage of links to two cases:
 
	 *  1) Links to directories:
 
	 *      Both the source path and the destination path must NOT contain any further links.
 
	 *      When resolving files at most one directory link is resolved.
 
	 *  2) Links to files:
 
	 *      The destination path must NOT contain any links.
 
	 *      The source path may contain one directory link.
 
	 */
 
	for (TarLinkList::iterator link = links.begin(); link != links.end(); link++) {
src/gamelog.cpp
Show inline comments
 
@@ -76,24 +76,26 @@ void GamelogReset()
 

	
 
	_gamelog_action  = NULL;
 
	_gamelog_actions = 0;
 
	_current_action  = NULL;
 
}
 

	
 
enum {
 
	GAMELOG_BUF_LEN = 1024 ///< length of buffer for one line of text
 
};
 

	
 
static int _dbgofs = 0; ///< offset in current output buffer
 

	
 
static void AddDebugText(char *buf, const char *s, ...) WARN_FORMAT(2, 3);
 

	
 
static void AddDebugText(char *buf, const char *s, ...)
 
{
 
	if (GAMELOG_BUF_LEN <= _dbgofs) return;
 

	
 
	va_list va;
 

	
 
	va_start(va, s);
 
	_dbgofs += vsnprintf(buf + _dbgofs, GAMELOG_BUF_LEN - _dbgofs, s, va);
 
	va_end(va);
 
}
 

	
 

	
 
@@ -268,25 +270,25 @@ static void GamelogPrintConsoleProc(cons
 
	IConsolePrint(CC_WARNING, s);
 
}
 

	
 
void GamelogPrintConsole()
 
{
 
	GamelogPrint(&GamelogPrintConsoleProc);
 
}
 

	
 
static int _gamelog_print_level = 0; ///< gamelog debug level we need to print stuff
 

	
 
static void GamelogPrintDebugProc(const char *s)
 
{
 
	DEBUG(gamelog, _gamelog_print_level, s);
 
	DEBUG(gamelog, _gamelog_print_level, "%s", s);
 
}
 

	
 

	
 
/** Prints gamelog to debug output. Code is executed even when
 
 * there will be no output. It is called very seldom, so it
 
 * doesn't matter that much. At least it gives more uniform code...
 
 * @param level debug level we need to print stuff
 
 */
 
void GamelogPrintDebug(int level)
 
{
 
	_gamelog_print_level = level;
 
	GamelogPrint(&GamelogPrintDebugProc);
src/gfxinit.cpp
Show inline comments
 
@@ -241,25 +241,25 @@ void CheckExternalFiles()
 
		}
 
	}
 

	
 
	bool sound = false;
 
	for (uint i = 0; !sound && i < lengthof(_sound_sets); i++) {
 
		sound = FileMD5(_sound_sets[i]);
 
	}
 

	
 
	if (!sound) {
 
		add_pos += seprintf(add_pos, last, "Your 'sample.cat' file is corrupted or missing! You can find 'sample.cat' on your Transport Tycoon Deluxe CD-ROM.\n");
 
	}
 

	
 
	if (add_pos != error_msg) ShowInfoF(error_msg);
 
	if (add_pos != error_msg) ShowInfoF("%s", error_msg);
 
}
 

	
 

	
 
static void LoadSpriteTables()
 
{
 
	memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf));
 
	uint i = FIRST_GRF_SLOT;
 

	
 
	_palette_remap_grf[i] = (_use_palette != _used_graphics_set->palette);
 
	LoadGrfFile(_used_graphics_set->files[GFT_BASE].filename, 0, i++);
 

	
 
	/*
src/network/network_command.cpp
Show inline comments
 
@@ -170,19 +170,19 @@ void NetworkClientSocket::Send_Command(P
 
	p->Send_uint32(cp->cmd);
 
	p->Send_uint32(cp->p1);
 
	p->Send_uint32(cp->p2);
 
	p->Send_uint32(cp->tile);
 
	p->Send_string(cp->text);
 

	
 
	byte callback = 0;
 
	while (callback < _callback_table_count && _callback_table[callback] != cp->callback) {
 
		callback++;
 
	}
 

	
 
	if (callback == _callback_table_count) {
 
		DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", callback);
 
		DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", cp->callback);
 
		callback = 0; // _callback_table[0] == NULL
 
	}
 
	p->Send_uint8 (callback);
 
}
 

	
 
#endif /* ENABLE_NETWORK */
src/network/network_func.h
Show inline comments
 
@@ -65,18 +65,18 @@ NetworkClientInfo *NetworkFindClientInfo
 
NetworkClientInfo *NetworkFindClientInfoFromIP(const char *ip);
 
const char *GetClientIP(NetworkClientInfo *ci);
 

	
 
void NetworkServerDoMove(ClientID client_id, CompanyID company_id);
 
void NetworkServerSendRcon(ClientID client_id, ConsoleColour colour_code, const char *string);
 
void NetworkServerSendError(ClientID client_id, NetworkErrorCode error);
 
void NetworkServerSendChat(NetworkAction action, DestType type, int dest, const char *msg, ClientID from_id, int64 data = 0);
 

	
 
void NetworkServerKickClient(ClientID client_id);
 
void NetworkServerBanIP(const char *banip);
 

	
 
void NetworkInitChatMessage();
 
void CDECL NetworkAddChatMessage(TextColour colour, uint8 duration, const char *message, ...);
 
void CDECL NetworkAddChatMessage(TextColour colour, uint8 duration, const char *message, ...) WARN_FORMAT(3, 4);
 
void NetworkUndrawChatMessage();
 
void NetworkChatMessageDailyLoop();
 

	
 
#endif /* ENABLE_NETWORK */
 
#endif /* NETWORK_FUNC_H */
src/newgrf.cpp
Show inline comments
 
@@ -141,25 +141,25 @@ void CDECL grfmsg(int severity, const ch
 
	va_list va;
 

	
 
	va_start(va, str);
 
	vsnprintf(buf, sizeof(buf), str, va);
 
	va_end(va);
 

	
 
	DEBUG(grf, severity, "[%s:%d] %s", _cur_grfconfig->filename, _nfo_line, buf);
 
}
 

	
 
static inline bool check_length(size_t real, size_t wanted, const char *str)
 
{
 
	if (real >= wanted) return true;
 
	grfmsg(0, "%s: Invalid pseudo sprite length %d (expected %d)!", str, real, wanted);
 
	grfmsg(0, "%s: Invalid pseudo sprite length " PRINTF_SIZE " (expected " PRINTF_SIZE ")!", str, real, wanted);
 
	return false;
 
}
 

	
 
static inline byte grf_load_byte(byte **buf)
 
{
 
	return *(*buf)++;
 
}
 

	
 
static uint16 grf_load_word(byte **buf)
 
{
 
	uint16 val = grf_load_byte(buf);
 
	return val | (grf_load_byte(buf) << 8);
 
@@ -4218,25 +4218,25 @@ static void GRFInfo(byte *buf, size_t le
 
		_cur_grfconfig->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
 
		_cur_grfconfig->error->message  = STR_NEWGRF_ERROR_MULTIPLE_ACTION_8;
 

	
 
		_skip_sprites = -1;
 
		return;
 
	}
 

	
 
	_cur_grffile->grfid = grfid;
 
	_cur_grffile->grf_version = version;
 
	_cur_grfconfig->status = _cur_stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
 

	
 
	/* Do swap the GRFID for displaying purposes since people expect that */
 
	DEBUG(grf, 1, "GRFInfo: Loaded GRFv%d set %08lX - %s (palette: %s)", version, BSWAP32(grfid), name, _cur_grfconfig->windows_paletted ? "Windows" : "DOS");
 
	DEBUG(grf, 1, "GRFInfo: Loaded GRFv%d set %08X - %s (palette: %s)", version, BSWAP32(grfid), name, _cur_grfconfig->windows_paletted ? "Windows" : "DOS");
 
}
 

	
 
/* Action 0x0A */
 
static void SpriteReplace(byte *buf, size_t len)
 
{
 
	/* <0A> <num-sets> <set1> [<set2> ...]
 
	 * <set>: <num-sprites> <first-sprite>
 
	 *
 
	 * B num-sets      How many sets of sprites to replace.
 
	 * Each set:
 
	 * B num-sprites   How many sprites are in this set
 
	 * W first-sprite  First sprite number to replace */
 
@@ -4395,25 +4395,25 @@ static void GRFLoadError(byte *buf, size
 

	
 
/* Action 0x0C */
 
static void GRFComment(byte *buf, size_t len)
 
{
 
	/* <0C> [<ignored...>]
 
	 *
 
	 * V ignored       Anything following the 0C is ignored */
 

	
 
	if (len == 1) return;
 

	
 
	size_t text_len = len - 1;
 
	const char *text = (const char*)(buf + 1);
 
	grfmsg(2, "GRFComment: %.*s", text_len, text);
 
	grfmsg(2, "GRFComment: %.*s", (int)text_len, text);
 
}
 

	
 
/* Action 0x0D (GLS_SAFETYSCAN) */
 
static void SafeParamSet(byte *buf, size_t len)
 
{
 
	if (!check_length(len, 5, "SafeParamSet")) return;
 
	buf++;
 
	uint8 target = grf_load_byte(&buf);
 

	
 
	/* Only writing GRF parameters is considered safe */
 
	if (target < 0x80) return;
 

	
 
@@ -4937,25 +4937,25 @@ static void FeatureTownName(byte *buf, s
 

	
 
			if (!check_length(len, 1, "FeatureTownName: lang_id")) return;
 
			lang = grf_load_byte(&buf);
 
			len--;
 
		} while (lang != 0);
 
		townname->id[nb_gen] = id;
 
		townname->nb_gen++;
 
	}
 

	
 
	if (!check_length(len, 1, "FeatureTownName: number of parts")) return;
 
	byte nb = grf_load_byte(&buf);
 
	len--;
 
	grfmsg(6, "FeatureTownName: %d parts", nb, nb);
 
	grfmsg(6, "FeatureTownName: %u parts", nb);
 

	
 
	townname->nbparts[id] = nb;
 
	townname->partlist[id] = CallocT<NamePartList>(nb);
 

	
 
	for (int i = 0; i < nb; i++) {
 
		if (!check_length(len, 3, "FeatureTownName: parts header")) return;
 
		byte nbtext =  grf_load_byte(&buf);
 
		townname->partlist[id][i].bitstart  = grf_load_byte(&buf);
 
		townname->partlist[id][i].bitcount  = grf_load_byte(&buf);
 
		townname->partlist[id][i].maxprob   = 0;
 
		townname->partlist[id][i].partcount = nbtext;
 
		townname->partlist[id][i].parts     = CallocT<NamePart>(nbtext);
src/newgrf.h
Show inline comments
 
@@ -120,20 +120,20 @@ struct GRFLoadedFeatures {
 
	bool has_newhouses;       ///< Set if there are any newhouses loaded.
 
	bool has_newindustries;   ///< Set if there are any newindustries loaded.
 
	ShoreReplacement shore;   ///< It which way shore sprites were replaced.
 
};
 

	
 
/* Indicates which are the newgrf features currently loaded ingame */
 
extern GRFLoadedFeatures _loaded_newgrf_features;
 

	
 
void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage);
 
void LoadNewGRF(uint load_index, uint file_index);
 
void ReloadNewGRFData(); // in saveload/afterload.cpp
 

	
 
void CDECL grfmsg(int severity, const char *str, ...);
 
void CDECL grfmsg(int severity, const char *str, ...) WARN_FORMAT(2, 3);
 

	
 
bool HasGrfMiscBit(GrfMiscBit bit);
 
bool GetGlobalVariable(byte param, uint32 *value);
 

	
 
StringID MapGRFStringID(uint32 grfid, StringID str);
 

	
 
#endif /* NEWGRF_H */
src/newgrf_engine.cpp
Show inline comments
 
@@ -794,25 +794,25 @@ static uint32 VehicleGetVariable(const R
 

	
 
		case VEH_AIRCRAFT:
 
			switch (variable - 0x80) {
 
				case 0x62: return MapAircraftMovementState(v);  // Current movement state
 
				case 0x63: return v->u.air.targetairport;       // Airport to which the action refers
 
				case 0x66: return MapAircraftMovementAction(v); // Current movement action
 
			}
 
			break;
 

	
 
		default: break;
 
	}
 

	
 
	DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, v->type);
 
	DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, (uint)v->type);
 

	
 
	*available = false;
 
	return UINT_MAX;
 
}
 

	
 

	
 
static const SpriteGroup *VehicleResolveReal(const ResolverObject *object, const SpriteGroup *group)
 
{
 
	const Vehicle *v = object->u.vehicle.self;
 

	
 
	if (v == NULL) {
 
		if (group->g.real.num_loading > 0) return group->g.real.loading[0];
src/saveload/saveload.cpp
Show inline comments
 
@@ -1631,25 +1631,25 @@ static SaveOrLoadResult SaveFileToDisk(b
 
		GetSavegameFormat("memory")->uninit_write(); // clean the memorypool
 
		fclose(_sl.fh);
 

	
 
		if (threaded) SetAsyncSaveFinish(SaveFileDone);
 

	
 
		return SL_OK;
 
	}
 
	catch (...) {
 
		AbortSaveLoad();
 
		if (_sl.excpt_uninit != NULL) _sl.excpt_uninit();
 

	
 
		/* Skip the "colour" character */
 
		DEBUG(sl, 0, GetSaveLoadErrorString() + 3);
 
		DEBUG(sl, 0, "%s", GetSaveLoadErrorString() + 3);
 

	
 
		if (threaded) {
 
			SetAsyncSaveFinish(SaveFileError);
 
		} else {
 
			SaveFileError();
 
		}
 
		return SL_ERROR;
 
	}
 
}
 

	
 
static void SaveFileToDiskThread(void *arg)
 
{
 
@@ -1831,25 +1831,25 @@ SaveOrLoadResult SaveOrLoad(const char *
 
			GamelogStopAction();
 
		}
 

	
 
		return SL_OK;
 
	}
 
	catch (...) {
 
		AbortSaveLoad();
 

	
 
		/* deinitialize compressor. */
 
		if (_sl.excpt_uninit != NULL) _sl.excpt_uninit();
 

	
 
		/* Skip the "colour" character */
 
		DEBUG(sl, 0, GetSaveLoadErrorString() + 3);
 
		DEBUG(sl, 0, "%s", GetSaveLoadErrorString() + 3);
 

	
 
		/* A saver/loader exception!! reinitialize all variables to prevent crash! */
 
		return (mode == SL_LOAD) ? SL_REINIT : SL_ERROR;
 
	}
 
}
 

	
 
/** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
 
void DoExitSave()
 
{
 
	SaveOrLoad("exit.sav", SL_SAVE, AUTOSAVE_DIR);
 
}
 

	
src/spritecache.cpp
Show inline comments
 
@@ -43,25 +43,25 @@ static inline SpriteCache *GetSpriteCach
 

	
 
static inline bool IsMapgenSpriteID(SpriteID sprite)
 
{
 
	return IsInsideMM(sprite, 4845, 4882);
 
}
 

	
 
static SpriteCache *AllocateSpriteCache(uint index)
 
{
 
	if (index >= _spritecache_items) {
 
		/* Add another 1024 items to the 'pool' */
 
		uint items = Align(index + 1, 1024);
 

	
 
		DEBUG(sprite, 4, "Increasing sprite cache to %d items (%d bytes)", items, items * sizeof(*_spritecache));
 
		DEBUG(sprite, 4, "Increasing sprite cache to %u items (" PRINTF_SIZE " bytes)", items, items * sizeof(*_spritecache));
 

	
 
		_spritecache = ReallocT(_spritecache, items);
 

	
 
		/* Reset the new items and update the count */
 
		memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
 
		_spritecache_items = items;
 
	}
 

	
 
	return GetSpriteCache(index);
 
}
 

	
 

	
 
@@ -324,25 +324,25 @@ static size_t GetSpriteCacheUsage()
 
	}
 

	
 
	return tot_size;
 
}
 

	
 

	
 
void IncreaseSpriteLRU()
 
{
 
	/* Increase all LRU values */
 
	if (_sprite_lru_counter > 16384) {
 
		SpriteID i;
 

	
 
		DEBUG(sprite, 3, "Fixing lru %d, inuse=%d", _sprite_lru_counter, GetSpriteCacheUsage());
 
		DEBUG(sprite, 3, "Fixing lru %u, inuse=" PRINTF_SIZE, _sprite_lru_counter, GetSpriteCacheUsage());
 

	
 
		for (i = 0; i != _spritecache_items; i++) {
 
			SpriteCache *sc = GetSpriteCache(i);
 
			if (sc->ptr != NULL) {
 
				if (sc->lru >= 0) {
 
					sc->lru = -1;
 
				} else if (sc->lru != -32768) {
 
					sc->lru--;
 
				}
 
			}
 
		}
 
		_sprite_lru_counter = 0;
 
@@ -352,25 +352,25 @@ void IncreaseSpriteLRU()
 
	if (++_compact_cache_counter >= 740) {
 
		CompactSpriteCache();
 
		_compact_cache_counter = 0;
 
	}
 
}
 

	
 
/** Called when holes in the sprite cache should be removed.
 
 * That is accomplished by moving the cached data. */
 
static void CompactSpriteCache()
 
{
 
	MemBlock *s;
 

	
 
	DEBUG(sprite, 3, "Compacting sprite cache, inuse=%d", GetSpriteCacheUsage());
 
	DEBUG(sprite, 3, "Compacting sprite cache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
 

	
 
	for (s = _spritecache_ptr; s->size != 0;) {
 
		if (s->size & S_FREE_MASK) {
 
			MemBlock *next = NextBlock(s);
 
			MemBlock temp;
 
			SpriteID i;
 

	
 
			/* Since free blocks are automatically coalesced, this should hold true. */
 
			assert(!(next->size & S_FREE_MASK));
 

	
 
			/* If the next block is the sentinel block, we can safely return */
 
			if (next->size == 0) break;
 
@@ -395,25 +395,25 @@ static void CompactSpriteCache()
 
			s = NextBlock(s);
 
		}
 
	}
 
}
 

	
 
static void DeleteEntryFromSpriteCache()
 
{
 
	SpriteID i;
 
	uint best = UINT_MAX;
 
	MemBlock *s;
 
	int cur_lru;
 

	
 
	DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=%d", GetSpriteCacheUsage());
 
	DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
 

	
 
	cur_lru = 0xffff;
 
	for (i = 0; i != _spritecache_items; i++) {
 
		SpriteCache *sc = GetSpriteCache(i);
 
		if (sc->ptr != NULL && sc->lru < cur_lru) {
 
			cur_lru = sc->lru;
 
			best = i;
 
		}
 
	}
 

	
 
	/* Display an error message and die, in case we found no sprite at all.
 
	 * This shouldn't really happen, unless all sprites are locked. */
src/stdafx.h
Show inline comments
 
@@ -117,36 +117,40 @@
 
#endif /* PSP */
 

	
 
/* by default we use [] var arrays */
 
#define VARARRAY_SIZE
 

	
 
/* Stuff for GCC */
 
#if defined(__GNUC__)
 
	#define NORETURN __attribute__ ((noreturn))
 
	#define FORCEINLINE inline
 
	#define CDECL
 
	#define __int64 long long
 
	#define GCC_PACK __attribute__((packed))
 
	/* Warn about functions using 'printf' format syntax. First argument determines which parameter
 
	 * is the format string, second argument is start of values passed to printf. */
 
	#define WARN_FORMAT(string, args) __attribute__ ((format (printf, string, args)))
 

	
 
	#if (__GNUC__ == 2)
 
		#undef VARARRAY_SIZE
 
		#define VARARRAY_SIZE 0
 
	#endif
 
#endif /* __GNUC__ */
 

	
 
#if defined(__WATCOMC__)
 
	#define NORETURN
 
	#define FORCEINLINE inline
 
	#define CDECL
 
	#define GCC_PACK
 
	#define WARN_FORMAT(string, args)
 
	#include <malloc.h>
 
#endif /* __WATCOMC__ */
 

	
 
#if defined(__MINGW32__) || defined(__CYGWIN__)
 
	#include <malloc.h> // alloca()
 
#endif
 

	
 
#if defined(WIN32)
 
	#define WIN32_LEAN_AND_MEAN     // Exclude rarely-used stuff from Windows headers
 
#endif
 

	
 
/* Stuff for MSVC */
 
@@ -168,35 +172,36 @@
 

	
 
	#if (_MSC_VER < 1400)                   // MSVC 2005 safety checks
 
		#error "Only MSVC 2005 or higher are supported. MSVC 2003 and earlier are not! Upgrade your compiler."
 
	#endif /* (_MSC_VER < 1400) */
 
	#pragma warning(disable: 4996)   // 'strdup' was declared deprecated
 
	#define _CRT_SECURE_NO_DEPRECATE // all deprecated 'unsafe string functions
 
	#pragma warning(disable: 6308)   // code analyzer: 'realloc' might return null pointer: assigning null pointer to 't_ptr', which is passed as an argument to 'realloc', will cause the original memory block to be leaked
 
	#pragma warning(disable: 6011)   // code analyzer: Dereferencing NULL pointer 'pfGetAddrInfo': Lines: 995, 996, 998, 999, 1001
 
	#pragma warning(disable: 6326)   // code analyzer: potential comparison of a constant with another constant
 
	#pragma warning(disable: 6031)   // code analyzer: Return value ignored: 'ReadFile'
 
	#pragma warning(disable: 6255)   // code analyzer: _alloca indicates failure by raising a stack overflow exception. Consider using _malloca instead
 
	#pragma warning(disable: 6246)   // code analyzer: Local declaration of 'statspec' hides declaration of the same name in outer scope. For additional information, see previous declaration at ...
 
	#define WARN_FORMAT(string, args)
 

	
 
	#include <malloc.h> // alloca()
 
	#define NORETURN __declspec(noreturn)
 
	#define FORCEINLINE __forceinline
 
	#define inline _inline
 

	
 
	#if !defined(WINCE)
 
		#define CDECL _cdecl
 
	#endif
 

	
 
	int CDECL snprintf(char *str, size_t size, const char *format, ...);
 
	int CDECL snprintf(char *str, size_t size, const char *format, ...) WARN_FORMAT(3, 4);
 
	#if defined(WINCE)
 
		int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap);
 
	#endif
 

	
 
	#if defined(WIN32) && !defined(_WIN64) && !defined(WIN64)
 
		#if !defined(_W64)
 
			#define _W64
 
		#endif
 

	
 
		typedef _W64 int INT_PTR, *PINT_PTR;
 
		typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;
 
	#endif /* WIN32 && !_WIN64 && !WIN64 */
 
@@ -215,25 +220,25 @@
 
		#endif
 
	#endif
 

	
 
	#if defined(WINCE)
 
		#define strcasecmp _stricmp
 
		#define strncasecmp _strnicmp
 
		#undef DEBUG
 
	#else
 
		#define strcasecmp stricmp
 
		#define strncasecmp strnicmp
 
	#endif
 

	
 
	void SetExceptionString(const char *s, ...);
 
	void SetExceptionString(const char *s, ...) WARN_FORMAT(1, 2);
 

	
 
	#if defined(NDEBUG) && defined(WITH_ASSERT)
 
		#undef assert
 
		#define assert(expression) if (!(expression)) { SetExceptionString("Assertion failed at %s:%d: %s", __FILE__, __LINE__, #expression); *(byte*)0 = 0; }
 
	#endif
 

	
 
	/* MSVC doesn't have these :( */
 
	#define S_ISDIR(mode) (mode & S_IFDIR)
 
	#define S_ISREG(mode) (mode & S_IFREG)
 

	
 
#endif /* defined(_MSC_VER) */
 

	
 
@@ -263,24 +268,33 @@
 
		const char *OTTD2FS(const char *name);
 
	#endif /* WIN32 */
 
#endif /* STRGEN */
 

	
 
#if defined(WIN32) || defined(WIN64) || defined(__OS2__) && !defined(__INNOTEK_LIBC__)
 
	#define PATHSEP "\\"
 
	#define PATHSEPCHAR '\\'
 
#else
 
	#define PATHSEP "/"
 
	#define PATHSEPCHAR '/'
 
#endif
 

	
 
/* MSVCRT of course has to have a different syntax for long long *sigh* */
 
#if defined(_MSC_VER) || defined(__MINGW32__)
 
	#define OTTD_PRINTF64 "%I64d"
 
	#define PRINTF_SIZE "%Iu"
 
#else
 
	#define OTTD_PRINTF64 "%lld"
 
	#define PRINTF_SIZE "%zu"
 
#endif
 

	
 
typedef unsigned char byte;
 

	
 
/* This is already defined in unix, but not in QNX Neutrino (6.x)*/
 
#if (!defined(UNIX) && !defined(__CYGWIN__) && !defined(__BEOS__) && !defined(__MORPHOS__)) || defined(__QNXNTO__)
 
	typedef unsigned int uint;
 
#endif
 

	
 
#if !defined(__BEOS__) && !defined(__NDS__) /* Already defined on BEOS and NDS */
 
	typedef unsigned char    uint8;
 
	typedef   signed char     int8;
 
	typedef unsigned short   uint16;
 
	typedef   signed short    int16;
 
@@ -337,26 +351,26 @@ assert_compile(sizeof(uint8)  == 1);
 
#if !defined(offsetof)
 
	#define offsetof(s, m) cpp_offsetof(s, m)
 
#endif /* offsetof */
 

	
 

	
 
/* take care of some name clashes on MacOS */
 
#if defined(__APPLE__)
 
	#define GetString OTTD_GetString
 
	#define DrawString OTTD_DrawString
 
	#define CloseConnection OTTD_CloseConnection
 
#endif /* __APPLE__ */
 

	
 
void NORETURN CDECL usererror(const char *str, ...);
 
void NORETURN CDECL error(const char *str, ...);
 
void NORETURN CDECL usererror(const char *str, ...) WARN_FORMAT(1, 2);
 
void NORETURN CDECL error(const char *str, ...) WARN_FORMAT(1, 2);
 
#define NOT_REACHED() error("NOT_REACHED triggered at line %i of %s", __LINE__, __FILE__)
 

	
 
#if defined(MORPHOS) || defined(__NDS__) || defined(__DJGPP__)
 
	/* MorphOS and NDS don't have C++ conformant _stricmp... */
 
	#define _stricmp stricmp
 
#elif defined(OPENBSD)
 
	/* OpenBSD uses strcasecmp(3) */
 
	#define _stricmp strcasecmp
 
#endif
 

	
 
#if !defined(MORPHOS) && !defined(OPENBSD) && !defined(__NDS__) && !defined(__DJGPP__)
 
	/* NDS, MorphOS & OpenBSD don't know wchars, the rest does :( */
src/strgen/strgen.cpp
Show inline comments
 
@@ -127,35 +127,39 @@ static LangString *HashFind(const char *
 
		if (strcmp(ls->name, s) == 0) return ls;
 
		idx = ls->hash_next;
 
	}
 
	return NULL;
 
}
 

	
 
#ifdef _MSC_VER
 
# define LINE_NUM_FMT "(%d)"
 
#else
 
# define LINE_NUM_FMT ":%d"
 
#endif
 

	
 
static void CDECL strgen_warning(const char *s, ...) WARN_FORMAT(1, 2);
 

	
 
static void CDECL strgen_warning(const char *s, ...)
 
{
 
	char buf[1024];
 
	va_list va;
 
	va_start(va, s);
 
	vsnprintf(buf, lengthof(buf), s, va);
 
	va_end(va);
 
	fprintf(stderr, "%s" LINE_NUM_FMT ": warning: %s\n", _file, _cur_line, buf);
 
	_warnings++;
 
}
 

	
 
static void CDECL strgen_error(const char *s, ...) WARN_FORMAT(1, 2);
 

	
 
static void CDECL strgen_error(const char *s, ...)
 
{
 
	char buf[1024];
 
	va_list va;
 
	va_start(va, s);
 
	vsnprintf(buf, lengthof(buf), s, va);
 
	va_end(va);
 
	fprintf(stderr, "%s" LINE_NUM_FMT ": error: %s\n", _file, _cur_line, buf);
 
	_errors++;
 
}
 

	
 
void NORETURN CDECL error(const char *s, ...)
 
@@ -454,25 +458,25 @@ static const CmdStruct *ParseCommandStri
 
		if (*end != ':') error("missing arg #");
 
		s = end + 1;
 
	}
 

	
 
	/* parse command name */
 
	start = s;
 
	do {
 
		c = *s++;
 
	} while (c != '}' && c != ' ' && c != '=' && c != '.' && c != 0);
 

	
 
	cmd = FindCmd(start, s - start - 1);
 
	if (cmd == NULL) {
 
		strgen_error("Undefined command '%.*s'", s - start - 1, start);
 
		strgen_error("Undefined command '%.*s'", (int)(s - start - 1), start);
 
		return NULL;
 
	}
 

	
 
	if (c == '.') {
 
		const char *casep = s;
 

	
 
		if (!(cmd->flags & C_CASE))
 
			error("Command '%s' can't have a case", cmd->cmd);
 

	
 
		do c = *s++; while (c != '}' && c != ' ' && c != '\0');
 
		*casei = ResolveCaseName(casep, s - casep - 1);
 
	}
 
@@ -591,25 +595,25 @@ static void ExtractCommandString(ParsedC
 
		if (ar == NULL) break;
 

	
 
		/* Sanity checking */
 
		if (argno != -1 && ar->consumes == 0) error("Non consumer param can't have a paramindex");
 

	
 
		if (ar->consumes) {
 
			if (argno != -1) argidx = argno;
 
			if (argidx < 0 || (uint)argidx >= lengthof(p->cmd)) error("invalid param idx %d", argidx);
 
			if (p->cmd[argidx] != NULL && p->cmd[argidx] != ar) error("duplicate param idx %d", argidx);
 

	
 
			p->cmd[argidx++] = ar;
 
		} else if (!(ar->flags & C_DONTCOUNT)) { // Ignore some of them
 
			if (p->np >= lengthof(p->pairs)) error("too many commands in string, max %d", lengthof(p->pairs));
 
			if (p->np >= lengthof(p->pairs)) error("too many commands in string, max " PRINTF_SIZE, lengthof(p->pairs));
 
			p->pairs[p->np].a = ar;
 
			p->pairs[p->np].v = param[0] != '\0' ? strdup(param) : "";
 
			p->np++;
 
		}
 
	}
 
}
 

	
 

	
 
static const CmdStruct *TranslateCmdForCompare(const CmdStruct *a)
 
{
 
	if (a == NULL) return NULL;
 

	
 
@@ -725,25 +729,25 @@ static void HandleString(char *str, bool
 
		if (ent != NULL && casep == NULL) {
 
			strgen_error("String name '%s' is used multiple times", str);
 
			return;
 
		}
 

	
 
		if (ent == NULL && casep != NULL) {
 
			strgen_error("Base string name '%s' doesn't exist yet. Define it before defining a case.", str);
 
			return;
 
		}
 

	
 
		if (ent == NULL) {
 
			if (_strings[_next_string_id]) {
 
				strgen_error("String ID 0x%X for '%s' already in use by '%s'", ent, str, _strings[_next_string_id]->name);
 
				strgen_error("String ID 0x%X for '%s' already in use by '%s'", _next_string_id, str, _strings[_next_string_id]->name);
 
				return;
 
			}
 

	
 
			/* Allocate a new LangString */
 
			ent = CallocT<LangString>(1);
 
			_strings[_next_string_id] = ent;
 
			ent->index = _next_string_id++;
 
			ent->name = strdup(str);
 
			ent->line = _cur_line;
 

	
 
			HashAdd(str, ent);
 
		}
src/string_func.h
Show inline comments
 
@@ -80,27 +80,27 @@ char *strecat(char *dst, const char *src
 
 * check is performed.
 
 *
 
 * @note usage: strecpy(dst, src, lastof(dst));
 
 * @note lastof() applies only to fixed size arrays
 
 *
 
 * @param dst The destination buffer
 
 * @param src The buffer containing the string to copy
 
 * @param last The pointer to the last element of the destination buffer
 
 * @return The pointer to the terminating null-character in the destination buffer
 
 */
 
char *strecpy(char *dst, const char *src, const char *last);
 

	
 
int CDECL seprintf(char *str, const char *last, const char *format, ...);
 
int CDECL seprintf(char *str, const char *last, const char *format, ...) WARN_FORMAT(3, 4);
 

	
 
char *CDECL str_fmt(const char *str, ...);
 
char *CDECL str_fmt(const char *str, ...) WARN_FORMAT(1, 2);
 

	
 
/**
 
 * Scans the string for valid characters and if it finds invalid ones,
 
 * replaces them with a question mark '?' (if not ignored)
 
 * @param str the string to validate
 
 * @param last the last valid character of str
 
 * @param allow_newlines whether newlines should be allowed or ignored
 
 * @param ignore whether to ignore or replace with a question mark
 
 */
 
void str_validate(char *str, const char *last, bool allow_newlines = false, bool ignore = false);
 

	
 
/** Scans the string for colour codes and strips them */
src/win32.cpp
Show inline comments
 
@@ -1073,31 +1073,31 @@ void DetermineBasePaths(const char *exe)
 
	_searchpaths[SP_SHARED_DIR] = strdup(tmp);
 
#else
 
	_searchpaths[SP_PERSONAL_DIR] = NULL;
 
	_searchpaths[SP_SHARED_DIR]   = NULL;
 
#endif
 

	
 
	/* Get the path to working directory of OpenTTD */
 
	getcwd(tmp, lengthof(tmp));
 
	AppendPathSeparator(tmp, MAX_PATH);
 
	_searchpaths[SP_WORKING_DIR] = strdup(tmp);
 

	
 
	if (!GetModuleFileName(NULL, path, lengthof(path))) {
 
		DEBUG(misc, 0, "GetModuleFileName failed (%d)\n", GetLastError());
 
		DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
 
		_searchpaths[SP_BINARY_DIR] = NULL;
 
	} else {
 
		TCHAR exec_dir[MAX_PATH];
 
		_tcsncpy(path, MB_TO_WIDE_BUFFER(exe, path, lengthof(path)), lengthof(path));
 
		if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, NULL)) {
 
			DEBUG(misc, 0, "GetFullPathName failed (%d)\n", GetLastError());
 
			DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
 
			_searchpaths[SP_BINARY_DIR] = NULL;
 
		} else {
 
			strecpy(tmp, WIDE_TO_MB_BUFFER(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
 
			char *s = strrchr(tmp, PATHSEPCHAR);
 
			*(s + 1) = '\0';
 
			_searchpaths[SP_BINARY_DIR] = strdup(tmp);
 
		}
 
	}
 

	
 
	_searchpaths[SP_INSTALLATION_DIR]       = NULL;
 
	_searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
 
}
 
@@ -1272,44 +1272,44 @@ const TCHAR *OTTD2FS(const char *name)
 

	
 

	
 
/** Convert to OpenTTD's encoding from that of the environment in
 
 * UNICODE. OpenTTD encoding is UTF8, local is wide
 
 * @param name pointer to a valid string that will be converted
 
 * @param utf8_buf pointer to a valid buffer that will receive the converted string
 
 * @param buflen length in characters of the receiving buffer
 
 * @return pointer to utf8_buf. If conversion fails the string is of zero-length */
 
char *convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen)
 
{
 
	int len = WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8_buf, (int)buflen, NULL, NULL);
 
	if (len == 0) {
 
		DEBUG(misc, 0, "[utf8] W2M error converting wide-string. Errno %d", GetLastError());
 
		DEBUG(misc, 0, "[utf8] W2M error converting wide-string. Errno %lu", GetLastError());
 
		utf8_buf[0] = '\0';
 
	}
 

	
 
	return utf8_buf;
 
}
 

	
 

	
 
/** Convert from OpenTTD's encoding to that of the environment in
 
 * UNICODE. OpenTTD encoding is UTF8, local is wide
 
 * @param name pointer to a valid string that will be converted
 
 * @param utf16_buf pointer to a valid wide-char buffer that will receive the
 
 * converted string
 
 * @param buflen length in wide characters of the receiving buffer
 
 * @return pointer to utf16_buf. If conversion fails the string is of zero-length */
 
wchar_t *convert_to_fs(const char *name, wchar_t *utf16_buf, size_t buflen)
 
{
 
	int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, utf16_buf, (int)buflen);
 
	if (len == 0) {
 
		DEBUG(misc, 0, "[utf8] M2W error converting '%s'. Errno %d", name, GetLastError());
 
		DEBUG(misc, 0, "[utf8] M2W error converting '%s'. Errno %lu", name, GetLastError());
 
		utf16_buf[0] = '\0';
 
	}
 

	
 
	return utf16_buf;
 
}
 

	
 
/** Our very own SHGetFolderPath function for support of windows operating
 
 * systems that don't have this function (eg Win9x, etc.). We try using the
 
 * native function, and if that doesn't exist we will try a more crude approach
 
 * of environment variables and hope for the best */
 
HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
 
{
src/yapf/yapf_base.hpp
Show inline comments
 
@@ -146,25 +146,25 @@ public:
 
		perf.Stop();
 
		if (_debug_yapf_level >= 2) {
 
			int t = perf.Get(1000000);
 
			_total_pf_time_us += t;
 

	
 
			if (_debug_yapf_level >= 3) {
 
				UnitID veh_idx = (m_veh != NULL) ? m_veh->unitnumber : 0;
 
				char ttc = Yapf().TransportTypeChar();
 
				float cache_hit_ratio = (m_stats_cache_hits == 0) ? 0.0f : ((float)m_stats_cache_hits / (float)(m_stats_cache_hits + m_stats_cost_calcs) * 100.0f);
 
				int cost = bDestFound ? m_pBestDestNode->m_cost : -1;
 
				int dist = bDestFound ? m_pBestDestNode->m_estimate - m_pBestDestNode->m_cost : -1;
 

	
 
				DEBUG(yapf, 3, "[YAPF%c]%c%4d- %d us - %d rounds - %d open - %d closed - CHR %4.1f%% - c%d(sc%d, ts%d, o%d) -- ",
 
				DEBUG(yapf, 3, "[YAPF%c]%c%4d- %d us - %d rounds - %d open - %d closed - CHR %4.1f%% - C %d D %d - c%d(sc%d, ts%d, o%d) -- ",
 
				  ttc, bDestFound ? '-' : '!', veh_idx, t, m_num_steps, m_nodes.OpenCount(), m_nodes.ClosedCount(),
 
				  cache_hit_ratio, cost, dist, m_perf_cost.Get(1000000), m_perf_slope_cost.Get(1000000),
 
				  m_perf_ts_cost.Get(1000000), m_perf_other_cost.Get(1000000)
 
				);
 
			}
 
		}
 
#endif /* !NO_DEBUG_MESSAGES */
 
		return bDestFound;
 
	}
 

	
 
	/** If path was found return the best node that has reached the destination. Otherwise
 
	 *  return the best visited node (which was nearest to the destination).
0 comments (0 inline, 0 general)