OpenCBM
error.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version
5  * 2 of the License, or (at your option) any later version.
6  *
7  * Copyright 2004 Spiro Trikaliotis
8  *
9  */
10 
11 #include <windows.h>
12 
13 #include <stdarg.h>
14 #include <stdio.h>
15 #include <assert.h>
16 
17 #include "arch.h"
18 
19 
34 char *arch_strerror(unsigned int ErrorCode)
35 {
36  static char ErrorMessageBuffer[2048];
37  int n;
38 
39  // Write the error message into the buffer
40 
41  n = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS
42  | FORMAT_MESSAGE_MAX_WIDTH_MASK,
43  NULL,
44  ErrorCode,
45  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
46  (LPTSTR) &ErrorMessageBuffer,
47  sizeof(ErrorMessageBuffer)-1,
48  NULL);
49 
50  // make sure there is a trailing zero
51 
52  ErrorMessageBuffer[n] = 0;
53 
54  return ErrorMessageBuffer;
55 }
56 
73 void arch_error(int AUnused, unsigned int ErrorCode, const char *Format, ...)
74 {
75  va_list ap;
76  char ErrorMessageBuffer[2048];
77  char ErrorMessageBuffer2[2048];
78  char *errorText = NULL;
79 
80  UNREFERENCED_PARAMETER(AUnused);
81 
82  // Write the optional string into the output
83 
84  if (Format && *Format)
85  {
86  va_start(ap, Format);
87 
88  _vsnprintf(ErrorMessageBuffer2, sizeof(ErrorMessageBuffer2), Format, ap);
89 
90  va_end(ap);
91 
92  // make sure there is a trailing zero
93 
94  ErrorMessageBuffer2[sizeof(ErrorMessageBuffer2) - 1] = 0;
95  }
96 
97  // Get the error message
98 
99  if (ErrorCode != 0)
100  {
101  errorText = arch_strerror(ErrorCode);
102  }
103 
104  // Append the message to the buffer. Make sure not to overwrite the buffer
105 
106  if (errorText)
107  {
108  _snprintf(ErrorMessageBuffer, sizeof(ErrorMessageBuffer), "%s: %s", ErrorMessageBuffer2, errorText);
109 
110  ErrorMessageBuffer[sizeof(ErrorMessageBuffer)-1] = 0;
111  }
112  else
113  {
114  assert(sizeof(ErrorMessageBuffer) >= sizeof(ErrorMessageBuffer2));
115 
116  strcpy(ErrorMessageBuffer, ErrorMessageBuffer2);
117  }
118 
119  fprintf(stderr, "%s\n", ErrorMessageBuffer);
120 
121 #if DBG
122 
123  {
124  int n = strlen(ErrorMessageBuffer);
125 
126  if (n == sizeof(ErrorMessageBuffer))
127  --n;
128 
129  ErrorMessageBuffer[n] = '\n';
130  ErrorMessageBuffer[n+1] = 0;
131  OutputDebugString(ErrorMessageBuffer);
132  }
133 
134 #endif
135 }
Define makros and functions which account for differences between the different architectures.