nulib2/nulib2/MiscUtils.c

122 lines
2.5 KiB
C
Raw Normal View History

2000-05-23 01:55:31 +00:00
/*
* Nulib2
2007-02-19 23:11:55 +00:00
* Copyright (C) 2000-2007 by Andy McFadden, All Rights Reserved.
2000-05-23 01:55:31 +00:00
* This is free software; you can redistribute it and/or modify it under the
2007-02-19 23:11:55 +00:00
* terms of the BSD License, see the file COPYING.
2000-05-23 01:55:31 +00:00
*
* Misc support functions.
*/
#define __MiscUtils_c__
#include "Nulib2.h"
/*
* Similar to perror(), but takes the error as an argument, and knows
* about NufxLib errors as well as system errors.
*
2014-12-22 02:17:23 +00:00
* If "format" is NULL, just the error message itself is printed.
2000-05-23 01:55:31 +00:00
*/
void
ReportError(NuError err, const char* format, ...)
{
const char* msg;
va_list args;
2014-12-22 02:17:23 +00:00
Assert(format != NULL);
va_start(args, format);
/* print the message, if any */
2014-12-22 02:17:23 +00:00
if (format != NULL) {
fprintf(stderr, "%s: ERROR: ", gProgName);
vfprintf(stderr, format, args);
}
/* print the error code data, if any */
if (err == kNuErrNone)
fprintf(stderr, "\n");
else {
2014-12-22 02:17:23 +00:00
if (format != NULL)
fprintf(stderr, ": ");
2014-12-22 02:17:23 +00:00
msg = NULL;
if (err >= 0)
msg = strerror(err);
2014-12-22 02:17:23 +00:00
if (msg == NULL)
msg = NuStrError(err);
2014-12-22 02:17:23 +00:00
if (msg == NULL)
fprintf(stderr, "(unknown err=%d)\n", err);
else
fprintf(stderr, "%s\n", msg);
}
va_end(args);
2000-05-23 01:55:31 +00:00
}
/*
* Memory allocation wrappers.
*
* Under gcc these would be macros, but not all compilers can handle that.
*/
#ifndef USE_DMALLOC
void*
Malloc(size_t size)
{
void* _result;
Assert(size > 0);
_result = malloc(size);
2014-12-22 02:17:23 +00:00
if (_result == NULL) {
ReportError(kNuErrMalloc, "malloc(%u) failed", (uint) size);
DebugAbort(); /* leave a core dump if we're built for it */
}
DebugFill(_result, size);
return _result;
2000-05-23 01:55:31 +00:00
}
void*
Calloc(size_t size)
{
void* _cresult = Malloc(size);
memset(_cresult, 0, size);
return _cresult;
2000-05-23 01:55:31 +00:00
}
void*
Realloc(void* ptr, size_t size)
{
void* _result;
2014-12-22 02:17:23 +00:00
Assert(ptr != NULL); /* disallow this usage */
Assert(size > 0); /* disallow this usage */
_result = realloc(ptr, size);
2014-12-22 02:17:23 +00:00
if (_result == NULL) {
ReportError(kNuErrMalloc, "realloc(%u) failed", (uint) size);
DebugAbort(); /* leave a core dump if we're built for it */
}
return _result;
2000-05-23 01:55:31 +00:00
}
void
Free(void* ptr)
{
2014-12-22 02:17:23 +00:00
if (ptr != NULL)
free(ptr);
2000-05-23 01:55:31 +00:00
}
#endif
/*
* This gets called when a buffer DataSource is no longer needed.
*/
NuResult
FreeCallback(NuArchive* pArchive, void* args)
{
DBUG(("+++ free callback 0x%08lx\n", (long) args));
Free(args);
return kNuOK;
}