1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//
// This file is part of the aMule Project.
//
// Copyright (c) 2005-2011 aMule Team ( admin@amule.org / http://www.amule.org )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
//

#include "Format.h"

#include "config.h"

#if defined HAVE_STDINT_H
#	include <stdint.h>
#elif defined HAVE_INTTYPES_H
#	include <inttypes.h>
#endif

#include <wx/intl.h>			// Needed for _()

#include <errno.h>			// Needed for errno and EINVAL
#include "strerror_r.h"			// Needed for mule_strerror_r()

/** Returns true if the char is a format-type. */
inline bool isTypeChar(wxChar c)
{
	switch (c) {
		case wxT('s'):		// String of characters
		case wxT('u'):		// Unsigned decimal integer
		case wxT('i'):		// Signed decimal integer
		case wxT('d'):		// Signed decimal integer
		case wxT('c'):		// Character
		case wxT('f'):		// Decimal floating point
		case wxT('F'):		// Decimal floating point
		case wxT('x'):		// Unsigned hexadecimal integer
		case wxT('X'):		// Unsigned hexadecimal integer (capital letters)
		case wxT('o'):		// Unsigned octal
		case wxT('e'):		// Scientific notation (mantise/exponent) using e character
		case wxT('E'):		// Scientific notation (mantise/exponent) using E character
		case wxT('g'):		// Use shorter %e or %f
		case wxT('G'):		// Use shorter %E or %F
		case wxT('p'):		// Pointer
		case wxT('n'):		// Not supported, still needs to be caught though
		case wxT('a'):		// (C99; not in SUSv2) Double in hexadecimal notation.
		case wxT('A'):		// (C99; not in SUSv2) Double in hexadecimal notation (capital letters).
		case wxT('C'):		// (Not in C99, but in SUSv2.)  Synonym for lc.  Don't use. Not supported.
		case wxT('S'):		// (Not in C99, but in SUSv2.)  Synonym for ls.  Don't use. Not supported.
		case wxT('m'):		// (Glibc extension.)  Print output of strerror(errno).  No argument is required.
//		case wxT('%'):		// A `%' is written.  No argument is converted.  The complete conversion specification is `%%'.
			return true;
	}

	return false;
}

/** Returns true if the char is a valid flag. */
inline bool isFlagChar(wxChar c)
{
	switch (c) {
		// C standard flags
		case wxT('+'):		// Include sign for integers
		case wxT('-'):		// Left-align output
		case wxT('#'):		// Alternate form, varies
		case wxT(' '):		// Pad with spaces
		case wxT('0'):		// Pad with zeros
		// SUSv2
		case wxT('\''):		// For decimal conversion (i, d, u, f, F, g, G) the output is to be grouped with thousands' grouping characters if the locale information indicates any.
		// glibc 2.2
		case wxT('I'):		// For decimal integer conversion (i, d, u) the output uses the locale's alternative output digits, if any.
			return true;
	}

	return false;
}

/** Returns true if the char is a valid length modifier. */
inline bool isLengthChar(wxChar c)
{
	switch (c) {
		case wxT('h'):		// Short ('hh') and char ('h')
		case wxT('l'):		// Long ('l') and long long ('ll')
		case wxT('L'):		// Double long
		case wxT('z'):		// size_t
		case wxT('j'):		// intmax_t
		case wxT('t'):		// ptrdiff_t
		case wxT('q'):		// quad. Synonym for 'll'. Don't use.
			return true;
	}

	return false;
}

/** Returns true if the argument is a valid length modifier */
inline bool isValidLength(const wxString& str)
{
	return ((str == wxT("hh")) || (str == wxT("h")) ||
		(str == wxT("l")) || (str == wxT("ll")) ||
		(str == wxT("L")) || (str == wxT("z")) ||
		(str == wxT("j")) || (str == wxT("t")) ||
		(str == wxT("q")));
}


enum eStringParserStates {
	esNonFormat = 0,	// Not in a format string
	esFormatStart,		// Start of a format string
	esFormat,		// Inside a format string
	esFormatEnd,		// Finished reading a format string
	esInvalidFormat		// Invalid (incomplete) format specifier
};

/**
 * State machine to extract format specifiers from the string
 *
 * All format strings will be extracted, regardless whether they are valid or
 * not. Also '%%' is considered to be special format string which requires no
 * arguments, thus it will be extracted too (that is because it has to be
 * converted to '%').
 */
static eStringParserStates stringParser[][3] = {
			/* %-sign,		type-char,	other */
/* esNonFormat */	{ esFormatStart,	esNonFormat,	esNonFormat	},
/* esFormatStart */	{ esFormatEnd,		esFormatEnd,	esFormat	},
/* esFormat */		{ esInvalidFormat,	esFormatEnd,	esFormat	},
/* esFormatEnd */	{ esFormatStart,	esNonFormat,	esNonFormat	},
/* esInvalidFormat */	{ esFormatEnd,		esFormatEnd,	esFormat	}
};

enum eFormatParserStates {
	efStart = 0,	// Format string start
	efArgIndex,	// Argument index
	efArgIndexEnd,	// End of the argument index ('$' sign)
	efFlagChar,	// Flag character
	efWidth,	// Width field
	efPrecStart,	// Precision field start ('.' character)
	efPrecision,	// Precision field
	efLength,	// Length field
	// The following two are terminal states, they terminate processing
	efType,		// Type character
	efError		// Invalid format specifier
};

/**
 * State machine to parse format specifiers
 *
 * Format specifiers are expected to follow the following structure:
 *	%[argIndex$][Flags][Width][.Precision][Length]<Type>
 */
static eFormatParserStates formatParser[][7] = {
			/* [1-9],	'0',		flagChar,	'.',		lengthChar,	typeChar,	'$' */
/* efStart */		{ efArgIndex,	efFlagChar,	efFlagChar,	efPrecStart,	efLength,	efType,		efError, },
/* efArgIndex */	{ efArgIndex,	efArgIndex,	efError,	efPrecStart,	efLength,	efType,		efArgIndexEnd, },
/* efArgIndexEnd */	{ efWidth,	efFlagChar,	efFlagChar,	efPrecStart,	efLength,	efType,		efError, },
/* efFlagChar */	{ efWidth,	efError,	efError,	efPrecStart,	efLength,	efType,		efError, },
/* efWidth */		{ efWidth,	efWidth,	efError,	efPrecStart,	efLength,	efType,		efError, },
/* efPrecStart */	{ efPrecision,	efPrecision,	efError,	efError,	efLength,	efType,		efError, },
/* efPrecision */	{ efPrecision,	efPrecision,	efError,	efError,	efLength,	efType,		efError, },
/* efLength */		{ efError,	efError,	efError,	efError,	efLength,	efType,		efError, }
};

// Forward-declare the specialization for const wxString&, needed by the parser
template<> void CFormat::ProcessArgument(FormatList::iterator, const wxString&);

void CFormat::Init(const wxString& str)
{
	m_formatString = str;
	m_argIndex = 0;

	// Extract format-string-like substrings from the input
	{
		size_t formatStart = 0;
		eStringParserStates state = esNonFormat;
		for (size_t pos = 0; pos < str.length(); ++pos) {
			if (str[pos] == wxT('%')) {
				state = stringParser[state][0];
			} else if (isTypeChar(str[pos])) {
				state = stringParser[state][1];
			} else {
				state = stringParser[state][2];
			}
			switch (state) {
				case esInvalidFormat:
					wxFAIL_MSG(wxT("Invalid format specifier: ") + str.Mid(formatStart, pos - formatStart + 1));
				/* fall through */
				case esFormatStart:
					formatStart = pos;
					break;
				case esFormatEnd:
					{
						FormatSpecifier fs;
						fs.startPos = formatStart;
						fs.endPos = pos;
						fs.result = str.Mid(formatStart, pos - formatStart + 1);
						m_formats.push_back(fs);<--- Uninitialized variables: fs.argIndex, fs.width, fs.precision<--- Uninitialized struct member: fs.argIndex<--- Uninitialized struct member: fs.width<--- Uninitialized struct member: fs.precision
					}
				default:
					break;
			}
		}
		wxASSERT_MSG((state == esFormatEnd) || (state == esNonFormat), wxT("Incomplete format specifier: ") + str.Mid(formatStart));
	}

	// Parse the extracted format specifiers, removing invalid ones
	unsigned formatCount = 0;
	for (FormatList::iterator it = m_formats.begin(); it != m_formats.end();) {
		if (it->result == wxT("%%")) {
			it->argIndex = 0;
			it->result = wxT("%");
			++it;
		} else {
			it->argIndex = ++formatCount;
			it->flag = '\0';
			it->width = 0;
			it->precision = -1;
			it->type = '\0';
			unsigned num = 0;
			wxString lengthModifier;
			bool isPrecision = false;
			eFormatParserStates state = efStart;
			for (size_t pos = 1; pos < it->result.length(); ++pos) {
				wxChar c = it->result[pos];
				if ((c >= wxT('1')) && (c <= wxT('9'))) {
					state = formatParser[state][0];
				} else if (c == wxT('0')) {
					state = formatParser[state][1];
				} else if (isFlagChar(c)) {
					state = formatParser[state][2];
				} else if (c == wxT('.')) {
					state = formatParser[state][3];
				} else if (isLengthChar(c)) {
					state = formatParser[state][4];
				} else if (isTypeChar(c)) {
					state = formatParser[state][5];
				} else if (c == wxT('$')) {
					state = formatParser[state][6];
				} else {
					state = efError;
				}
				if ((c >= wxT('0')) && (c <= wxT('9'))) {
					num *= 10;
					num += (c - wxT('0'));
				}
				switch (state) {
					case efArgIndexEnd:
						it->argIndex = num;
						num = 0;
						break;
					case efFlagChar:
						it->flag = c;
						break;
					case efPrecStart:
						it->width = num;
						num = 0;
						isPrecision = true;
						break;
					case efLength:
						if (isPrecision) {
							it->precision = num;
						} else if (num > 0) {
							it->width = num;
						}
						num = 0;
						lengthModifier += c;
						if (!isValidLength(lengthModifier)) {
							state = efError;
						}
						break;
					case efType:
						if (isPrecision) {
							it->precision = num;
						} else if (num > 0) {
							it->width = num;
						}
						if (c == wxT('m')) {
							it->argIndex = 0;
							it->type = wxT('s');
							int errnum = errno;
#if defined(HAVE_STRERROR) || defined(HAVE_STRERROR_R)
							unsigned buflen = 256;
							bool done = false;
							do {
								errno = 0;
								char* buf = new char[buflen];
								*buf = '\0';
								int result = mule_strerror_r(errnum, buf, buflen);
								if ((result == 0) || (buflen > 1024)) {
									ProcessArgument<const wxString&>(it, wxString(buf, wxConvLocal));
								} else if (errno == EINVAL) {
									if (*buf == '\0') {
										ProcessArgument<const wxString&>(it, wxString::Format(_("Unknown error %d"), errnum));
									} else {
										ProcessArgument<const wxString&>(it, wxString(buf, wxConvLocal));
									}
								} else if (errno != ERANGE) {
									ProcessArgument<const wxString&>(it, wxString::Format(_("Unable to get error description for error %d"), errnum));
								} else {
									buflen <<= 1;
								}
								delete [] buf;
								done = ((result == 0) || (errno != ERANGE));
							} while (!done);
#else
							wxFAIL_MSG(wxString::Format(wxT("Unable to get error description for error %d."), errnum));
							ProcessArgument<const wxString&>(it, wxString::Format(_("Unable to get error description for error %d"), errnum));
#endif
						} else {
							it->type = c;
						}
					default:
						break;
				}
				wxCHECK2_MSG(state != efError, break, wxT("Invalid format specifier: ") + it->result);
				if (state == efType) {
					// Needed by the '%m' conversion, which takes place immediately,
					// overwriting it->result
					break;
				}
			}
			if (state == efError) {
				it = m_formats.erase(it);
				--formatCount;
			} else {
				++it;
			}
		}
	}
}

wxString CFormat::GetString() const
{
	wxString result;
	FormatList::const_iterator it = m_formats.begin();
	if (it == m_formats.end()) {
		result = m_formatString;
	} else {
		unsigned lastEnd = 0;
		for (; it != m_formats.end(); ++it) {
			result += m_formatString.Mid(lastEnd, it->startPos - lastEnd);
			result += it->result;
			lastEnd = it->endPos + 1;
		}
		result += m_formatString.Mid(lastEnd);
	}
	return result;
}

wxString CFormat::GetModifiers(FormatList::const_iterator it) const
{
	wxString result = wxT("%");
	if (it->flag != wxT('\0')) {
		result += it->flag;
	}
	if (it->width > 0) {
		result += wxString::Format(wxT("%u"), it->width);
	}
	if (it->precision >= 0) {
		result += wxString::Format(wxT(".%u"), it->precision);
	}
	return result;
}

// Forward-declare the specialization for unsigned long long
template<> void CFormat::ProcessArgument(FormatList::iterator, unsigned long long);

// Processing a double-precision floating-point argument
template<>
void CFormat::ProcessArgument(FormatList::iterator it, double value)
{
	switch (it->type) {
		case wxT('a'):
		case wxT('A'):
		case wxT('e'):
		case wxT('E'):
		case wxT('f'):
		case wxT('F'):
		case wxT('g'):
		case wxT('G'):
			break;
		case wxT('s'):
			it->type = wxT('g');
			break;
		default:
			wxFAIL_MSG(wxT("Floating-point value passed for non-floating-point format field: ") + it->result);
			return;
	}
	it->result = wxString::Format(GetModifiers(it) + it->type, value);
}

// Processing a wxChar argument
template<>
void CFormat::ProcessArgument(FormatList::iterator it, wxChar value)
{
	switch (it->type) {
		case wxT('c'):
			break;
		case wxT('s'):
			it->type = wxT('c');
			break;
		case wxT('u'):
		case wxT('d'):
		case wxT('i'):
		case wxT('o'):
		case wxT('x'):
		case wxT('X'):
			ProcessArgument(it, (unsigned long long)value);
			return;
		case wxT('a'):
		case wxT('A'):
		case wxT('e'):
		case wxT('E'):
		case wxT('f'):
		case wxT('F'):
		case wxT('g'):
		case wxT('G'):
			ProcessArgument(it, (double)value);
			return;
		default:
			wxFAIL_MSG(wxT("Character value passed to non-character format field: ") + it->result);
			return;
	}
	it->result = wxString::Format(GetModifiers(it) + it->type, value);
}

// Processing a signed long long argument
template<>
void CFormat::ProcessArgument(FormatList::iterator it, signed long long value)
{
	switch (it->type) {
		case wxT('c'):
			ProcessArgument(it, (wxChar)value);
			return;
		case wxT('i'):
			break;
		case wxT('o'):
		case wxT('x'):
		case wxT('X'):
			ProcessArgument(it, (unsigned long long)value);
			return;
		case wxT('u'):
		case wxT('d'):
		case wxT('s'):
			it->type = wxT('i');
			break;
		case wxT('a'):
		case wxT('A'):
		case wxT('e'):
		case wxT('E'):
		case wxT('f'):
		case wxT('F'):
		case wxT('g'):
		case wxT('G'):
			ProcessArgument(it, (double)value);
			return;
		default:
			wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it->result);
			return;
	}
	it->result = wxString::Format(GetModifiers(it) + WXLONGLONGFMTSPEC + it->type, value);
}

// Processing an unsigned long long argument
template<>
void CFormat::ProcessArgument(FormatList::iterator it, unsigned long long value)
{
	switch (it->type) {
		case wxT('c'):
			ProcessArgument(it, (wxChar)value);
			return;
		case wxT('u'):
		case wxT('o'):
		case wxT('x'):
		case wxT('X'):
			break;
		case wxT('i'):
		case wxT('d'):
		case wxT('s'):
			it->type = wxT('u');
			break;
		case wxT('a'):
		case wxT('A'):
		case wxT('e'):
		case wxT('E'):
		case wxT('f'):
		case wxT('F'):
		case wxT('g'):
		case wxT('G'):
			ProcessArgument(it, (double)value);
			return;
		default:
			wxFAIL_MSG(wxT("Integer value passed for non-integer format field: ") + it->result);
			return;
	}
	it->result = wxString::Format(GetModifiers(it) + WXLONGLONGFMTSPEC + it->type, value);
}

// Processing a wxString argument
template<>
void CFormat::ProcessArgument(FormatList::iterator it, const wxString& value)
{
	if (it->type != wxT('s')) {
		wxFAIL_MSG(wxT("String value passed for non-string format field: ") + it->result);
	} else {
		if (it->precision >= 0) {
			it->result = value.Left(it->precision);
		} else {
			it->result = value;
		}
		if ((it->width > 0) && (it->result.length() < it->width)) {
			if (it->flag == wxT('-')) {
				it->result += wxString(it->width - it->result.length(), wxT(' '));
			} else {
				it->result = wxString(it->width -it->result.length(), wxT(' ')) + it->result;
			}
		}
	}
}

// Processing pointer arguments
template<>
void CFormat::ProcessArgument(FormatList::iterator it, void * value)
{
	if ((it->type == wxT('p')) || (it->type == wxT('s'))) {
		// Modifiers (if any) are ignored for pointer conversions
		// built-in Format for pointer is not consistent:
		// - Windows: uppercase, no leading 0x
		// - Linux:   leading zeros missing
		// -> format it as hex
		if (sizeof(void*) == 8) {
			// 64 bit
			it->result = wxString::Format(wxString(wxT("0x%016")) + WXLONGLONGFMTSPEC + wxT("x"), (uintptr_t)value);
		} else {
			// 32 bit
			it->result = wxString::Format(wxT("0x%08x"), (uintptr_t)value);
		}
	} else {
		wxFAIL_MSG(wxT("Pointer value passed for non-pointer format field: ") + it->result);
	}
}


// Generic argument processor template
template<typename _Tp>
CFormat& CFormat::operator%(_Tp value)
{
	m_argIndex++;
	for (FormatList::iterator it = m_formats.begin(); it != m_formats.end(); ++it) {
		if (it->argIndex == m_argIndex) {
			if ((it->type != wxT('n')) && (it->type != wxT('C')) && (it->type != wxT('S'))) {
				ProcessArgument<_Tp>(it, value);
			} else {
				wxFAIL_MSG(wxT("Not supported conversion type in format field: ") + it->result);
			}
		}
	}
	return *this;
}

// explicit instatiation for the types we handle
template CFormat& CFormat::operator%<double>(double);
template CFormat& CFormat::operator%<wxChar>(wxChar);
template CFormat& CFormat::operator%<signed long long>(signed long long);
template CFormat& CFormat::operator%<unsigned long long>(unsigned long long);
template CFormat& CFormat::operator%<const wxString&>(const wxString&);
template CFormat& CFormat::operator%<void *>(void *);

// File_checked_for_headers