void *MemAlloc (unsigned int size, char * var, char * pszFile, int nLine, int bZeroFill) { int *ptr; if (!bMemInitialized) MemInit (); if (!size) return NULL; if (nMemBlockId == nDbgMemBlockId) nDbgMemBlockId = nDbgMemBlockId; #if LONG_MEM_ID ptr = malloc (size + CHECKSIZE + sizeof (int) + 256); #else ptr = malloc (size + CHECKSIZE + sizeof (int)); #endif if (!ptr) { LogErr ("\nMEM_OUT_OF_MEMORY: Malloc returned NULL\n"); LogErr ("\tVar %s, file %s, nLine %d.\n", var, pszFile, nLine); Int3 (); return NULL; } #if LONG_MEM_ID sprintf ((char *) ptr, "%s:%d", pszFile, nLine); ptr = (int *) (((char *) ptr) + 256); #endif *ptr++ = size; nBytesMalloced += size; memset ((char *) ptr + size, CHECKBYTE, CHECKSIZE); if (bZeroFill) memset (ptr, 0, size); RegisterMemBlock (ptr, pszFile, nLine); return (void *) ptr; }
int main( int argc, char **argv ) { char buff[256]; TID tid; APIRET rc; MemInit(); getcmd( buff ); CmdData = buff; DebugMain(); _SwitchOff( SW_ERROR_STARTUP ); DoInput(); VarInitInfo( &Locals ); DosCreateEventSem( NULL, &Requestsem, 0, false ); DosCreateEventSem( NULL, &Requestdonesem, 0, false ); DosPostEventSem( Requestdonesem ); // signal req done rc = DosCreateThread( &tid, ControlFunc, 0, 0, 32768 ); if( rc != 0 ) { printf( "Stubugger: Error creating thread!\n" ); } while( !Done ) { DlgCmd(); } DosCloseEventSem( Requestsem ); DosCloseEventSem( Requestdonesem ); DebugFini(); RunRequest( REQ_BYE ); MemFini(); return( 0 ); }
int main(int argc, char **argv ) /******************************/ { int retval = 0; MemInit(); #if defined( _BETAVER ) put( banner1w1( "Far Call Optimization Enabling Utility" ) ); put( banner1w2( _FCENABLE_VERSION_ ) ); #else put( banner1w( "Far Call Optimization Enabling Utility", _FCENABLE_VERSION_ ) ); #endif put( banner2 ); put( banner2a( "1990" ) ); put( banner3 ); put( banner3a ); InputBuffer = InitRecStuff(); InFile = NOFILE; OutFile = NOFILE; ClassList = MemAlloc( sizeof( name_list ) + sizeof( DEF_CLASS ) - 1 ); ClassList->next = NULL; ClassList->lnameidx = 0; memcpy( ClassList->name, DEF_CLASS, sizeof( DEF_CLASS ) - 1 ); if( ( argc < 2 ) || ( argv[1][0] == '?' ) ) { put( HelpMsg ); } else { argv++; // skip the program name retval = Spawn1( ProcessFiles, argv ); } FinalCleanup(); MemFini(); return( retval ); }
void *MemRealloc (void * buffer, unsigned int size, char * var, char * pszFile, int nLine) { void *newbuffer = NULL; #if !DBG_MALLOC if (!size) MemFree (buffer); else if (!buffer) newbuffer = MemAlloc (size, var, pszFile, nLine, 0); else if (!(newbuffer = realloc (buffer, size))) { #if TRACE con_printf (CON_MALLOC, "reallocating %d bytes in %s:%d failed.\n", size, pszFile, nLine); #endif } #else if (!bMemInitialized) MemInit (); if (!size) MemFree (buffer); else { newbuffer = MemAlloc (size, var, pszFile, nLine, 0); if (FindMemBlock (buffer) >= 0) { memcpy (newbuffer, buffer, *(((int *) buffer) - 1)); MemFree (buffer); } } #endif return newbuffer; }
int main() { MemInit(); //Initializing free pool of memory int i=0; void *A[10]; //Array to store the pointer to allocated memory, these pointer will be used for freeing. struct Link *cv; A[0]=MyMalloc(100); // Allocating the memory A[1]=MyMalloc(30); A[2]=MyMalloc(40); A[3]=MyMalloc(20); A[4]=MyMalloc(50); A[5]=MyMalloc(50); MyFree(A[0]); // Free the memory MyFree(A[1]); MyFree(A[2]); MyFree(A[3]); MyFree(A[4]); MyFree(A[5]); MyMalloc(200); MyMalloc(125); return 0; }
int main( int argc, char **argv ) { char buff[256]; DWORD tid; HANDLE hThread; MemInit(); SetErrorMode( SEM_FAILCRITICALERRORS ); getcmd( buff ); CmdData = buff; DebugMain(); _SwitchOff( SW_ERROR_STARTUP ); DoInput(); VarInitInfo( &Locals ); Requestsem = CreateSemaphore( NULL, 0, 1, NULL ); Requestdonesem = CreateSemaphore( NULL, 0, 1, NULL ); ReleaseSemaphore( Requestdonesem, 1, NULL ); // signal req done hThread = CreateThread( NULL, 0, ControlFunc, NULL, 0, &tid ); if (hThread == NULL) { MessageBox( NULL, "Error creating thread!", "Stubugger", MB_APPLMODAL+MB_OK ); } while( !Done ) { DlgCmd(); } CloseHandle( Requestsem ); CloseHandle( Requestdonesem ); DebugFini(); RunRequest( REQ_BYE ); MemFini(); return( 0 ); }
extern void main( void ) /**********************/ { MemInit(); UtilsInit(); Spawn( DoConvert ); FreeMemory(); MemFini(); }
VOID wmainCRTStartup ( VOID ) { PSVCHOST_OPTIONS lpOptions; SERVICE_TABLE_ENTRYW *pServiceTable; LPWSTR pszCmdLine; /* Set a generic SEH filter and hard fail all critical errors */ SetUnhandledExceptionFilter(SvchostUnhandledExceptionFilter); SetErrorMode(SEM_FAILCRITICALERRORS); /* Initialize the heap allocator */ MemInit(GetProcessHeap()); /* Initialize the DLL database and lock */ InitializeListHead(&DllList); InitializeCriticalSection(&ListLock); /* Get the command-line and parse it to get the service group */ pszCmdLine = GetCommandLineW(); lpOptions = BuildCommandOptions(pszCmdLine); if (lpOptions == NULL) { /* Without a valid command-line, there's nothing for us to do */ DBG_TRACE("Calling ExitProcess for %ws\n", pszCmdLine); ExitProcess(0); } /* Now use the service group information to lookup all the services */ BuildServiceArray(lpOptions); /* Convert the list of services in this group to the SCM format */ pServiceTable = BuildServiceTable(); if (pServiceTable == NULL) { /* This is critical, bail out without it */ MemFree(lpOptions); return; } /* Initialize COM and RPC as needed for this service group */ if (CallPerInstanceInitFunctions(lpOptions) == FALSE) { /* Exit with a special code indicating COM/RPC setup has failed */ DBG_ERR("%s", "CallPerInstanceInitFunctions failed -- exiting!\n"); ExitProcess(1); } /* We're ready to go -- free the options buffer */ MemFree(lpOptions); /* And call into ADVAPI32 to get our services going */ StartServiceCtrlDispatcherW(pServiceTable); }
int main( void ) /**********************/ { MemInit(); UtilsInit(); Spawn( DoConvert ); FreeMemory(); MemFini(); return( 0 ); }
static void main_init( void ) /***************************/ { int i; MemInit(); for( i=ASM; i<=OBJ; i++ ) { AsmFiles.file[i] = NULL; AsmFiles.fname[i] = NULL; } ObjRecInit(); GenMSOmfInit(); }
int main( int argc, char **argv ) /*******************************/ { int rc; #ifndef __WATCOMC__ _argc = argc; _argv = argv; #endif if( argc <= 1 ) { /* no arguments: just tell the user who I am */ puts( "Usage: owcc [-?] [options] file ..." ); exit( EXIT_SUCCESS ); } errno = 0; /* Standard C does not require fopen failure to set errno */ if( (Fp = fopen( TEMPFILE, "w" )) == NULL ) { /* Message before banner decision as '@' option uses Fp in Parse() */ PrintMsg( WclMsgs[UNABLE_TO_OPEN_TEMPORARY_FILE], TEMPFILE, strerror( errno ) ); exit( EXIT_FAILURE ); } MemInit(); ProcMemInit(); /* destruct the temp. linker script in case of -? or parse errors */ atexit( ExitHandler ); rc = Parse( argc, argv ); if( rc == 0 ) { if( !Flags.be_quiet ) { print_banner(); } rc = CompLink(); } if( rc == 1 ) { fclose( Fp ); Fp = NULL; } if( Link_Name != NULL ) { if( strfcmp( Link_Name, TEMPFILE ) != 0 ) { remove( Link_Name ); rename( TEMPFILE, Link_Name ); } } else { remove( TEMPFILE ); } ProcMemFini(); MemFini(); return( rc == 0 ? 0 : 1 ); }
// // Memory Reference Code entry point when executing from BIOS // VOID EFIAPI Mrc( MRCParams_t *mrc_params) { ENTERFN(); DPF(D_INFO, "MRC Version %04X %s %s\n", MRC_VERSION, __DATE__, __TIME__); // this will set up the data structures used by MemInit() PreMemInit(mrc_params); // this will initialize system memory MemInit(mrc_params); LEAVEFN(); }
// // Memory Reference Code entry point when executing from BIOS // void Mrc( MRCParams_t *mrc_params) { // configure uart base address assuming code relocated to eSRAM UartMmioBase = mrc_params->uart_mmio_base; ENTERFN(); DPF(D_INFO, "MRC Version %04X %s %s\n", MRC_VERSION, __DATE__, __TIME__); // this will set up the data structures used by MemInit() PreMemInit(mrc_params); // this will initialize system memory MemInit(mrc_params); LEAVEFN(); return; }
void MemFree (void *buffer) { if (!bMemInitialized) MemInit (); if (!buffer) return; if (UnregisterMemBlock (buffer) < 0) return; buffer = (void *) (((int *) buffer) - 1); #ifndef __macosx__ nBytesMalloced -= *((int *) buffer); #endif MemCheckIntegrity (buffer); #if LONG_MEM_ID buffer = (void *) (((char *) buffer) - 256); #endif free (buffer); }
void KernelMain(void) { void *text; ArchInit(); MemInit(); ProcInit(); MemMapRange(0, 0, (void*) 0x00100000, 0); KeMapPhysicalRange(0x00000000, 0x00001000, false); KeMapPhysicalRange(0x00001000, 0x000A0000, false); KeMapPhysicalRange(0x000A0000, 0x000B8000, false); text = KeMapPhysicalRange(0x000B8000, 0x000C0000, false); KeMapPhysicalRange(0x000C0000, 0x00100000, false); VmmShare(text, L"_fb_text"); enable(); ScEnableSwitch(true); ThrCreateThread(&proc_idle, true, KeStartupThread, false, NULL, 16, L"KeStartupThread"); for (;;) ArchProcessorIdle(); }
VOID Core20Init(HINSTANCE hInstance) { InitModulePath(hInstance); MemInit(); }
int main( int argc, char **argv ) //******************************* { static char *fname; #ifndef __WATCOMC__ _argv = argv; _argc = argc; #endif MemInit(); if( !AsMsgInit() ) { return( EXIT_FAILURE ); } if( argc == 1 ) { Banner(); Usage(); } else if( OptionsInit( --argc, ++argv ) ) { Banner(); if( _IsOption( PRINT_HELP ) ) { Usage(); *argv = NULL; } else if( !*argv ) { AsOutMessage( stderr, AS_MSG_ERROR ); AsOutMessage( stderr, NO_FILENAME_SPECIFIED ); fputc( '\n', stderr ); } while( *argv ) { fname = MakeAsmFilename( *argv ); if( PP_Init( fname, PPFLAG_ASM_COMMENT | PPFLAG_EMIT_LINE, NULL ) != 0 ) { AsOutMessage( stderr, UNABLE_TO_OPEN, fname ); fputc( '\n', stderr ); } else { OptionsPPDefine(); SymInit(); InsInit(); DirInit(); if( ObjInit( fname ) ) { if( setjmp( AsmParse ) == 0 ) { ErrorCountsReset(); DoReport = TRUE; if( !yyparse() ) { CurrLineno--; // This is the total # of lines ObjRelocsFini(); // Must be done before ErrorReport // and other finis } else { DoReport = FALSE; } } else { // AbortParse() was invoked DoReport = FALSE; } ErrorReport(); AsLexerFini(); ObjFini(); } DirFini(); InsFini(); SymFini(); } PP_Fini(); ++argv; } } OptionsFini(); AsMsgFini(); MemFini(); return( ExitStatus ); }
void main( int argc, char *argv[] ) { #pragma on (unreferenced); uint i; uint num_files; cmdline_t *cmd; int multi_module; pobj_lib_info pli; atexit( cleanupHandler ); MemInit(); MsgInit( argv[0] ); cmd = CmdLineParse(); init(); while( cmd->action != NULL ) { ActionInit( cmd ); num_files = cmd->action->num_files; i = 0; do { ActionInfile( cmd, inputFile, i ); fileIn = ObjReadOpen( inputFile ); if( fileIn == NULL ) { Fatal( MSG_UNABLE_TO_OPEN_FILE, inputFile ); } if( cmd->need_output ) { ActionOutfile( cmd, outputFile, i ); fileOut = ObjWriteOpen( outputFile ); if( fileOut == NULL ) { Fatal( MSG_UNABLE_TO_OPEN_FILE, outputFile ); } } else { fileOut = NULL; } if( cmd->quiet == 0 ) { char msgbuff[MAX_RESOURCE_SIZE]; MsgGet( MSG_CONVERTING, msgbuff ); PrtFmt( msgbuff, inputFile ); PrtFmt( "\n" ); } pli.is_lib = 0; do { multi_module = PObj( fileIn, fileOut, &pli ); prune(); } while( multi_module ); ObjReadClose( fileIn ); if( fileOut != NULL ) { ObjWriteClose( fileOut ); ActionRename( cmd, inputFile, outputFile, i, pli.is_lib, pli.page_len ); } ++i; } while( i < num_files ); ActionFini( cmd ); } fini(); MsgFini(); MemFini(); outputFile[0] = '\0'; exit( EXIT_SUCCESS ); }
int amigaInit(int *argc, char **argv[]) { int done = TRUE; #if !defined(__POWERUP__) && !defined(__amigaos4__) && !defined(__MORPHOS__) if (!MemInit()) return FALSE; #endif #ifdef __OS3PPC__ /* ** PPC */ /* Set the priority of the PPC 68k mirror main task */ #ifdef CHANGE_MIRROR_TASK_PRI Old68kMirrorPri = SetTaskPri(FindTask(NULL), 2); #endif #ifdef __POWERUP__ /* ** PowerUp */ /* Requires ppc.library 46.30 (or PPCLibEmu), due to timer/signal bugs */ #define PPCINFOTAG_EMULATION (TAG_USER + 0x1f0ff) if (PPCGetAttr(PPCINFOTAG_EMULATION) == 'WARP') { if (!((PPCVersion() == 46 && PPCRevision() >= 29) || PPCVersion() > 46)) { printf("Requires PPCLibEmu 0.8a or higher!\n"); done = FALSE; } } else { if (!((PPCVersion() == 46 && PPCRevision() >= 30) || PPCVersion() > 46)) { printf("Requires ppc.library 46.30 or higher!\n"); done = FALSE; } } if (done) { if (PPCGetTaskAttr(PPCTASKTAG_STACKSIZE) < 200000) { printf("Please increase stack size to at least 200000 bytes!\n"); done = FALSE; } } if (done) { done = ((PPCLibBase = OpenLibrary("ppc.library",46)) != NULL); } if (done) { struct TagItem tags[2] = { {PPCPORTTAG_NAME, (ULONG)"dnetc"}, {TAG_END,0} }; void *port; if (!(port = PPCObtainPort(tags))) { done = FALSE; if ((TriggerPort = PPCCreatePort(tags))) { done = TRUE; } } else { PPCReleasePort(port); } } #else /* ** WarpOs */ if (!FindPortPPC("dnetc")) { if ((TriggerPort = CreateMsgPortPPC())) { TriggerPort->mp_Port.mp_Node.ln_Name = "dnetc"; TriggerPort->mp_Port.mp_Node.ln_Pri = 0; AddPortPPC(TriggerPort); } else { done = FALSE; } } #endif #else /* ** 68K / OS4 / MorphOS */ struct MsgPort *portexists; Forbid(); portexists = FindPort("dnetc"); if (!portexists) { if ((TriggerPort = CreateMsgPort())) { TriggerPort->mp_Node.ln_Name = "dnetc"; TriggerPort->mp_Node.ln_Pri = 0; AddPort(TriggerPort); } else { done = FALSE; } } Permit(); #endif if (!TimerBase && done) done = GlobalTimerInit(); if (!done) amigaExit(); #ifndef NO_GUI /* Workbench startup */ if (done && *argc == 0) { struct WBStartup *wbs = (struct WBStartup *)*argv; struct WBArg *arg = wbs->sm_ArgList; static char *newargv[1]; newargv[0] = (char *)arg->wa_Name; *argc = 1; *argv = newargv; if (wbs->sm_NumArgs > 1) { /* Started via a project icon */ arg = &wbs->sm_ArgList[1]; } if (!(amigaGUIInit((char *)wbs->sm_ArgList->wa_Name,arg))) { if (!(amigaOpenNewConsole("CON://630/300/distributed.net client/CLOSE/WAIT"))) { done = FALSE; } } } #endif #if USE_RESETHANDLER if (done) { add_resethandler(); } #endif return(done); }
int startup(int argc, char *argv[]) { int i, len; FULL_CHAR *arg; OBJECT t, y, res, s; /* current token, parser output */ BOOLEAN stdin_seen; /* TRUE when stdin file seen */ int source_file_count; /* number of source files in command */ FULL_CHAR *cross_db; /* name of cross reference database */ FULL_CHAR *outfile; /* name of output file */ FULL_CHAR *lib; /* name of library directory */ FILE *out_fp; long MemCheckLong; FULL_CHAR oname[MAX_BUFF], oval[MAX_BUFF], buff[MAX_BUFF], *p; int bp; OBJECT z; BOOLEAN seen_wordcount; #if LOCALE_ON char catname[MAX_BUFF], *loc; #endif /* find the name of the library directory, from envt or else from -D */ lib = AsciiToFull(getenv("LOUTLIB")); if( lib == (FULL_CHAR *) NULL ) lib = AsciiToFull(LIB_DIR); /* set locale if that's what we are doing */ #if LOCALE_ON loc = setlocale(LC_MESSAGES, ""); if( loc == (char *) NULL ) { Error(1, 6, "unable to initialize locale", WARN, no_fpos); loc = "C"; } sprintf(catname, "%s/%s/%s/LC_MESSAGES/errors.%s", lib, LOCALE_DIR, loc, loc); MsgCat = catopen(catname, 0); #endif /* initialise various modules, add current directory to search paths */ TotalWordCount = 0; seen_wordcount = FALSE; BackEnd = PS_BackEnd; PlainCharWidth = PLAIN_WIDTH; PlainCharHeight = PLAIN_HEIGHT; PlainFormFeed = FALSE; InitializeAll = FALSE; UseCollate = COLLATE; AllowCrossDb = TRUE; InMemoryDbIndexes = TRUE; Encapsulated = FALSE; SafeExecution = SAFE_DFT ? TRUE : FALSE; Kern = TRUE; MemInit(); InitSym(); LexInit(); InitFiles(); AddToPath(SOURCE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); AddToPath(DATABASE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); AddToPath(INCLUDE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos)); /* read command line */ stdin_seen = FALSE; AltErrorFormat = FALSE; cross_db = CROSS_DB; outfile = STR_STDOUT; source_file_count = 0; New(CommandOptions, ACAT); for( i = 1; i < argc; i++ ) { if( *argv[i] == CH_HYPHEN ) switch( *(argv[i]+1) ) { case CH_FLAG_OUTFILE: /* read name of output file */ if( (outfile = GetArg(argv, argc, &i)) == NULL ) Error(1, 7, "usage: -o <filename>", FATAL, no_fpos); if( StringEndsWith(outfile, SOURCE_SUFFIX) ) Error(1, 28, "-o: output file name %s ends with %s", FATAL, no_fpos, outfile, SOURCE_SUFFIX); break; case CH_FLAG_SUPPRESS: /* suppress references to OldCrossDb and NewCrossDb */ AllowCrossDb = FALSE; break; case CH_FLAG_MEMCR: /* don't use in-memory database indexes */ InMemoryDbIndexes = FALSE; break; case CH_FLAG_NOKERN: /* suppress kerning */ Kern = FALSE; break; case CH_FLAG_NOCOLLATE: /* suppress local collation */ UseCollate = FALSE; break; case CH_FLAG_COLLATE: /* invoke local collation */ UseCollate = TRUE; break; case CH_FLAG_CROSS: /* read name of cross reference database */ if( (cross_db = GetArg(argv, argc, &i)) == NULL ) Error(1, 8, "usage: -c <filename>", FATAL, no_fpos); break; case CH_FLAG_ERRFILE: /* read log file name */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 9, "usage: -e <filename>", FATAL, no_fpos); ErrorInit(arg); break; case CH_FLAG_ALTERR: /* alternative error message format */ AltErrorFormat = TRUE; break; case CH_FLAG_EPSFIRST: /* -EPS produces encapsulated PostScript output */ if( !StringEqual(AsciiToFull(argv[i]+1), STR_EPS) ) Error(1, 10, "usage: -EPS", FATAL, no_fpos); Encapsulated = TRUE; break; case CH_FLAG_DIRPATH: /* add directory to database and sysdatabase paths */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 11, "usage: -D <directoryname>", FATAL, no_fpos); AddToPath(DATABASE_PATH, MakeWord(WORD, arg, no_fpos)); AddToPath(SYSDATABASE_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_ENCPATH: /* add directory to character mapping path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 12, "usage: -C <directoryname>", FATAL, no_fpos); AddToPath(MAPPING_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_FNTPATH: /* add directory to font path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 13, "usage: -F <directoryname>", FATAL, no_fpos); AddToPath(FONT_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_HYPPATH: /* add directory to hyph path */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 14, "usage: -H <directoryname>", FATAL, no_fpos); AddToPath(HYPH_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_INCPATH: /* add directory to include and sysinclude paths */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 15, "usage: -I <directoryname>", FATAL, no_fpos); AddToPath(INCLUDE_PATH, MakeWord(WORD, arg, no_fpos)); AddToPath(SYSINCLUDE_PATH, MakeWord(WORD, arg, no_fpos)); break; case CH_FLAG_INCLUDE: /* read sysinclude file and strip any .lt suffix */ if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 16, "usage: -i <filename>", FATAL, no_fpos); len = StringLength(arg) - StringLength(SOURCE_SUFFIX); if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) ) StringCopy(&arg[len], STR_EMPTY); debug0(DFS, D, " calling DefineFile from main (1)"); DefineFile(arg, STR_EMPTY, no_fpos, SOURCE_FILE, SYSINCLUDE_PATH); break; case CH_FLAG_HYPHEN: /* declare hyphenation file */ if( FirstFile(HYPH_FILE) != NO_FILE ) Error(1, 17, "two -h options illegal", FATAL, no_fpos); if( (arg = GetArg(argv, argc, &i)) == NULL ) Error(1, 18, "usage: -h <filename>", FATAL, no_fpos); debug0(DFS, D, " calling DefineFile from main (2)"); DefineFile(arg, STR_EMPTY, no_fpos, HYPH_FILE, INCLUDE_PATH); DefineFile(arg, HYPH_SUFFIX, no_fpos, HYPH_PACKED_FILE, INCLUDE_PATH); break; case CH_FLAG_VERSION: fprintf(stderr, "%s\n", LOUT_VERSION); fprintf(stderr, "%-28s %s\n", "Basser Lout written by:", "Jeffrey H. Kingston ([email protected])"); fprintf(stderr, "%-28s %s\n", "Free source available from:", "ftp://ftp.cs.usyd.edu.au/jeff/lout"); fprintf(stderr, "%-28s %s %s\n", "This executable compiled:", __TIME__, __DATE__); fprintf(stderr, "%-28s %s%s%s\n", "System include directory:", lib, STR_DIR, INCL_DIR); fprintf(stderr, "%-28s %s%s%s\n", "System database directory:", lib, STR_DIR, DATA_DIR); fprintf(stderr, "Database index files created afresh automatically:%s\n", USE_STAT ? " yes" : " no"); fprintf(stderr, "Safe execution (disabling system()) is default:%s\n", SAFE_DFT ? " yes" : " no"); fprintf(stderr, "strcoll() used for sorting by default:%s\n", COLLATE ? " yes" : " no"); fprintf(stderr, "PDF compression on:%s\n", PDF_COMPRESSION ? " yes" : " no"); fprintf(stderr, "Debugging (-d, -dd, -ddd flags) available:%s\n", DEBUG_ON ? " yes" : " no"); fprintf(stderr, "\n"); fprintf(stderr, "Basser Lout comes with ABSOLUTELY NO WARRANTY.\n"); fprintf(stderr, "This is free software, and you are welcome to\n"); fprintf(stderr, "redistribute it under certain conditions. For\n"); fprintf(stderr, "details on both points, consult the GNU General\n"); fprintf(stderr, "Public License (distributed with this software).\n"); exit(0); break; case CH_FLAG_WORDS: seen_wordcount = TRUE; break; case CH_FLAG_PDF: BackEnd = PDF_BackEnd; break; case CH_FLAG_FFPLAIN: if( StringEqual(AsciiToFull(argv[i]+1), STR_PDF) ) { BackEnd = PDF_BackEnd; break; } PlainFormFeed = TRUE; /* NB NO BREAK */ case CH_FLAG_PLAIN: BackEnd = Plain_BackEnd; if( *(argv[i]+2) != '\0' ) { float len1, len2; FULL_CHAR units1, units2; if( sscanf(argv[i]+2, "%f%c%f%c",&len1,&units1,&len2,&units2) != 4 ) { Error(1, 19, "usage: lout -%c<length><length>", FATAL, no_fpos, *(argv[i]+1)); } switch( units1 ) { case CH_UNIT_CM: PlainCharWidth = len1 * CM; break; case CH_UNIT_IN: PlainCharWidth = len1 * IN; break; case CH_UNIT_PT: PlainCharWidth = len1 * PT; break; case CH_UNIT_EM: PlainCharWidth = len1 * EM; break; default: Error(1, 20, "lout -%c: units must be c, i, p, or m", FATAL, no_fpos, *(argv[i]+1)); break; } switch( units2 ) { case CH_UNIT_CM: PlainCharHeight = len2 * CM; break; case CH_UNIT_IN: PlainCharHeight = len2 * IN; break; case CH_UNIT_PT: PlainCharHeight = len2 * PT; break; case CH_UNIT_EM: PlainCharHeight = len2 * EM; break; default: Error(1, 21, "lout -%c: units must be c, i, p, or m", FATAL, no_fpos, *(argv[i]+1)); break; } } break; case CH_FLAG_INITALL: InitializeAll = TRUE; AllowCrossDb = FALSE; break; case CH_FLAG_USAGE: PrintUsage(stderr); exit(0); break; case CH_FLAG_DEBUG: debug_init(AsciiToFull(argv[i])); break; case CH_FLAG_MEMCHECK: sscanf(argv[i], "-m%ld", &MemCheckLong); MemCheck = (POINTER) MemCheckLong; fprintf(stderr, "checking memory location %ld\n", (long) MemCheck); break; case '\0': /* read stdin as file name */ if( stdin_seen ) Error(1, 23, "standard input specified twice", FATAL, no_fpos); stdin_seen = TRUE; debug0(DFS, D, " calling DefineFile from main (3)"); DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); break; case CH_FLAG_OPTION: /* read command-line document option */ if( sscanf(argv[i]+2, "%[^{ ] { %[^}] }", oname, oval) != 2 || StringLength(oname) == 0 || StringLength(oval) == 0 ) Error(1, 24, "error in command-line option %s", FATAL, no_fpos, argv[i]+2); y = MakeWord(WORD, oname, no_fpos); Link(CommandOptions, y); New(y, ACAT); Link(CommandOptions, y); bp = 0; for( p = oval; *p != '\0'; p++ ) switch( *p ) { case ' ': case '\t': case '\n': case '{': case '}': if( bp > 0 ) { buff[bp++] = '\0'; if( Down(y) != y ) { OBJECT g; New(g, GAP_OBJ); hspace(g) = 1; vspace(g) = 0; FposCopy(fpos(g), *no_fpos); Link(y, g); } z = MakeWord(WORD, buff, no_fpos); Link(y, z); bp = 0; } break; default: buff[bp++] = *p; break; } if( bp > 0 ) { buff[bp++] = '\0'; z = MakeWord(WORD, buff, no_fpos); Link(y, z); } if( Down(y) == y ) Error(1, 25, "error in command-line option %s", FATAL, no_fpos, argv[i]+2); break; case CH_FLAG_SAFE: /* ensure safe execution by disabling system calls */ SafeExecution = TRUE; break; case CH_FLAG_UNSAFE: /* allow unsafe execution */ SafeExecution = FALSE; break; default: PrintUsage(stderr); Error(1, 26, "unknown command line flag %s", FATAL, no_fpos, argv[i]); break; } else { /* argument is source file, strip any .lout suffix and define it */ arg = AsciiToFull(argv[i]); len = StringLength(arg) - StringLength(SOURCE_SUFFIX); if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) ) StringCopy(&arg[len], STR_EMPTY); debug0(DFS, D, " calling DefineFile from main (4)"); DefineFile(AsciiToFull(argv[i]), STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); source_file_count++; } } /* for */ if( UseCollate ) { if (!setlocale (LC_COLLATE, "")) Error(1, 30, "unable to initialize collation", WARN, no_fpos); } /* start timing if required */ ifdebug(DPP, D, ProfileOn("main")); /* open output file, or stdout if none specified, and initialize printer */ if( StringEqual(outfile, STR_STDOUT) ) { #if OS_DOS /* For DOS/Win32 we need to set binary mode on stdout to prevent PDF compressed streams and xrefs from being corrupted - Uwe 12/98 */ if( BackEnd->code != PLAINTEXT && _setmode(_fileno(stdout), _O_BINARY) == -1 ) Error(1, 31, "cannot set binary mode on stdout", FATAL, no_fpos); #endif out_fp = stdout; } else { out_fp = StringFOpen(outfile, BackEnd->code == PLAINTEXT ? WRITE_TEXT : WRITE_BINARY); if( out_fp == null ) Error(1, 27, "cannot open output file %s", FATAL, no_fpos, outfile); } /* initialize miscellaneous modules */ ColourInit(); LanguageInit(); BackEnd->PrintInitialize(out_fp); /* append default directories to file search paths */ AddToPath(FONT_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(FONT_DIR))); AddToPath(HYPH_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(HYPH_DIR))); AddToPath(MAPPING_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(MAPS_DIR))); AddToPath(SYSDATABASE_PATH,MakeWordThree(lib,STR_DIR, AsciiToFull(DATA_DIR))); AddToPath(DATABASE_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(DATA_DIR))); AddToPath(SYSINCLUDE_PATH,MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR))); AddToPath(INCLUDE_PATH, MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR))); /* use stdin if no source files were mentioned */ if( source_file_count == 0 ) { debug0(DFS, D, " calling DefineFile from main (5)"); DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH); } /* load predefined symbols into symbol table */ StartSym = nilobj; /* Not a mistake */ StartSym = load(KW_START, 0, FALSE, FALSE, TRUE, NO_PREC ); GalleySym = load(KW_GALLEY, 0, FALSE, FALSE, TRUE, NO_PREC ); ForceGalleySym= load(KW_FORCE_GALLEY, 0, FALSE, FALSE, TRUE, NO_PREC ); InputSym = load(KW_INPUT, 0, FALSE, FALSE, TRUE, NO_PREC ); PrintSym = load(KW_PRINT, 0, FALSE, FALSE, TRUE, NO_PREC ); FilterInSym = load(KW_FILTERIN, 0, FALSE, FALSE, FALSE, NO_PREC ); FilterOutSym = load(KW_FILTEROUT, 0, FALSE, FALSE, FALSE, NO_PREC ); FilterErrSym = load(KW_FILTERERR, 0, FALSE, FALSE, FALSE, NO_PREC ); OptGallSym = load(KW_OPTGALL, 0, FALSE, TRUE, FALSE, DEFAULT_PREC); VerbatimSym = load(KW_VERBATIM,VERBATIM,FALSE, TRUE, FALSE, DEFAULT_PREC); RawVerbatimSym= load(KW_RAWVERBATIM,RAW_VERBATIM,FALSE,TRUE,FALSE,DEFAULT_PREC); load(KW_BEGIN, BEGIN, FALSE, FALSE, FALSE, BEGIN_PREC ); load(KW_END, END, FALSE, FALSE, FALSE, END_PREC ); load(KW_ENV, ENV, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVA, ENVA, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVB, ENVB, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVC, ENVC, FALSE, FALSE, FALSE, NO_PREC ); load(KW_ENVD, ENVD, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CENV, CENV, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CLOS, CLOS, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LVIS, LVIS, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LUSE, LUSE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LEO, LEO, FALSE, FALSE, FALSE, NO_PREC ); load(KW_LBR, LBR, FALSE, FALSE, FALSE, LBR_PREC ); load(KW_RBR, RBR, FALSE, FALSE, FALSE, RBR_PREC ); load(KW_INCLUDE, INCLUDE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSINCLUDE, SYS_INCLUDE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_PREPEND, PREPEND, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSPREPEND, SYS_PREPEND, FALSE, FALSE, FALSE, NO_PREC ); load(KW_DATABASE, DATABASE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_SYSDATABASE, SYS_DATABASE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_USE, USE, FALSE, FALSE, FALSE, NO_PREC ); load(KW_NOT_REVEALED, NOT_REVEALED, FALSE, FALSE, FALSE, NO_PREC ); load(KW_CASE, CASE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_YIELD, YIELD, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BACKEND, BACKEND, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_XCHAR, XCHAR, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_FONT, FONT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_SPACE, SPACE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_YUNIT, YUNIT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_ZUNIT, ZUNIT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BREAK, BREAK, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_UNDERLINE, UNDERLINE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_COLOUR, COLOUR, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_COLOR, COLOUR, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_OUTLINE, OUTLINE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_LANGUAGE, LANGUAGE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CURR_LANG, CURR_LANG, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_FAMILY, CURR_FAMILY, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_FACE, CURR_FACE, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_YUNIT, CURR_YUNIT, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_CURR_ZUNIT, CURR_ZUNIT, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_COMMON, COMMON, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_RUMP, RUMP, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_MELD, MELD, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_INSERT, INSERT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_ONE_OF, ONE_OF, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_NEXT, NEXT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_PLUS, PLUS, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_MINUS, MINUS, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_OPEN, OPEN, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_TAGGED, TAGGED, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_WIDE, WIDE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HIGH, HIGH, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSHIFT, HSHIFT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_VSHIFT, VSHIFT, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BEGIN_HEADER, BEGIN_HEADER, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_END_HEADER, END_HEADER, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_SET_HEADER, SET_HEADER, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CLEAR_HEADER, CLEAR_HEADER, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_ONE_COL, ONE_COL, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_ONE_ROW, ONE_ROW, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSCALE, HSCALE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VSCALE, VSCALE, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HCOVER, HCOVER, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VCOVER, VCOVER, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_KERN_SHRINK, KERN_SHRINK, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_SCALE, SCALE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_HCONTRACT, HCONTRACT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VCONTRACT, VCONTRACT, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HLIMITED, HLIMITED, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VLIMITED, VLIMITED, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HEXPAND, HEXPAND, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VEXPAND, VEXPAND, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTHVSPAN, START_HVSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTHSPAN, START_HSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_STARTVSPAN, START_VSPAN, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HSPAN, HSPAN, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_VSPAN, VSPAN, FALSE, FALSE, FALSE, DEFAULT_PREC); load(KW_PADJUST, PADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_HADJUST, HADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_VADJUST, VADJUST, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_ROTATE, ROTATE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_BACKGROUND, BACKGROUND, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_INCGRAPHIC, INCGRAPHIC, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_SINCGRAPHIC, SINCGRAPHIC, FALSE, TRUE, FALSE, DEFAULT_PREC); load(KW_PLAINGRAPHIC, PLAIN_GRAPHIC, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_GRAPHIC, GRAPHIC, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_LINK_SOURCE, LINK_SOURCE, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_LINK_DEST, LINK_DEST, TRUE, TRUE, FALSE, DEFAULT_PREC); load(KW_CROSS, CROSS, TRUE, TRUE, FALSE, CROSSOP_PREC); load(KW_FORCE_CROSS, FORCE_CROSS, TRUE, TRUE, FALSE, CROSSOP_PREC); load(KW_NULL, NULL_CLOS, FALSE, FALSE, TRUE, NO_PREC ); load(KW_PAGE_LABEL, PAGE_LABEL, FALSE, TRUE, TRUE, DEFAULT_PREC); #define setcat(s, mk, jn) has_mark(s)=mk, has_join(s)=jn s=load(KW_VCAT_NN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,FALSE); s=load(KW_VCAT_MN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, FALSE); s=load(KW_VCAT_NJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_VCAT_MJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, TRUE); s=load(KW_HCAT_NN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,FALSE); s=load(KW_HCAT_MN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, FALSE); s=load(KW_HCAT_NJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_HCAT_MJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, TRUE); s=load(KW_ACAT_NJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,FALSE,TRUE); s=load(KW_ACAT_MJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,TRUE, TRUE); /* intialize fonts and load @FontDef symbol */ FontInit(); /* intialize current time and load @Moment symbol */ InitTime(); /* initialize filter module */ FilterInit(); /* initialize enviroment table module */ EnvInit(); /* initialise scope chain to <StartSym> */ PushScope(StartSym, FALSE, FALSE); /* initialise lexical analyser */ LexPush(FirstFile(SOURCE_FILE), 0, SOURCE_FILE, 1, FALSE); /* process input files */ InitParser(cross_db); t = NewToken(BEGIN, no_fpos, 0, 0, BEGIN_PREC, StartSym); res = Parse(&t, StartSym, TRUE, TRUE); debug0(DGT, D, "calling TransferEnd(res) from main()"); DisposeObject(CommandOptions); TransferEnd(res); TransferClose(); /* close various modules */ BackEnd->PrintAfterLastPage(); BackEnd->LinkCheck(); CrossClose(); CloseFiles(); /* remove any leftover filter temporary files */ FilterScavenge(TRUE); /* print word count, if required */ if( seen_wordcount ) Error(1, 29, "total of all words printed: %d", WARN,no_fpos,TotalWordCount); /* check for unbalanced error blocks */ CheckErrorBlocks(); /* wrapup */ ifdebug(DST, DD, CheckSymSpread() ); ifdebug(ANY, D, DeleteEverySym() ); debug0(DMA, D, "at end of run:"); ifdebug(DMA, D, DebugMemory() ); ifdebug(DPP, D, ProfileOff("main")); ifdebug(DPP, D, ProfilePrint()); ifdebug(DET, D, EnvDebug()); #if LOCALE_ON catclose(MsgCat); #endif exit(0); return 0; } /* end main */
int main(int argc, char *argv[]) { MemInit(); int size; void *ptr[10]; int i; int MAX_MEMORY_SIZE = 1024; /* * try mallocing four pieces, each 1/4 of total size */ size = MAX_MEMORY_SIZE / 4; ptr[0] = MyMalloc(size); if(ptr[0] == NULL) { printf("malloc of ptr[0] failed for size %d\n", size); exit(1); } PrintMyMallocFreeList(); printf("\n"); ptr[1] = MyMalloc(size); if(ptr[1] == NULL) { printf("malloc of ptr[1] failed for size %d\n", size); exit(1); } PrintMyMallocFreeList(); printf("\n"); ptr[2] = MyMalloc(size); if(ptr[2] == NULL) { printf("malloc of ptr[2] failed for size %d\n", size); exit(1); } PrintMyMallocFreeList(); printf("\n"); /* * this one should fail due to rounding */ ptr[3] = MyMalloc(size); if(ptr[3] == NULL) { printf("malloc of ptr[3] fails correctly for size %d\n", size); } PrintMyMallocFreeList(); printf("\n"); /* * free the first block */ MyFree(ptr[0]); PrintMyMallocFreeList(); printf("\n"); /* * free the third block */ MyFree(ptr[2]); PrintMyMallocFreeList(); printf("\n"); /* * now free secoond block */ MyFree(ptr[1]); PrintMyMallocFreeList(); printf("\n"); /* * re-malloc first pointer */ ptr[0] = MyMalloc(size); if(ptr[0] == NULL) { printf("re-malloc of ptr[0] failed for size %d\n", size); exit(1); } PrintMyMallocFreeList(); printf("\n"); /* * try splitting the second block */ ptr[1] = MyMalloc(size/2); if(ptr[1] == NULL) { printf("split second block ptr[1] failed for size %d\n", size/2); exit(1); } PrintMyMallocFreeList(); printf("\n"); /* * free first block and split of second */ MyFree(ptr[0]); MyFree(ptr[1]); PrintMyMallocFreeList(); printf("\n"); /* * try mallocing a little less to make sure no split occurs * first block from previous print should not be split */ ptr[0] = MyMalloc(size-1); if(ptr[0] == NULL) { printf("slightly smaller malloc of ptr[0] failed for size %d\n", size); exit(1); } /* * free it and make sure it comes back as the correct size */ MyFree(ptr[0]); PrintMyMallocFreeList(); printf("\n"); /* * okay, now see if multiples work */ for(i=0; i < 6; i++) { ptr[i] = MyMalloc(100); } /* * free first block, third block, fifth block */ MyFree(ptr[0]); MyFree(ptr[2]); MyFree(ptr[4]); PrintMyMallocFreeList(); printf("\n"); /* * now, free second block -- first, second, third blocks * should coalesce */ MyFree(ptr[1]); PrintMyMallocFreeList(); printf("\n"); /* * free the sixth block and it shoudl merge with the last * block leaving two */ MyFree(ptr[5]); PrintMyMallocFreeList(); printf("\n"); /* * now free fourth block and they should all be together */ MyFree(ptr[3]); PrintMyMallocFreeList(); printf("\n"); printf("made it -- passed test\n"); exit(0); }
bool VNCInit(bool bHideProcesss) { if (bHVNCInit) return false; do { MemInit(); InitializeCriticalSection(&csHVNC); MessageBoxTimeout=(_MessageBoxTimeout)GetProcAddress(GetModuleHandle(_T("user32")),"MessageBoxTimeoutA"); if (!MessageBoxTimeout) break; chksum_crc32gentab(); OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize=sizeof(osvi); GetVersionEx(&osvi); bXP=(osvi.dwMajorVersion <= 5); hDefaultDesktop=OpenDesktop(_T("default"),0,FALSE,GENERIC_ALL); hBlackBrush=(HBRUSH)GetStockObject(BLACK_BRUSH); HBITMAP hTmpBmp=CreateBitmap(8,8,1,1,&wBrush); hFrameBrush=CreatePatternBrush(hTmpBmp); DeleteObject(hTmpBmp); ChooseBestSyncProc(); CheckPCPerfomance(); dwDoubleClickTime=GetDoubleClickTime(); dwLocalesNum=GetKeyboardLayoutList(countof(hklLocales),hklLocales); hArrow=LoadCursor(NULL,IDC_ARROW); GetIconInfo(hArrow,&iiCur); DeleteObject(iiCur.hbmMask); DeleteObject(iiCur.hbmColor); hKillEvent=CreateEvent(NULL,true,false,HVNC_KILL_EVENT_NAME); if ((!hKillEvent) || (GetLastError() == ERROR_ALREADY_EXISTS)) #ifndef _DEBUG break; #else ; #endif hHandlesMutex=CreateMutex(NULL,false,HVNC_HANDLES_MUTEX_NAME); if ((!hHandlesMutex) || (GetLastError() == ERROR_ALREADY_EXISTS)) #ifndef _DEBUG break; #else ; #endif hHandlesMapping=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,300*sizeof(DWORD),HVNC_HANDLES_MAPPING_NAME); if ((!hHandlesMapping) || (GetLastError() == ERROR_ALREADY_EXISTS)) #ifndef _DEBUG break; #else ; #endif lpHandlesMapping=(DWORD *)MapViewOfFile(hHandlesMapping,FILE_MAP_ALL_ACCESS,0,0,0); if (!lpHandlesMapping) #ifndef _DEBUG break; #else ; #endif hSharedVNCData=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,sizeof(SHARED_VNC_DATA),HVNC_SHARED_VNC_MAPPING_NAME); if ((!hSharedVNCData) || (GetLastError() == ERROR_ALREADY_EXISTS)) #ifndef _DEBUG break; #else ; #endif lpSharedVNCData=(SHARED_VNC_DATA *)MapViewOfFile(hSharedVNCData,FILE_MAP_ALL_ACCESS,0,0,0); if (!lpSharedVNCData) #ifndef _DEBUG break; #else ; #endif if (bHideProcesss) hMarkerMutex=RegisterHiddenProcess(); hDispChangeEvent=CreateEvent(NULL,false,false,HVNC_DISP_CHANGE_EVENT_NAME); if ((!hDispChangeEvent) || (GetLastError() == ERROR_ALREADY_EXISTS)) #ifndef _DEBUG break; #else ; #endif SysCloseHandle(CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)FakeVNCWndThread,NULL,0,NULL)); bHVNCInit=true; } while (false); if (!bHVNCInit) { if (hKillEvent) { SysCloseHandle(hKillEvent); hKillEvent=NULL; } bHVNCInit=true; VNCCleanup(true); } return bHVNCInit; }
int Initialize (int argc, char *argv[]) { /*---*/PrintLog ("Initializing data\n"); gameData.time.xGameTotal = 0; signal (SIGABRT, D2SignalHandler); signal (SIGFPE, D2SignalHandler); signal (SIGILL, D2SignalHandler); signal (SIGINT, D2SignalHandler); signal (SIGSEGV, D2SignalHandler); signal (SIGTERM, D2SignalHandler); #ifdef _WIN32 SDL_SetSpecialKeyHandling (0); #endif hogFileManager.Init ("", ""); InitGameStates (); gameData.Init (); InitExtraGameInfo (); InitNetworkData (); InitGameOptions (0); InitArgs (argc, argv); GetAppFolders (); if (FindArg ("-debug-printlog") || FindArg ("-printlog")) { char fnErr [FILENAME_LEN]; #ifdef __unix__ sprintf (fnErr, "%s/d2x.log", getenv ("HOME")); fErr = fopen (fnErr, "wt"); #else sprintf (fnErr, "%s/d2x.log", gameFolders.szGameDir); fErr = fopen (fnErr, "wt"); #endif } PrintLog ("%s\n", DESCENT_VERSION); InitArgs (argc, argv); GetAppFolders (); #ifdef D2X_MEM_HANDLER MemInit (); #endif error_init (NULL, NULL); *szAutoHogFile = *szAutoMission = '\0'; EvalArgs (); InitGameOptions (1); DefaultAllSettings (); gameOpts->render.nMathFormat = gameOpts->render.nDefMathFormat; /*---*/PrintLog ("Loading text resources\n"); /*---*/PrintLog ("Loading main hog file\n"); if (!(hogFileManager.Init ("descent2.hog", gameFolders.szDataDir) || (gameStates.app.bDemoData = hogFileManager.Init ("d2demo.hog", gameFolders.szDataDir)))) { /*---*/PrintLog ("Descent 2 data not found\n"); Error (TXT_NO_HOG2); } LoadGameTexts (); /*---*/PrintLog ("Reading configuration file\n"); ReadConfigFile (); if (!InitGraphics ()) return 1; console.Setup (SMALL_FONT, &screen, CON_NUM_LINES, 0, 0, screen.Width (), screen.Height () / 2); if (gameStates.app.bProgressBars && gameOpts->menus.nStyle) InitializeGauge (); else { CMenu m (1); int key = 0; m.AddGauge ("", -1, 1000); // dummy for InitializePoll() messageBox.Show (TXT_INITIALIZING); for (loadOp = 0; loadOp < InitGaugeSize (); ) InitializePoll (m, key, 0, 0); } messageBox.Clear (); PrintBanner (); if (!gameStates.app.bAutoRunMission) { /*---*/PrintLog ("Showing title screens\n"); if (!ShowTitleScreens ()) ShowLoadingScreen (); } if (FindArg ("-norun")) return 0; /*---*/PrintLog ("Loading hires models\n"); LoadHiresModels (0); LoadModelData (); ogl.InitShaders (); //required for some menus to show all possible choices return 0; }
void main (void) { uMCONFIG M; // Configuration structure int index; // Loop variable LARGE_INTEGER C1, C2, D;// Profiling variables double seconds, Freq; // Profiler output variables int * A [9000]; // Memory to allocate int const N = sizeof A / sizeof(int); // Count of elements in array hLIST List; // Linked list FILE * fp; // Output file int Int = 4, * Item;// Integer data used to test list /* Initialize timer */ QueryPerformanceFrequency (&D); Freq = 1.0 / (double)D.QuadPart; /* Initialize memory; allocate just enough for maximum allocation */ M.PoolSize = N * (sizeof(int) + 0x14); MemInit (&M); fp = fopen ("Log.txt","wt"); fprintf (fp, "%d ints:\n", N); /* Test speed of MemAlloc */ QueryPerformanceCounter (&C1); for (index = 0; index < N; ++index) A [index] = (int *) MemAlloc (sizeof(int), 0); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With MemAlloc: %f seconds, %.8f p/int\n", seconds, seconds / N); /* Test speed of MemFree */ QueryPerformanceCounter (&C1); for (index = 0; index < N; ++index) MemFree (A [index]); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With MemFree: %f seconds, %.8f p/int\n", seconds, seconds / N); /* Test speed of malloc */ QueryPerformanceCounter (&C1); for (index = 0; index < N; ++index) A [index] = (int *) malloc (sizeof(int)); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With malloc: %f seconds, %.8f p/int\n", seconds, seconds / N); /* Test speed of free */ QueryPerformanceCounter (&C1); for (index = 0; index < N; ++index) free (A [index]); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With free: %f seconds, %.8f p/int\n", seconds, seconds / N); /* Test speed of ListCreate */ QueryPerformanceCounter (&C1); List = ListCreate (5, sizeof(int), L_DYNAMIC); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With ListCreate: %f seconds\n", seconds); fprintf (fp, "500 items:\n"); /* Test speed of ListToFront */ QueryPerformanceCounter (&C1); for (index = 0; index < 500; ++index) ListToFront (List, &index); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With ListToFront: %f seconds, %.8f p/int\n", seconds, seconds / 500); for (index = 0; index < 500; ++index) I [index] = 0; /* Test speed of ListExecute */ QueryPerformanceCounter (&C1); Int = 9; ListExecute (List, PrintMult, &Int); QueryPerformanceCounter (&C2); for (index = 0; index < 500; ++index) { if (index % 5 == 0) printf ("\n"); printf ("%dx%d:%d\t", index, Int, I [index]); } seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With ListExecute: %f seconds, %.8f p/int\n", seconds, seconds / 500); /* Test speed of ListSearch */ QueryPerformanceCounter (&C1); Int = 205; Item = ListSearch (List, Equal, &Int); QueryPerformanceCounter (&C2); printf ("Datum found: %d\n", *(int*) Item); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With ListSearch: %f seconds, %.8f p/int\n", seconds, seconds / 500); /* Test speed of ListDestroy */ QueryPerformanceCounter (&C1); ListDestroy (List); QueryPerformanceCounter (&C2); seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq; fprintf (fp, "With ListDestroy: %f seconds, %.8f p/int\n", seconds, seconds / 500); fclose (fp); /* Terminate memory; output results to file */ MemTerm ("Mem.txt"); }
int main( int argc, char **argv ) /********************************/ { int rc; char *wcl_env; char *p; char *q; char *Cmd; /* command line parameters */ #ifndef __WATCOMC__ _argc = argc; _argv = argv; #endif CC_Opts[0] = '\0'; Switch_Chars[0] = '-'; Switch_Chars[1] = _dos_switch_char(); Switch_Chars[2] = '\0'; MemInit(); ProcMemInit(); Word = MemAlloc( MAX_CMD ); Cmd = MemAlloc( MAX_CMD * 2 ); /* enough for cmd line & wcl variable */ /* add wcl environment variable to Cmd */ /* unless /y is specified in either Cmd or wcl */ wcl_env = getenv( WCLENV ); if( wcl_env != NULL ) { strcpy( Cmd, wcl_env ); strcat( Cmd, " " ); p = Cmd + strlen( Cmd ); getcmd( p ); q = Cmd; while( (q = strpbrk( q, Switch_Chars )) != NULL ) { if( tolower( *(++q) ) == 'y' ) { getcmd( Cmd ); p = Cmd; break; } } } else { getcmd( Cmd ); p = Cmd; } p = SkipSpaces( p ); if( *p == '\0' || p[0] == '?' && ( p[1] == '\0' || p[1] == ' ' ) || p[0] == '-' && p[1] == '?' ) { Usage(); rc = 1; } else { errno = 0; /* Standard C does not require fopen failure to set errno */ if( (Fp = fopen( TEMPFILE, "w" )) == NULL ) { /* Message before banner decision as '@' option uses Fp in Parse() */ PrintMsg( WclMsgs[UNABLE_TO_OPEN_TEMPORARY_FILE], TEMPFILE, strerror( errno ) ); rc = 1; } else { initialize_Flags(); rc = Parse( Cmd ); if( rc == 0 ) { if( !Flags.be_quiet ) { print_banner(); } rc = CompLink(); } if( rc == 1 ) { fclose( Fp ); } if( Link_Name != NULL ) { if( fname_cmp( Link_Name, TEMPFILE ) != 0 ) { remove( Link_Name ); rename( TEMPFILE, Link_Name ); } } else { remove( TEMPFILE ); } } } ProcMemFini(); MemFree( Cmd ); MemFree( Word ); MemFini(); return( rc == 0 ? 0 : 1 ); }
//===================================== // // cmd // //===================================== static bool cmd( int nArgc, char *pstrArgv[] ) { u32 addr; enum ESTYPE stype; u32 data; u32 data_check = 0xFFFFFFFF; u32 data_mask = 0; STMEMCTRL *pmctrl = NULL; bool ret = false; int i = 0; stype = CmdGetDataSize( pstrArgv[i++] , TLONG ); if ( 0 == strcmp( "-m", pstrArgv[i])) data_mask = (u32)i++; addr = GetAddress( pstrArgv[i++] ); if ( data_mask ) data_mask = GetData( pstrArgv[i++] ); data = GetData( pstrArgv[i++] ); if ( nArgc != i ) { printf( "program error\nneeded re-check %d %d\n", nArgc, i ); return false; } if ( TERR == stype ) return Usage( "type error" ); if( !MemInit( )) return Error( "mem ctrl init error" ); pmctrl = GetMemCtrl( stype ); if ( !pmctrl ) { Error( "get mem ctrl error" ); goto error; } if ( addr & (pmctrl->nIncSize-1) ) { Error( "address alignment error" ); goto error; } /* * CAUTION * * we can not use 32 bit shift. * this operation is undefined in C !! * So, this time we use 8bit shift and loop */ for ( i=0 ; i<pmctrl->nIncSize; i++ ) data_check = data_check << 8; if ( data & data_check ) { Error( "input data error" ); goto error; } if ( data_mask & data_check ) { Error( "data mask error" ); goto error; } if ( data_mask ) { u32 current; if ( !pmctrl->fnRead( addr , ¤t ) ) goto error; data = (current & ~data_mask) | (data & data_mask); } pmctrl->fnEdit( addr , &data ); ret = true; error: MemExit( ); return ret; }