byte huge *getdump (long *size,void (* func)(double)) /*********** * Describe : принять дамп памяти прибора в память ЭВМ * Params : word *size - размер принятых данных (в байтах), меньше чем * : размер выделенной памяти, так как он выровнен * : на границу 1024 байта * : PFV func - функция для отображения считывания, ей * : передаем процент считанной информации * Return : byte huge* - указатель на буфер, куда записаны данные * Call : input,waitstart,setaddr,getKbyte,bioscom ***********/ { /* i-текущий адрес */ unsigned long volume,i_long; uint i=0,Imax=1024; /* Imax-макс. адрес */ byte empty,bufer[1024]; /* */ int err=0,rpt=0; /* */ byte huge *ppm=NULL,huge *cur=NULL; /* указатель на буфер */ // считываем базовый адрес порта base_addr = *((unsigned far *)((unsigned far *)0x00400000L+connect_port)); if (base_addr==0) // СОМ1 в 40:00 СОМ2 в 42:00 {printf("\nCOM-%d is absent!",connect_port); return 0; } // bioscom (0,SETTINGS,connect_port); /* инициализируем COM */ outportb (base_addr+3,0x83); // 8byt 1stop N outportb (base_addr,12); // скорость обмена 115200/12=9600 outportb (base_addr+1,0); outportb (base_addr+3,0x03); // конец установки скорости empty = inportb (base_addr+4); outportb (base_addr+4,0); // Запрет прерывания от порта for (i_long=0L;i_long<Imax;i_long+=512L,cur=(byte huge *)cur+1024,i=(uint)i_long) { if (func!=NULL) /* */ func ((double)((double)i_long/(double)Imax)); /* рисуем прогресс */ sleep (1); do /* */ { /* */ setaddr(i); /* посылаем адрес начала */ err=waitstart(); /* ждем строки "STRT" */ if (err==0) /* если не ошибка то */ err=input(&empty); /* принимаем пустой байт */ if (err==0) /* если не ошибка и если */ if (i==0) /* первый Кбайт то */ err=getKbyte(bufer); /* принимаем в буфер */ else /* иначе */ { err=getKbyte(cur); /* принимаем в назначение */ if (*bufer!=*ppm) { printf ("\n There is problem, count = %u",(uint)i); abort (); } } if (err != 0) /* если ошибка */ { /* */ rpt++; /* число повторов */ if (rpt>REPEATS) /* */ { /* */ if (ppm!=NULL) /* освобождаем память */ farfree ((byte far *)ppm); /* если выделена */ printf("\nCommunication ERROR %X",(unsigned)err); return (NULL); /* возвращаем ошибка */ } /* */ } /* */ } /* */ while (err!=0); /* */ /* */ if (i==0) /* если первый Кбайт */ { /* то */ Imax = (uint)bufer[8]+bufer[9]*256; /* вычисляем Imax */ *size = (long)Imax*2L; /* размер в байтах */ volume = (unsigned long)(*size)+1024; /* выделяем 128 Кбайт */ ppm=(byte huge*) farcalloc(volume,sizeof(byte));/* выделяем память */ cur = ppm; if (ppm==NULL) { printf ("\n Imax = %u, size = %ld",Imax,(*size)); printf ("\n No enough memory! Function GETDUMP. "); printf ("\n %ul bytes free. ",farcoreleft()); abort (); } reportmemory(getmaxx(),getmaxy()-textheight("X")-5); memcpy ((byte *)ppm,bufer,1024); /* копируем из буфера */ } /* */ } /* */ if (func!=NULL) /* */ func ((double)1.0); /* рисуем прогресс */ return ((byte huge*) ppm); /* */ } /* */
//------- Zapis obdelnika videoram do XMS/Disk ------------------- int xv_to_virt(int xo, int yo, int xs, int ys, int dx, int dy) { // xo,yo - pravy horni bod obrazu na obrazovce // xs,ys - pravy horni bod obrazu v souboru // dx,dy - velikost obrazu v pixlech // Ppg. zapise do souboru obdelnik z videoram. // Pozn: pro 2 a 16 barev musi byt vsechna x nasobkem 8 !!! char *inbuf=NULL; int ist,yak,dyak,yoak; long lenmap,xx_lenbuf; int nkusu,nline,x2o,kk,LenLine; if(xv_vv[xv_act].xv_file <= 0 && xv_vv[xv_act].xv_XMS==-1) return( 2 ); if(xv_vv[xv_act].xv_bits != 0 && xg_256 == MM_256) return( 4 ); if(xv_vv[xv_act].xv_bits != 3 && xg_256 == MM_2) return( 4 ); #if HI_COLOR if(xv_vv[xv_act].xv_bits != -1 && xg_256 == MM_Hic) return( 4 ); #endif lenmap = farcoreleft(); // Kolik alokovat if(lenmap >= 65512L) xx_lenbuf = 55512L; else xx_lenbuf = lenmap - (dx+1024); if(xx_lenbuf < (dx+16)) return( 6 ); // Neni pamet ani na 1 radek inbuf = farmalloc(xx_lenbuf); if(inbuf == NULL) return( 6 ); if(xv_vv[xv_act].xv_bits >= 0) LenLine = dx>>xv_vv[xv_act].xv_bits; else
void dbg_printmem(void) { static unsigned nearLast = 0; static unsigned long farLast = 0; unsigned nearThis; unsigned long farThis; switch(heapcheck()) { case _HEAPCORRUPT: cputs("HEAP CORRUPTED. Cannot proceed!\r\n"); abort(); case _HEAPEMPTY: cputs("NO HEAP. Cannot proceed!\r\n"); abort(); default: cputs("Unknown heapcheck() error. Cannot proceed!\r\n"); abort(); case _HEAPOK: break; } nearThis = coreleft(); farThis = farcoreleft(); dprintf(("[free memory: near=%6u far=%13lu]\n", nearThis, farThis)); if(nearLast) dprintf(("[changed : near=%6d far=%13ld]\n" , nearThis - nearLast , farThis - farLast)); nearLast = nearThis; farLast = farThis; }
/************************************************************************ Function : Main Returns : zero on successful execution 3 on an error condition The main routine allocates memory for the input and output buffers. Characters are then read from the input buffer building the line buffer that will be sent to the filter processor. Lines are read and filtered until the end of input is reached. ************************************************************************/ int main(void) { char c; int i, Type; unsigned long core; setmode(1,O_BINARY); /* set standard out to binary mode */ NoLines = FALSE; /* No lines have been read yet */ core = farcoreleft(); /* get available memory */ if (core > 64000U) /* limit buffers to total of 64000 */ BufSize = 64000U; /* bytes */ else BufSize = (unsigned)core; if ((InBuffer = malloc(BufSize)) == NULL) /* allocate buffer space */ exit(3); /* abort if error occured */ CurInPtr = InBuffer; /* split buffer */ BufSize = BufSize/2; /* between input and output buffers */ OutBuffer = InBuffer + BufSize; CurOutPtr = OutBuffer; LinePtr = Line; /* set line buffer pointer */ CurBufLen = 0; /* and reset buffer size to zero */ Put(PipeId,PipeIdLen); /* Identify process to message window */ while ((c = NextChar()) != 0) /* read characters */ { if ((c == 13) || (c == 10)) /* build line until new line is seen */ { *LinePtr = 0; ProcessLine(Line); /* then filter the line */ LinePtr = Line; } /* characters are added to line only up to 132 characters */ else if ((FP_OFF(LinePtr) - FP_OFF(&Line)) < 132) { *LinePtr = c; LinePtr++; } } *LinePtr = 0; ProcessLine(Line); /* filter last line */ if (NoLines) /* if no lines */ { Type = MsgNewLine; /* send something to the */ i = 1; /* message window */ Put((char *)&Type,1); Put((char *)&i,2); Put((char *)&i,2); Put(" ",2); } EndMark = MsgEoFile; /* indicate end of input to */ Put(&EndMark,1); /* message window */ flushOut((unsigned)(CurOutPtr-OutBuffer)); /* flush out remaining buffer */ return 0; /* everything went ok */ }
static void *memalloc( rspf_uint32 size ) { void *ptr; ptr = malloc(size); if (!ptr) { #ifdef __MSDOS__ printf("Memory allocation error in VPFQUERY (%d)(%d)\n",size, farcoreleft()); #else printf("Memory allocation error in VPFQUERY (%d)\n",(int)size); #endif exit(1); } return ptr; }
/*********************************************************************** Function : main Returns : zero for successful execution 3 if an error is encountered The main routine allocates buffers for the input and output buffer. Characters are then read from the input buffer building the line buffer that will be sent to the filter processor. Lines are read and filtered until the end of input is reached. ***********************************************************************/ int main( void ) { char c; unsigned long core; setmode(1,O_BINARY); /* set output stream to binary mode */ core = farcoreleft(); if (core > 64000U) BufSize = 64000U; else BufSize = (unsigned)core; /* get available memory */ /* stay under 64K */ if ((CurInPtr = malloc(BufSize)) == NULL) /* allocate buffer space */ exit(3); #if 0 processor = NULL; /* set current processor to none */ #endif InBuffer = CurInPtr; /* input buffer is first half of space */ BufSize = BufSize/2; /* output buffer is 2nd half */ OutBuffer = InBuffer + BufSize; CurOutPtr = OutBuffer; /* set buffer pointers */ LinePtr = Line; CurBufLen = 0; Put(PipeId,PipeIdLen); /* send ID string to message window */ while ((c = NextChar()) != 0) /* read characters */ { if ((c == 13) || (c == 10)) /* build until line end */ { *LinePtr = 0; ProcessLine(Line); /* filter the line */ LinePtr = Line; } /* characters are added to buffer up to 132 characters max */ else if ((FP_OFF(LinePtr) - FP_OFF(&Line)) < 132) { *LinePtr = c; /* add to line buffer */ LinePtr++; } } *LinePtr = 0; ProcessLine(Line); /* filter last line */ EndMark = MsgEoFile; Put(&EndMark,1); /* indicate end of input to the message window */ flushOut((unsigned)(CurOutPtr-OutBuffer)); /* flush the buffer */ return 0; /* return OK */ }
void ulist_init() { uint i; user.list=lmalloc(sizeof(ulist_t) *(MAX_user+1)); if (user.list==NULL) error(lpu(farcoreleft(),0)); op_user(); for (i=0;i<=user.member;++i) { if (sion_sr("user",lpu(i,0))==0) continue; sion_read(nowvar); ulist_rep(i,nowvar); } sion_close(); }
/************************************************************************* * *N vpfmalloc * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function allocates memory off of the heap and checks for * success. If not enough memory is available, this routine will abort * the program with an error message. Can be in graphics mode to call * this procedure, not a necessity. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * size <input> == (unsigned long) number of bytes to allocate. * return <output> == (void *) pointer to the allocated memory. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1990 Original Version DOS Turbo C * Ronald Rozensky Sept 1991 check for no memory, graphics mode *E *************************************************************************/ void *vpfmalloc( unsigned long size ) { void *p; #ifdef __MSDOS__ p = farmalloc( size ); if (!p) { printf("Out of memory %ld %ld\n",size,farcoreleft()); getch(); if (graphic_mode()) closegraph(); exit(1); } #else p = malloc(size); if (!p) { printf("Out of memory %ld\n", size); exit(1); } #endif return p; }
byte huge *getdump (long *size,void (* func)(double)) /*********** * Describe : принять дамп памяти прибора в память ЭВМ * Params : word *size - размер принятых данных (в байтах), меньше чем * : размер выделенной памяти, так как он выровнен * : на границу 1024 байта * : PFV func - функция для отображения считывания, ей * : передаем процент считанной информации * Return : byte huge* - указатель на буфер, куда записаны данные * Call : input,waitstart,setaddr,getKbyte,bioscom ***********/ { /* i-текущий адрес */ unsigned long volume,i_long; uint i=0,Imax=1024; /* Imax-макс. адрес */ byte bufer[1024]; /* */ int err=0,rpt=0; /* */ byte huge *ppm=NULL,huge *cur=NULL; /* указатель на буфер */ /* */ fout=fopen("memory.bin","rb"); if (fout==NULL) { printf ("\n Can't found file memory.bin. " "\n Try find it in current directory. "); abort (); } for (i_long=0L;i_long<Imax;i_long+=512L,cur=(byte huge *)cur+1024,i=(uint)i_long) { if (func!=NULL) /* */ func ((double)((double)i_long/(double)Imax)); /* рисуем прогресс */ do /* */ { /* */ if (err<=8) /* если не ошибка и если */ if (i==0) /* первый Кбайт то */ err=getKbyte(bufer); /* принимаем в буфер */ else /* иначе */ { err=getKbyte(cur); /* принимаем в назначение */ if (*bufer!=*ppm) { printf ("\n There is problem, count = %u",(uint)i); abort (); } } if (err>8) /* если ошибка */ { /* */ rpt++; /* число повторов */ if (rpt>REPEATS) /* */ { /* */ if (ppm!=NULL) /* освобождаем память */ farfree ((byte far *)ppm); /* если выделена */ return (NULL); /* возвращаем ошибка */ } /* */ } /* */ } /* */ while (err>8); /* */ /* */ if (i==0) /* если первый Кбайт */ { /* то */ Imax=(uint) bufer[8]+bufer[9]*256; /* вычисляем Imax */ *size=(long) Imax*2L; /* размер в байтах */ volume=(unsigned long) (*size)+1024L; /* выравненный по 1024 б */ ppm=(byte huge*) farcalloc(volume,sizeof(byte));/* выделяем память */ cur = ppm; if (ppm==NULL) { printf ("\n Imax = %u, size = %ld",Imax,(*size)); printf ("\n No enough memory! Function GETDUMP. "); printf ("\n %ul bytes free. ",farcoreleft()); abort (); } memcpy ((byte *)ppm,bufer,1024); /* копируем из буфера */ } /* */ } /* */ if (func!=NULL) /* */ func ((double)1.0); /* рисуем прогресс */ fclose (fout); return ((byte huge*) ppm); /* */ } /* */
/************************************************************************* * *N vpf_open_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function opens a vpf table and either loads it into RAM or sets * up the structure to read off of disk. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * tablename <input> == (const char *) file name of the table. * storage <input> == (storage_type) table storage mode - * either ram or disk. * mode <input> == (const char *) file mode for opening the table - * same as fopen() mode in C. * defstr <input> == (char *) table definition string used for * creating a writable table. * vpf_open_table <output> == (vpf_table_type) VPF table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels April 1991 DOS Turbo C * Dave Flinn July 1991 UNIX compatable *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ vpf_table_type vpf_open_table( const char * tablename, storage_type storage , const char * mode, char * defstr ) { vpf_table_type table; char tablepath[255], * idxname; ossim_int32 i, j; ossim_int32 tablesize, idxsize, memsize; ossim_uint32 ulval; char * diskname = "VPF data disc"; strcpy(tablepath,tablename); rightjust(tablepath); /* Parse out name and path */ j = -1; i=(long)strlen(tablepath); while (i>0) { #ifdef __MSDOS__ if (tablepath[i] == '\\') { #else if (tablepath[i] == '/') { #endif j = i; break; } i--; } strncpy(table.name,&(tablepath[j+1]),12); rightjust(table.name); strupr(table.name); table.path = (char *)vpfmalloc(((unsigned long)strlen(tablepath)+5)*(unsigned long)sizeof(char)); strcpy(table.path, tablepath); table.path[j+1] = '\0'; /* Establish a read or write table operation */ if ( mode[0] == 'r' ) table.mode = Read ; else table.mode = Write ; /*fprintf(stderr, "vpf_open_table opening %s\n", tablepath);*/ table.fp = vpfopencheck(tablepath,mode,diskname); if (table.fp == NULL) { perror(tablepath); /* #if __MSDOS__ perror(tablepath); getch(); if (getgraphmode() >= 0) closegraph(); exit(0); #endif */ free(table.path); if (table.fp) { fclose(table.fp); table.fp = NULL; } return table; } /* If file is to be created, copy the def string ptr into header for now */ if ( table.mode == Write ) table.defstr = defstr ; #ifdef __MSDOS__ tablesize = (filelength(fileno(table.fp))); #else { /* UNIX doesn't have a filelength function, so this is the best */ struct stat statbuf ; if ( stat ( tablepath, &statbuf ) < 0 ) { fprintf (stderr, "vpf_open_table: can't stat file\n" ) ; free(table.path); fclose(table.fp); table.fp = NULL; return table; } tablesize = statbuf.st_size ; } #endif /* Populate table structure with correct data, either for read or write */ table.reclen = parse_data_def(&table); if ( table.mode == Write ) { /* write out header */ rewind ( table.fp ) ; Write_Vpf_Int ( &table.ddlen, table.fp, 1 ) ; Write_Vpf_Char ( table.defstr, table.fp, table.ddlen ) ; free ( table.defstr ) ; table.defstr = (char *) NULL ; table.nrows = 0 ; } if (table.reclen > 0) { /* Index file */ table.xstorage = (storage_type)COMPUTE; if (table.mode != Write) table.nrows = (tablesize - table.ddlen)/table.reclen; table.xfp = (FILE *) NULL ; } else { idxname = strdup( tablepath ); #ifdef __MSDOS__ idxname[strlen(tablepath)-1] = 'x'; #else if (idxname[strlen(tablepath)-1] == '.') idxname[strlen(tablepath)-2] = 'x'; else idxname[strlen(tablepath)-1] = 'x'; #endif table.xfp = fopen(idxname, mode); if ((!table.xfp) && (table.mode == Read)) { perror(idxname); fprintf(stderr, "hit RETURN to continue..."); i=getc(stdin); free(idxname); for (i = 0; i < table.nfields; i++) free(table.header[i].name); free(table.header); free(table.path); fclose(table.fp); table.fp = NULL; return table; } free(idxname); /*#ifdef __MSDOS__*/ table.xstorage = (storage_type)DISK; /* Worst case default */ /*#endif*/ /* Only read in index if file is read only */ if (table.xfp && ( table.mode == Read ) ) { Read_Vpf_Int (&(table.nrows), table.xfp, 1 ) ; Read_Vpf_Int (&ulval, table.xfp, 1 ) ; idxsize = table.nrows*sizeof(index_cell) + 10L; #ifdef __MSDOS__ if ( (idxsize < (farcoreleft()/2)) && (idxsize < __64K) ) #else if (0) #endif { table.xstorage = (storage_type)RAM; table.index = (index_type)vpfmalloc(idxsize); for (i=0;i<table.nrows;i++) { Read_Vpf_Int (&(table.index[i].pos), table.xfp, 1) ; Read_Vpf_Int (&(table.index[i].length),table.xfp,1 ) ; } fclose(table.xfp); } } else if (table.mode == Write) { /* Write out dummy header record for index file. vpf_close_table finishes the job. */ Write_Vpf_Int ( &(table.ddlen), table.xfp, 1 ) ; Write_Vpf_Int ( &(table.ddlen), table.xfp, 1 ) ; table.xstorage = (storage_type)DISK; table.index = (index_type) NULL ; } } /* end of if table .reclen */ table.storage = (storage_type)DISK; #ifdef __MSDOS__ memsize = (ossim_int32)min(farcoreleft(),__64K); #else memsize = MAXINT; #endif if ( (storage != disk) && ( table.mode == Read ) ) { if (tablesize + table.nrows * table.nfields * HEAP_OVERHEAD < memsize) { fseek(table.fp,index_pos(1,table),SEEK_SET); table.row = (row_type *)vpfmalloc((table.nrows+1)*sizeof(row_type)); for (i=0;i<table.nrows;i++) { table.row[i] = read_next_row(table); } fclose(table.fp); table.storage = (storage_type)RAM; } } table.status = OPENED; return table; } /************************************************************************* * *N vpf_close_table * *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Purpose: *P * This function frees an entire table from memory. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Parameters: *A * table <inout> == (vpf_table_type) VPF table structure. *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * History: *H * Barry Michaels May 1991 DOS Turbo C *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * External Variables: *X * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Functions Called: *F * None *E *:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * Portability: *O * This module should be ANSI C compatible. *E *************************************************************************/ void vpf_close_table( vpf_table_type *table ) { register ossim_int32 i; if (table->status != OPENED) { return; } /*fprintf(stderr, "vpf_close_table closing %s%s\n", table->path, table->name);*/ /* If the table is writable, write out the final record count */ if ( table->mode == Write && table->xfp ) { rewind ( table->xfp ) ; Write_Vpf_Int ( &table->nrows, table->xfp, 1 ) ; Write_Vpf_Int ( &table->ddlen, table->xfp, 1 ) ; } for (i=0;i<table->nfields;i++) { free(table->header[i].name); /* free up null text string */ if ( table->header[i].type == 'T') free(table->header[i].nullval.Char); /* free up index file string */ if (table->header[i].tdx!=(char *)NULL) free ( table->header[i].tdx ) ; /* free up narrative table string */ if (table->header[i].narrative!=(char *)NULL) { free ( table->header[i].narrative ) ; } } free(table->header); switch (table->storage) { case RAM: for (i=0;i<table->nrows;i++) free_row(table->row[i],*table); free(table->row); break; case DISK: fclose(table->fp); break; default: printf("%s%s: unknown storage flag: %d\n",table->path,table->name, table->storage); break; } switch (table->xstorage) { case RAM: free(table->index); break; case DISK: fclose(table->xfp); break; case COMPUTE: break; default: printf("%s%s: unknown index storage flag: %d\n", table->path,table->name,table->storage); break; } table->nfields = 0; free(table->path); table->status = CLOSED; } ossim_int32 is_vpf_table( const char *fname ) { FILE *fp; ossim_int32 n, ok; fp = fopen( fname, "rb" ); if (!fp) { return FALSE; } Read_Vpf_Int ( &n, fp, 1 ) ; fseek( fp, n-1, SEEK_CUR ); if (fgetc(fp) == ';') ok = TRUE; else ok = FALSE; fclose(fp); return ok; }
void MM_Startup (void) { id0_int_t i; id0_unsigned_long_t length; //void id0_far *start; id0_unsigned_t segstart,seglength,endfree; if (mmstarted) MM_Shutdown (); mmstarted = true; bombonerror = true; // // set up the linked list (everything in the free list) // mmhead = NULL; mmfree = &mmblocks[0]; for (i=0; i<MAXBLOCKS-1; i++) mmblocks[i].next = &mmblocks[i+1]; mmblocks[i].next = NULL; // // get all available near conventional memory segments // length = EMULATED_NEAR_PARAGRAPHS*16 - SAVENEARHEAP; seglength = length / 16; // now in paragraphs segstart = EMULATED_NEAR_SEG; mminfo.nearheap = length; #if 0 length=coreleft(); start = (void id0_far *)(nearheap = malloc(length)); length -= 16-(FP_OFF(start)&15); length -= SAVENEARHEAP; seglength = length / 16; // now in paragraphs segstart = FP_SEG(start)+(FP_OFF(start)+15)/16; mminfo.nearheap = length; #endif // locked block of unusable low memory // from 0 to start of near heap // Formerly known as GETNEWBLOCK if( !(mmnew=mmfree) ) { Quit("MM_GETNEWBLOCK: No free blocks!"); } mmfree=mmfree->next; // fill in start and next after a spot is found mmhead = mmnew; // this will always be the first node mmnew->start = 0; mmnew->length = segstart; mmnew->attributes = LOCKBIT; endfree = segstart+seglength; mmrover = mmhead; // // get all available far conventional memory segments // length = EMULATED_FAR_PARAGRAPHS*16 - SAVEFARHEAP; seglength = length / 16; // now in paragraphs segstart = EMULATED_FAR_SEG; mminfo.farheap = length; mminfo.mainmem = mminfo.nearheap + mminfo.farheap; #if 0 length=farcoreleft(); start = farheap = farmalloc(length); length -= 16-(FP_OFF(start)&15); length -= SAVEFARHEAP; seglength = length / 16; // now in paragraphs segstart = FP_SEG(start)+(FP_OFF(start)+15)/16; mminfo.farheap = length; mminfo.mainmem = mminfo.nearheap + mminfo.farheap; #endif // locked block of unusable near heap memory (usually just the stack) // from end of near heap to start of far heap // Formerly known as GETNEWBLOCK if( !(mmnew=mmfree) ) { Quit("MM_GETNEWBLOCK: No free blocks!"); } mmfree=mmfree->next; // fill in start and next after a spot is found mmnew->start = endfree; mmnew->length = segstart-endfree; mmnew->attributes = LOCKBIT; mmrover->next = mmnew; endfree = segstart+seglength; mmrover = mmnew; // // detect EMS and allocate 64K at page frame // mminfo.EMSmem = 0x10000; // Looks unused #if 0 if (MML_CheckForEMS()) { MM_MapEMS(); // map in used pages mminfo.EMSmem = 0x10000l; } else { mminfo.EMSmem = 0; } #endif // // detect XMS and get upper memory blocks // mminfo.XMSmem = 0; // Unused #if 0 if (MML_CheckForXMS()) { } else { mminfo.XMSmem = 0; } #endif // // cap off the list // // locked block of high memory (video, rom, etc) // from end of far heap or EMS/XMS to 0xffff // Formerly known as GETNEWBLOCK if( !(mmnew=mmfree) ) { Quit("MM_GETNEWBLOCK: No free blocks!"); } mmfree=mmfree->next; // fill in start and next after a spot is found mmnew->start = endfree; mmnew->length = 0xffff-endfree; mmnew->attributes = LOCKBIT; mmnew->next = NULL; mmrover->next = mmnew; // // allocate the misc buffer // mmrover = mmhead; // start looking for space after low block MM_GetPtr (&bufferseg,BUFFERSIZE); }
int InitializeFittingMemory (unsigned long size, int HardDiskOk, unsigned long *allocated, /* Needed to check wether a swap file is not created on the source or destination drive: */ char sdrv, char tdrv) { char *tempvar = NULL; struct dfree free; int curdisk, tempdisk, run = 1; unsigned long farfree; struct IniParserStruct *ParsedData; ParsedData = GetParsedData (); Initialised = TRUE; AmofProcessed = 0; CloseFunc = DoNothing; PrepareToReadFunc = ResetAmof; PrepareToWriteFunc = ResetAmof; /* First of all see wether main memory is not large enough */ farfree = farcoreleft (); if (farfree > size) { FarBlock = (char far *) farmalloc (size); LastOffset = FP_OFF (FarBlock); LastSegment = FP_SEG (FarBlock); SavedSegment = LastSegment = LastSegment + LastOffset / 16; SavedOffset = LastOffset = LastOffset % 16; MemType = BUFFERS; CloseFunc = CloseBuffers; ReadFunc = BufferRead; WriteFunc = BufferWrite; PrepareToReadFunc = PrepareForChangingBuffers; PrepareToWriteFunc = PrepareForChangingBuffers; *allocated = size; } /* See wether EMS is installed. */ if ((!MemType) && ParsedData->UseEMS && ((EMSBase = EMSbaseaddress ()) != 0)) { /* See if there is enough memory. */ if ((size / 16384) + 1 < EMSpages ()) { Handle = EMSalloc ((int) (size / 16384) + 1); if (Handle >= 0) { CloseFunc = CloseEMS; WriteFunc = EMSWrite; ReadFunc = EMSRead; MemType = EMS; } *allocated = size; } } /* See wether XMS is installed. */ if (ParsedData->UseXMS && (!MemType) && XMSinit ()) { /* See if there is enough memory. */ if (size < XMScoreleft ()) { Handle = XMSalloc (size); if (Handle != 0) { MemType = XMS; CloseFunc = CloseXMS; WriteFunc = XMSWrite; ReadFunc = XMSRead; } *allocated = size; } } /* See wether the hard disk can be used. */ if (!MemType && HardDiskOk) { tempvar = getenv ("temp"); if (!tempvar) tempvar = getenv ("TEMP"); if (tempvar && tempvar[0]) strcpy (tempfile, tempvar); else strcpy (tempfile, "C:\\"); /* Make sure that the disk where the temporary file is created is not either the source of the target of the disk copy. */ if ((toupper (tempfile[0]) == toupper (sdrv)) || (toupper (tempfile[0]) == toupper (tdrv))) strcpy (tempfile, "C:\\"); curdisk = getdisk (); tempdisk = toupper (tempfile[0]) - 65; /* If the TEMP environment variable doesn't have a path form, use the root of c: instead. */ if ((tempdisk < 0) || (tempdisk > 26) || (tempfile[1] != ':')) { strcpy (tempfile, "C:\\"); tempdisk = 2; } for (;;) { setdisk (tempdisk); if (getdisk () == tempdisk) { unsigned long total; setdisk (curdisk); getdfree (tempdisk + 1, &free); total = (long) free.df_avail * (long) free.df_bsec * (long) free.df_sclus; if (total >= size) { char* pSFNSlot; ConvertToSFN(tempfile, ENVVAR_ID); pSFNSlot = GetSFN(ENVVAR_ID); if (pSFNSlot) { strcpy(tempfile, pSFNSlot); Handle = creattemp (tempfile, 0); if (Handle != -1) { MemType = HARDDISK; CloseFunc = CloseDisk; ReadFunc = DiskRead; WriteFunc = DiskWrite; PrepareToReadFunc = PrepareForReadingDisk; PrepareToWriteFunc = PrepareForWritingDisk; *allocated = size; break; } } } } if (tempdisk != 2 || run == 1) /* if not C drive. */ { run++; strcpy (tempfile, "C:\\"); tempdisk = 2; /* try C drive instead. */ } else break; } } /* See if there is enough memory left on the far heap. */ if (!MemType && farfree > BUFFERSIZE) { size = farfree - (farfree % BUFFERSIZE); FarBlock = (char far *) farmalloc (size); LastOffset = FP_OFF (FarBlock); LastSegment = FP_SEG (FarBlock); SavedSegment = LastSegment = LastSegment + LastOffset / 16; SavedOffset = LastOffset = LastOffset % 16; MemType = BUFFERS; CloseFunc = CloseBuffers; ReadFunc = BufferRead; WriteFunc = BufferWrite; PrepareToReadFunc = PrepareForChangingBuffers; PrepareToWriteFunc = PrepareForChangingBuffers; *allocated = size; } return MemType; }
void TERMWINDOWMEMBER DoDebugCmd(const char **ncmsg) { char str[128]; NetCmdReplyMsg->SetTextWithFormat(ncmsg[5], programName, version); NetCmdReplyMsg->AppendText(bn); #ifndef VISUALC sprintf(str, ncmsg[6], _osmajor, _osminor); AppendLineToNetCommandReply(str); #endif if (LockMenu(MENU_READ)) { #ifndef WINCIT if (*vdDesc) { sprintf(str, getmenumsg(MENU_READ, 84), getmenumsg(MENU_READ, 85), vdDesc); AppendLineToNetCommandReply(str); } if (*cdDesc) { sprintf(str, getmenumsg(MENU_READ, 84), getmenumsg(MENU_READ, 86), cdDesc); AppendLineToNetCommandReply(str); } if (*kdDesc) { sprintf(str, getmenumsg(MENU_READ, 84), getmenumsg(MENU_READ, 87), kdDesc); AppendLineToNetCommandReply(str); } if (*sdDesc) { sprintf(str, getmenumsg(MENU_READ, 84), getmenumsg(MENU_READ, 88), sdDesc); AppendLineToNetCommandReply(str); } #endif #ifdef MSC r.h.ah = 0x48; // allocate memory r.h.al = 0; r.x.bx = 0xffff; // ask for an impossible amount intdos(&r, &r); sprintf(str, getmenumsg(MENU_READ, 90), _bios_memsize()); NetCmdReplyMsg->AppendText(str); sprintf(str, getmenumsg(MENU_READ, 91), ltoac((long)r.x.bx*16L)); AppendLineToNetCommandReply(str); #else #ifdef WINCIT MEMORYSTATUS ms; ms.dwLength = sizeof(ms); GlobalMemoryStatus(&ms); label Avail; CopyStringToBuffer(Avail, ltoac(ms.dwAvailPhys / 1024)); sprintf(str, getmenumsg(MENU_READ, 92), ltoac(ms.dwTotalPhys / 1024), Avail); AppendLineToNetCommandReply(str); CopyStringToBuffer(Avail, ltoac(ms.dwAvailPageFile / 1024)); sprintf(str, getmenumsg(MENU_READ, 93), ltoac(ms.dwTotalPageFile / 1024), Avail); AppendLineToNetCommandReply(str); CopyStringToBuffer(Avail, ltoac(ms.dwAvailVirtual / 1024)); sprintf(str, getmenumsg(MENU_READ, 107), ltoac(ms.dwTotalVirtual / 1024), Avail); AppendLineToNetCommandReply(str); sprintf(str, getmenumsg(MENU_READ, 108), ms.dwMemoryLoad); AppendLineToNetCommandReply(str); #else sprintf(str, getmenumsg(MENU_READ, 90), biosmemory()); NetCmdReplyMsg->AppendText(str); sprintf(str, getmenumsg(MENU_READ, 91), ltoac(farcoreleft())); AppendLineToNetCommandReply(str); #endif #endif if (*cmdLine) { sprintf(str, getmenumsg(MENU_READ, 94), cmdLine); AppendLineToNetCommandReply(str); } UnlockMenu(MENU_READ); } else { sprintf(str, getmsg(188), ncmsg[76]); AppendLineToNetCommandReply(str); } sprintf(str, ncmsg[7], cfg.sysop); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[8], cfg.mdata); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[9], cfg.dumbmodem); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[10], bauds[cfg.initbaud]); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[11], connectbauds[cfg.minbaud]); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[12], cfg.modsetup); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[13], cfg.modunsetup); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[14], cfg.downshift); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[15], cfg.dialsetup); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[16], cfg.dialpref); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[17], cfg.dialring); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[18], cfg.dialringwait); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[19], cfg.downshift); NetCmdReplyMsg->AppendText(str); for (int i = 0; i < 7; i++) { if (cfg.updays[i]) { sprintf(str, ncmsg[38], i + 1); NetCmdReplyMsg->AppendText(str); } } NetCmdReplyMsg->AppendText(bn); sprintf(str, ncmsg[20], cfg.downshift); NetCmdReplyMsg->AppendText(str); EXTRA_OPEN_BRACE for (int i = 0; i < 24; i++) { if (cfg.uphours[i]) { sprintf(str, ncmsg[38], i + 1); NetCmdReplyMsg->AppendText(str); } } EXTRA_CLOSE_BRACE NetCmdReplyMsg->AppendText(bn); sprintf(str, ncmsg[21], cfg.hangupdelay); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[22], cfg.hangup); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[23], cfg.offhookstr); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[24], cfg.baudPause); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[26], cfg.autoansi); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[27], cfg.MsgDatSizeInK); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[28], cfg.maxfiles); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[29], cfg.MAXLOGTAB); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[30], cfg.maxrooms); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[31], cfg.maxhalls); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[32], cfg.maxgroups); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[33], cfg.maxborders); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[34], (ulong) cfg.nmessages); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[35], cfg.ovrEms); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[36], cfg.ovrExt); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[37], cfg.bios); AppendLineToNetCommandReply(str); #ifdef AUXMEM sprintf(str, ncmsg[40], cfg.vmemfile); AppendLineToNetCommandReply(str); #endif sprintf(str, ncmsg[41], cfg.checkCTS); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[42], cfg.scrollSize); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[43], cfg.scrollColors); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[44], cfg.maxjumpback); AppendLineToNetCommandReply(str); sprintf(str, ncmsg[45], cfg.statnum); AppendLineToNetCommandReply(str); }
int main(int argc, char **argv) { int CheckDuplicateDescriptions; int SortBy; int SkipTilde; int SkipMovedto; char *arg; int c; int i; int j; FILE *fp; struct ffblk ffb; int done; int Len; char **Lines; int maxLines; int nLines; int pathlen; char Line[200]; char Dirname[MAX_PATH]; char Filename[MAX_PATH]; char OutFilename[MAX_PATH]; char *s; char *Description; char *FormattedLine; unsigned long farcoreleftStart; unsigned long farcoreleftEnd; long FileSize; struct stat statbuf; int verbose; int ragged; int terminalsized; printf("%s\n", ProgVer); printf("Replacement for James Jessiman's makelist\n"); printf("Call with -h to see a list of options.\n\n"); strcpy(Dirname, "PARTS"); /* Default input directory path */ strcpy(OutFilename, "parts.lst"); /* Default output filename */ verbose = 0; ragged = 1; /* Steve wants it ragged by default */ terminalsized = 1; /* Steve wants it to fit in 80 chars by default */ CheckDuplicateDescriptions = 0; SortBy = 0; SkipTilde = 0; SkipMovedto = 1; while (--argc > 0) { arg = *++argv; if (arg[0] == '-') { switch (arg[1]) { case '?': case 'h': PrintUsage(); exit(1); break; case '8': namelen = 12; break; case 'c': CheckDuplicateDescriptions = 1; break; case 'n': case 'd': SortBy = arg[1]; break; case 'm': SkipMovedto = 0; break; case '~': SkipTilde = 1; break; case 'i': if (--argc > 0) strcpy(Dirname, *++argv); else { PrintUsage(); printf("*** input directory expected as next argument after -i.\n"); exit(1); } break; case 'o': if (--argc > 0) strcpy(OutFilename, *++argv); else { PrintUsage(); printf("*** output filename expected as next argument after -o.\n"); exit(1); } break; case 'q': quiet = 1; case 'f': forceit = 1; break; case 'r': ragged = ragged ^ 1; break; case 't': terminalsized = terminalsized ^ 1; break; case 'v': verbose = 1; break; default: PrintUsage(); printf("*** Unknown option '%s'.\n", arg); exit(1); break; } } else { PrintUsage(); exit(1); } } /* Do a stat to see if Dirname exists and is a directory. */ if (stat(Dirname, &statbuf) < 0) { printf("*** Could not stat input directory \"%s\".\n", Dirname); exit(1); } if ((statbuf.st_mode & S_IFDIR) == 0) { printf("*** Input directory \"%s\" is not a directory.\n", Dirname); exit(1); } if (CheckDuplicateDescriptions) SortBy = 'd'; if (!SortBy) { if (forceit) SortBy = 'd'; if (!quiet) printf("Sorting by [D]escription.\n"); } if (!SortBy) { printf("Sort by [N]umber or [D]escription: "); c = getch(); printf("%c\n", c); if (c == 'N' || c == 'n') SortBy = 'n'; else if (c == 'D' || c == 'd') SortBy = 'd'; else { printf("Nothing done.\n"); exit(0); } } farcoreleftStart = farcoreleft(); nLines = 0; maxLines = numlines; Lines = farmalloc(maxLines * sizeof(char *)); if (!Lines) { printf("Out of memory after %d parts\n", nLines); printf("Memory available at beginning: %ld kBytes\n", (farcoreleftStart + 1023) / 1024); exit(1); } strcpy(Filename, Dirname); strcat(Filename, "\\"); pathlen = strlen(Filename); strcat(Filename, "*.*"); for (done = findfirst(Filename, &ffb, 0); !done; done = findnext(&ffb)) { if (verbose) { printf("Processing file: \"%s\"\n", ffb.ff_name); } strcpy(Filename + pathlen, ffb.ff_name); fp = fopen(Filename, "rt"); if (!fp) { if (!quiet) printf("Cannot open \"%s\"", ffb.ff_name); PressAnyKey(); continue; } fgets(Line, sizeof(Line), fp); fclose(fp); s = Line + strlen(Line) - 1; while (s >= Line && (*s == '\n' || *s == '\r' || *s == '\t' || *s == ' ')) *s-- = '\0'; /* clear newline and trailing tabs and spaces */ s = Line; while (*s == '\t' || *s == ' ') *s++; if (*s++ != '0') { if (!quiet) printf("Line type 0 expected in \"%s\", skipping...", ffb.ff_name); PressAnyKey(); continue; } while (*s == '\t' || *s == ' ') *s++; Description = s; if (SkipTilde && Description[0] == '~') continue; if (SkipMovedto && strncmp(Description, "~Moved to", 9) == 0) continue; Len = strlen(Description); if (Len == 0) { if (!quiet) printf("Empty description in \"%s\"", ffb.ff_name); PressAnyKey(); } if (Len > 64) { /* Original makelist truncates to 64 characters. */ if (!quiet) { printf("Description in \"%s\" will be truncated to 64 characters:\n", ffb.ff_name); printf("Before: \"%s\"\n", Description); printf("After: \"%-64.64s\"\n", Description); } PressAnyKey(); } if (namelen == 12) FormattedLine = farmalloc(79); else FormattedLine = farmalloc(128); if (!FormattedLine) { printf("Out of memory after %d parts\n", nLines); printf("Memory available at beginning: %ld kBytes\n", (farcoreleftStart + 1023) / 1024); exit(1); } if (namelen > 12) strcpy(shortfilename, ffb.ff_name); else { GetShortPathName(Filename, shortfilepath, MAX_PATH); s = basename(shortfilepath); strcpy(shortfilename, s); if (s != NULL) free(s); if (strcmp(ffb.ff_name, shortfilename)) { if (!quiet) printf("Filename \"%s\" will be shortened to %s\n", ffb.ff_name, shortfilename); PressAnyKey(); } } Len = strlen(shortfilename); if (Len > namelen) { if (!quiet) printf("Filename \"%s\" will be truncated to %d characters.\n", shortfilename, namelen); PressAnyKey(); } shortfilename[namelen] = 0; if (namelen == 12) sprintf(FormattedLine, "%-12s %-64.64s", shortfilename, Description); else if (ragged && terminalsized) { if (Len > 14) /* Squeeze every last char out of the 80. */ sprintf(FormattedLine, "%s %-64.64s", shortfilename, Description); else sprintf(FormattedLine, "%-14s %-64.64s", shortfilename, Description); } else if (ragged) { if (Len > 12) sprintf(FormattedLine, "%s %-64.64s", shortfilename, Description); else sprintf(FormattedLine, "%-12s %-64.64s", shortfilename, Description); } else sprintf(FormattedLine, "%-25s %-64.64s", shortfilename, Description); if (terminalsized) { if (namelen == 12) FormattedLine[78] = 0; else FormattedLine[80] = 0; } if (verbose) { printf("%d:\t%s\n", nLines, FormattedLine); } if (nLines >= maxLines) { /* Let's have another 1000 pointers */ maxLines += numlines; Lines = farrealloc(Lines, maxLines * sizeof(char *)); if (!Lines) { printf("Out of memory after %d parts\n", nLines); printf("Memory available at beginning: %ld kBytes\n", (farcoreleftStart + 1023) / 1024); exit(1); } } Lines[nLines++] = FormattedLine; if (nLines % 100 == 0) printf("%d parts so far...\r", nLines); } printf("%d parts found in %s.\n", nLines, Dirname); if (nLines == 0) { printf("No parts found, nothing done.\n"); exit(0); } printf("Sorting...\n"); qsort(Lines, nLines, sizeof(Lines[0]), (SortBy == 'n') ? CmpNumber : CmpDescription); if (CheckDuplicateDescriptions) { printf("Checking for duplicate descriptions. \"%s\" unchanged.\n", OutFilename); for (i = 0; i < nLines; i += j) { for (j = 1; i + j < nLines; j++) { if (stricmp(Lines[i] + (namelen+2), Lines[i + j] + (namelen+2)) != 0) break; /* OK to break, lines are sorted */ if (j == 1) /* First duplicate */ printf("%s\n", Lines[i]); printf("%s\n", Lines[i + j]); } if (j > 1) /* Duplicates found */ PressAnyKey(); } } else { fp = fopen(OutFilename, "wt"); if (!fp) { printf("Cannot open \"%s\" for writing.\n", OutFilename); exit(1); } for (i = 0; i < nLines; i++) fprintf(fp, "%s\n", Lines[i]); FileSize = ftell(fp); fclose(fp); printf("\"%s\" successfully written, %ld kBytes\n", OutFilename, (FileSize + 1023) / 1024); } if (numlines > 1000) /* if not Borland DOS compiler then skip the mem msg. */ { return (0); } farcoreleftEnd = farcoreleft(); printf("Maximum memory usage: %ld kBytes of %ld kBytes available\n", (farcoreleftStart - farcoreleftEnd + 1023) / 1024, (farcoreleftStart + 1023) / 1024); return (0); }
int main( void ) { dword FarFreeMemoryAtStart=(unsigned long)farcoreleft(); printf("\n\n Reliable file system" "\n by" "\n Dvorka" "\n" "\n Compiled at %s, %s\n", __DATE__, __TIME__ ); printf( " Starting with far heap: %luB \n", FarFreeMemoryAtStart ); randomize(); InitializeSimulation( INIT_WRITE_TABLE, INIT_CREATE_DEVICES ); // create everything new FSCreatMasterBoot( 0x80, 512, 1 ); FSCreatMasterBoot( 0x81, 512, 1 ); FSCreatMasterBoot( 0x82, 512, 1 ); // data stripe FSCreatPartition( 0x80, 1, 0, 500, ACTIVE_PARTITION ); // parity stripe FSCreatPartition( 0x80, 2, 501, 1023, NONACTIVE_PARTITION ); // data stripe FSCreatPartition( 0x81, 1, 0, 500, NONACTIVE_PARTITION ); // swap party FSCreatPartition( 0x81, 2, 501, 1023, NONACTIVE_PARTITION ); // data stripe FSCreatPartition( 0x82, 1, 0, 500, NONACTIVE_PARTITION ); // data stripe FSCreatPartition( 0x82, 2, 501, 1001, NONACTIVE_PARTITION ); // format parties FSFormat( 0x80, 1, RFS_DATA ); FSFormat( 0x80, 2, RFS_DATA ); FSFormat( 0x81, 1, RFS_DATA ); FSFormat( 0x81, 2, RFS_SWAP ); FSFormat( 0x82, 1, RFS_DATA ); FSFormat( 0x82, 2, RFS_DATA ); FSOpenFileSystem( SWAP_ON, CACHE_ON, 10000lu ); // nothing to do... FSShutdownFileSystem(); printf("\n\n Memory statistic:"); if( FarFreeMemoryAtStart!=((unsigned long) farcoreleft())) { printf("\n Deallocation ERROR:"); Beep(); Beep(); Beep(); } else Beep(); printf( "\n Far free at start: %lu" "\n and now : %lu" "\n\n" , FarFreeMemoryAtStart, ((unsigned long) farcoreleft()) ); printf("\n Bye! \n\n"); return 0; }
void MemInfo(char forced) { #ifndef TEXTONLY char str[30]; unsigned long ldsp; int y=endvtoolbar(); int color; long value; if(forced && meminfovisible) { if(arachne.framescount) { p->activeframe=0; redrawHTML(REDRAW_NO_MESSAGE,REDRAW_CREATE_VIRTUAL); } else redrawHTML(REDRAW_WITH_MESSAGE,REDRAW_VIRTUAL); meminfovisible=0; return; } if((x_maxx()<640 || arachne.GUIstyle || fullscreen || customerscreen || fixedfont) /*fixedfont=printing hack*/ && !forced) return; if(arachne.GUIstyle) meminfovisible=1; mouseoff(); y+=2; Box3D(x_maxx()-150,y,x_maxx()-1,x_maxy()-17); y+=1; htmlfont(0,NORMAL); if(forced && lastinfo && endvtoolbar()>=x_maxy()-14*(fonty(0,NORMAL)-1)) goto moreinfo; #ifndef POSIX //DOS memory value=farcoreleft();//>>10; //!!glennmcc Oct 09, 2004 don't round off to KB sprintf(str,"%4lu",value); if(value<50000l || memory_model==0) { color=2; strcat(str,"[!!!]"); } else if(memory_model==2) { color=3; strcat(str,"[+]"); } else { color=0; strcat(str,"[?]"); } MemInfoLine("Dos mem",str,color,&y);//!!glennmcc Oct 09, 2004 don't round off to KB //XMS used sprintf(str,"%5lu",mem_all_xmem()); MemInfoLine("Used XMS (KB)",str,0,&y); #endif//posix //XSWAP free ldsp=ie_free()>>10; sprintf(str,"%4ld",ldsp); if(ldsp<500) { color=2; strcat(str,"[!!!]"); } else color=0; MemInfoLine("Free xSwap (KB)",str,color,&y); //XSWAP used sprintf(str,"%4ld",ie_used()>>10); MemInfoLine("Used xSwap (KB)",str,0,&y); #ifndef POSIX //disk space //!!glennmcc: Nov 25, 2005 -- check space on the cache drive //and the current drive .... display both when not the same drive //when cache is on local drive, display only one #ifndef NOKEY { ldsp=lastdiskspace(configvariable(&ARACHNEcfg,"CachePath",NULL))>>20; //local & cache /**/ if(ldsp==(localdiskspace()>>20)) sprintf(str,"%4lu",ldsp); else sprintf(str,"%4lu %4lu",localdiskspace()>>20,ldsp); /**/ //temp & cache /* if(ldsp==(lastdiskspace(getenv("TEMP"))>>20)) sprintf(str,"cache_%4lu",ldsp); else sprintf(str,"temp_%4lu cache_%4lu",lastdiskspace(getenv("TEMP"))>>20,ldsp); */ }
//. Mix only the paletes on screen (visible) void MixVisiblePaletes(char writepal) { int pocet=0,i,celkpocet=0; int secidx[MAXPALMIX+1]; XSWAP atomadr[MAXPALMIX+1]; struct picinfo *dataptr; struct picinfo *obrazky; struct Url url; int maxpocet;//,frameID; XSWAP dummy1; unsigned dummy2; unsigned currentHTMLatom=p->firstHTMLatom,nextHTMLatom; struct HTMLframe *frame; struct HTMLrecord *imgatomptr; struct HTTPrecord HTTPdoc; // struct TMPframedata *htmldata; #ifdef POSIX maxpocet=MAXPALMIX; #else maxpocet=(int)((farcoreleft()-2000l)/(5500+sizeof(struct picinfo))); if(maxpocet>MAXPALMIX) maxpocet=MAXPALMIX; else if(maxpocet<1) maxpocet=1; #endif obrazky=farmalloc(sizeof(struct picinfo)*maxpocet); if(!obrazky)memerr(); // while(HTMLdoc.cur<HTMLdoc.len) while(currentHTMLatom!=IE_NULL) { kbhit(); imgatomptr=(struct HTMLrecord *)ie_getswap(currentHTMLatom); if(!imgatomptr) MALLOCERR(); nextHTMLatom=imgatomptr->next; frame=&(p->htmlframe[imgatomptr->frameID]); if( (imgatomptr->type==IMG || imgatomptr->type==TD_BACKGROUND) && (imgatomptr->y>=frame->posY || imgatomptr->yy>=frame->posY) && (imgatomptr->y<frame->posY+frame->scroll.ysize || imgatomptr->yy<frame->posY+frame->scroll.ysize) && (imgatomptr->x>=frame->posX || imgatomptr->xx>=frame->posX) && (imgatomptr->x<frame->posX+frame->scroll.xsize || imgatomptr->xx<frame->posX+frame->scroll.xsize) || imgatomptr->type==BACKGROUND) { // idx[celkpocet]=HTMLdoc.cur; atomadr[celkpocet]=currentHTMLatom; dataptr=(struct picinfo *)ie_getswap(imgatomptr->ptr); if(dataptr) { dataptr->palismap=0; swapmod=1; if(celkpocet<MAXPALMIX) { memcpy(&obrazky[pocet],dataptr,sizeof(struct picinfo)); AnalyseURL(obrazky[pocet].URL,&url,IGNORE_PARENT_FRAME); if(SearchInCache(&url,&HTTPdoc,&dummy1,&dummy2)) { i=0; while(i<pocet) { if(!strcmp(obrazky[i].filename,HTTPdoc.locname)) { secidx[celkpocet++]=i; goto nextobrazek; } i++; } //pocitaji se jenom GIFy a bitmapy: // tr.: only GIFs and bitmaps are counted/calculated if(HTTPdoc.locname[0] && (strstr(HTTPdoc.locname,".GIF") || strstr(HTTPdoc.locname,".BMP"))) { strcpy(obrazky[pocet].filename,HTTPdoc.locname); secidx[celkpocet++]=pocet; //u prvniho obrazku 0, u druheho 1; // tr.: at the first picture 0, at the second 1 pocet++; } if(pocet==maxpocet) goto allobrazky; } } else goto allobrazky; }//endif nasel sem neco (tr.: endif I found something) else MALLOCERR(); } nextobrazek: // HTMLdoc.cur++; currentHTMLatom=nextHTMLatom; } allobrazky: i=0; if(celkpocet>0) { if(!MixPal(obrazky,pocet,writepal)) //zkusim smichat palety... // tr.: I try to mix the palette goto ven; while(i<celkpocet) { //zrychlena verze (tr.: accelerated version) imgatomptr=(struct HTMLrecord *)ie_getswap(atomadr[i]); if(imgatomptr && (imgatomptr->type==IMG || imgatomptr->type==BACKGROUND || imgatomptr->type==TD_BACKGROUND)) { dataptr=(struct picinfo *)ie_getswap(imgatomptr->ptr); if(dataptr) { int resize_x=dataptr->resize_x; int resize_y=dataptr->resize_y; memcpy(dataptr,&obrazky[secidx[i]],sizeof(struct picinfo)); dataptr->resize_x=resize_x; dataptr->resize_y=resize_y; swapmod=1; } else MALLOCERR(); } else MALLOCERR(); i++; } } ven: if(obrazky) farfree(obrazky); }
int main( void ) { dword FarFreeMemoryAtStart=(unsigned long)farcoreleft(); printf("\n\n Reliable file system" "\n by" "\n Jarda & Dvorka" "\n" "\n Compiled at %s, %s\n", __DATE__, __TIME__ ); printf( " Starting with far heap: %luB \n", FarFreeMemoryAtStart ); randomize(); //- work with file system - #ifdef CREATE_EVERYTHING_NEW InitializeSimulation( TRUE, TRUE ); // create everything new FSCreatMasterBoot( 0x80, 512, 1 ); FSCreatMasterBoot( 0x81, 512, 1 ); FSCreatMasterBoot( 0x82, 512, 1 ); // data stripe FSCreatPartition( 0x80, 1, 0, 500, ACTIVE_PARTITION ); // parity stripe FSCreatPartition( 0x80, 2, 501, 1023, NONACTIVE_PARTITION ); // data stripe FSCreatPartition( 0x81, 1, 0, 500, ACTIVE_PARTITION ); // swap party FSCreatPartition( 0x81, 2, 501, 1023, NONACTIVE_PARTITION ); // data stripe FSCreatPartition( 0x82, 1, 0, 500, ACTIVE_PARTITION ); // swap party FSCreatPartition( 0x82, 2, 501, 1023, NONACTIVE_PARTITION ); // format parties FSFormat( 0x80, 1, RFS_DATA ); FSFormat( 0x80, 2, RFS_DATA ); FSFormat( 0x81, 1, RFS_DATA ); FSFormat( 0x81, 2, RFS_SWAP ); FSFormat( 0x82, 1, RFS_DATA ); FSFormat( 0x82, 2, RFS_SWAP ); #else InitializeSimulation(); // only init handles,... #endif // init file system ( inside init of cache ) FSOpenFileSystem( SWAP_ON, CACHE_ON, 10000lu ); #ifdef CACHE_TEST; word PackageID=0, GetNumber=0, i; dword Logical, Free; void far *Buffer=farmalloc(10*512); if( !Buffer ) exit(0); // allocates && creates package ( 0x81 or 1 - it has same effect ) CacheManAllocateSector( 0x81, 1, 0, 1, Logical, GetNumber, PackageID, FPACK_CREAT ); word j; word Number; // PackageID set in previous function for( i=1; i<=5; i++ ) { // allocate allocates < logical, logical+6 > CacheManAllocateSector( 1, 1, 0lu, 7, Logical, GetNumber, PackageID, FPACK_ADD ); printf("\n Get number: %u", GetNumber ); // init buffer for save for( j=0; j<10*512; j++ ) ((byte far * )Buffer)[j]=0xCC; if( random(5) ) // probably add CacheManSaveSector( 1, 1, Logical, 7, PackageID, FPACK_ADD, Buffer ); else CacheManSaveSector( 1, 1, Logical, 7, PackageID, FPACK_CREAT, Buffer ); // load what's written from cache ( something ) // Number=(word)random(7) + 1u; Number=7; CacheManLoadSector( 1, 1, Logical, Number, PackageID, FPACK_ADD, Buffer ); if( !random(10) ) // probably not commit { if( random(2) ) CacheManCommitPackage( PackageID, FPACK_NOTHING ); // commit else { CacheManCommitPackage( PackageID, FPACK_DELETE ); // commit && del pack // create new PackID because in alloc and save used! CacheManAllocateSector( 1, 1, 0lu, 7, Logical, GetNumber, PackageID, FPACK_CREAT ); printf("\n Get number: %u", GetNumber ); } } // print free space on device GetPartyFreeSpace( 0x81, 1, Free ); GetPartyFreeSpace( 0x81, 2, Free ); printf("\n\n ----->"); } farfree(Buffer); // UndoAlfLog( 0x81, 1, "TEST.ALF" ); // RecoverUsingCml( "TEST.CML" ); // RollbackOkaLog( 1, 1, "11TEST.OKA" ); // RecoverParty( 1, 1 ); #endif #ifdef CACHE_EXAMPLE; int Handle; word PackageID, GetNumber=0, i, j, bytes; dword Previous=0, Logical1, Logical2, Logical; #define BUFFER_SIZE 512 void far *Buffer=farmalloc(BUFFER_SIZE); if( !Buffer ) { printf("All1 Error..");exit(0); } void far *BufferOut=farmalloc(BUFFER_SIZE); if( !BufferOut ) { printf("All2 Error..");exit(0); } // now read some nice data to buffer if ((Handle = open("input.txt", O_CREAT | O_RDWR | O_BINARY, S_IWRITE | S_IREAD )) == -1) { printf("Error.."); return ERR_FS_FATAL_ERROR; } if( _dos_read( Handle, Buffer, BUFFER_SIZE, &bytes) != 0 ) { printf("Error.."); return ERR_FS_FATAL_ERROR; } close(Handle); // --- begin work ------------------------------------------------ //* for(i=0; i<512; i++ ) ((byte far *)Buffer)[i]=0xAA; CacheManAllocateSector( 1, 1, 0, 1, Logical1, GetNumber, PackageID, FPACK_CREAT ); CacheManSaveSector( 1, 1, Logical1, 1u, PackageID, FPACK_ADD, Buffer ); for(i=0; i<512; i++ ) ((byte far *)Buffer)[i]=0xBB; CacheManAllocateSector( 1, 1, 0, 1, Logical2, GetNumber, PackageID, FPACK_ADD ); CacheManSaveSector( 1, 1, Logical2, 1u, PackageID, FPACK_ADD, Buffer ); //*/ CacheManCompleteCommit( FPACK_DELETE ); //* for(i=0; i<512; i++ ) ((byte far *)BufferOut)[i]=0xEE; CacheManLoadSector( 1, 1, Logical1, 1u, PackageID, FPACK_CREAT, BufferOut ); if ((Handle = open("AA", O_CREAT | O_RDWR | O_BINARY, S_IWRITE | S_IREAD )) == -1) { printf("Error.."); return ERR_FS_FATAL_ERROR; } if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 ) { printf("Error.."); return ERR_FS_FATAL_ERROR; } close(Handle); // --- for(i=0; i<512; i++ ) ((byte far *)BufferOut)[i]=0xEE; CacheManLoadSector( 1, 1, Logical2, 1u, PackageID, FPACK_ADD, BufferOut ); if ((Handle = open("BB", O_CREAT | O_RDWR | O_BINARY, S_IWRITE | S_IREAD )) == -1) { printf("Error.."); return ERR_FS_FATAL_ERROR; } if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 ) { printf("Error.."); return ERR_FS_FATAL_ERROR; } close(Handle); //*/ // --- end work ------------------------------------------------ // save buffer content ------------------------------------------------ if ((Handle = open("output2.txt", O_CREAT | O_RDWR | O_BINARY, S_IWRITE | S_IREAD )) == -1) { printf("Error.."); return ERR_FS_FATAL_ERROR; } if( _dos_write( Handle, BufferOut, BUFFER_SIZE, &bytes) != 0 ) { printf("Error.."); return ERR_FS_FATAL_ERROR; } close(Handle); farfree(Buffer); farfree(BufferOut); #endif #ifdef STRIP_EXAMPLE #define BUFFER_SIZE 512 #define SECTOR 31 byte far *Buffer=(byte far *)farmalloc(BUFFER_SIZE); if( !Buffer ) { printf("All1 Error..");exit(0); } printf("\n\n\n Test: "); ReadLogicalSector( 1, SECTOR, Buffer, 1 ); Buffer[0]=0xAB; CLASSICWriteLogicalSector( 1, SECTOR, Buffer, 1 ); ReadLogicalSector( 1, SECTOR, Buffer, 1 ); ReadLogicalSector( 1, SECTOR, Buffer, 1 ); farfree(Buffer); #endif FSShutdownFileSystem(); // contains complete commit //------------------------- printf("\n\n Memory statistic:"); if( FarFreeMemoryAtStart!=((unsigned long) farcoreleft())) { printf("\n Deallocation ERROR:"); Beep(); Beep(); Beep(); } else Beep(); printf( "\n Far free at start: %lu" "\n and now : %lu" "\n\n" , FarFreeMemoryAtStart, ((unsigned long) farcoreleft()) ); printf("\n Bye! \n\n"); return 0; }
/* -------------------------------------------------------------------- */ void fkey(void) { char key; int oldIO, i; label string; unsigned space; key = (char) getch(); while (kbhit()) /* flush keyboard buffer */ getch(); if (strcmpi(cfg.f6pass, "f6disabled") != SAMESTRING) if (ConLock == TRUE && key == K_A_L && strcmpi(cfg.f6pass, "disabled") != SAMESTRING) { ConLock = FALSE; oldIO = whichIO; whichIO = CONSOLE; onConsole = TRUE; /* update25(); */ do_idle(0); string[0] = 0; getNormStr("System Password", string, NAMESIZE, NO_ECHO); if (strcmpi(string, cfg.f6pass) != SAMESTRING) ConLock = TRUE; whichIO = (BOOL) oldIO; onConsole = (BOOL) (whichIO == CONSOLE); /* update25(); */ do_idle(0); givePrompt(); return; } if (ConLock && !gl_user.sysop && strcmpi(cfg.f6pass, "f6disabled") != SAMESTRING) return; switch (key) { case K_F1: drop_dtr(); detectflag = FALSE; break; case K_F2: if (parm.door) ExitToMsdos = 1; else Initport(); detectflag = FALSE; break; case K_F3: sysReq = (BOOL) (!sysReq); break; case K_F4: anyEcho = (BOOL) (!anyEcho); break; case K_F5: if (whichIO == CONSOLE) whichIO = MODEM; else whichIO = CONSOLE; onConsole = (BOOL) (whichIO == CONSOLE); break; case K_S_F6: if (!ConLock) gl_user.aide = (BOOL) (!gl_user.aide); break; case K_A_F6: if (!ConLock) gl_user.sysop = (BOOL) (!gl_user.sysop); break; case K_F6: if (gl_user.sysop || !ConLock) sysopkey = TRUE; break; case K_F7: cfg.noBells = !cfg.noBells; break; case K_A_C: case K_F8: chatkey = !chatkey; /* will go into chat from main() */ break; case K_F9: cfg.noChat = !cfg.noChat; chatReq = FALSE; break; case K_F10: help(); break; case K_A_B: backout = !backout; break; case K_A_D: debug = !debug; break; case K_A_E: eventkey = TRUE; break; case K_A_L: if (cfg.f6pass[0] && strcmpi(cfg.f6pass, "f6disabled") != SAMESTRING) ConLock = (BOOL) (!ConLock); break; case K_A_M: #ifndef ATARI_ST cPrintf("Free heap %lXh (%lu.)\n", farcoreleft(), farcoreleft()); space = _stklen - ((unsigned) 0xffff - _SP); cPrintf("Free stack %Xh (%u.)\n", space, space); #endif break; case K_A_P: if (printing) { printing = FALSE; fclose(printfile); } else { printfile = fopen(cfg.printer, "a"); if (printfile) { printing = TRUE; } else { printing = FALSE; } } break; case K_A_T: gl_user.twit = (BOOL) (!gl_user.twit); break; case K_A_X: if (dowhat == MAINMENU || dowhat == SYSOPMENU) { if (loggedIn) { i = getYesNo("Exit to MS-DOS", 0); } else { doCR(); doCR(); mPrintf("Exit to MS-DOS"); doCR(); i = TRUE; } if (!i) { if (dowhat == MAINMENU) { givePrompt(); } else { doCR(); mPrintf("Privileged function: "); } break; } ExitToMsdos = TRUE; } break; case K_PgDn: logBuf.credits -= 10; break; case K_PgUp: logBuf.credits += 10; break; case K_Lft: ungetch('-'); getkey = 1; break; case K_Rgt: ungetch('='); getkey = 1; break; case K_Up: ungetch(']'); getkey = 1; break; case K_Dwn: ungetch('['); getkey = 1; break; default: break; } /* update25(); */ do_idle(0); }
void PushRect(rect * R, int *err) { /* We don't really use ERR, but its for compatibility */ savelist *lastsave = savetail; long savesize = ImageSize(R); /* And we don't give a shit about size. */ savetail = farcalloc(sizeof(savelist), 1L); savetail->prev = lastsave; savetail->im = NULL; if (memok(savesize)) { safe_alloc = 1; savetail->im = (image far *) farcalloc(savesize, 1L); } savetail->R = farmalloc(sizeof(rect)); *(savetail->R) = *R; if (!savetail->im) { char tbuf[128]; char tbuf2[128]; FILE *fd; image *tmp; char *pathname = getenv("TMP"); unsigned char drive; struct dfree dtable; long dfree; #ifdef AXTDEBUG printf("\nLook out, I'm pushing to disk."); #endif /* Find out if there is enough space left on the thing */ if (pathname && access(pathname,0)) pathname = NULL; if (pathname && pathname[1] == ':') drive = toupper(pathname[0]) - 'A' + 1; else drive = 0; getdfree(drive, &dtable); if (dtable.df_sclus == 0xffff && drive) { drive = 0; getdfree(drive, &dtable); pathname = NULL; /* and so this doesn't happen again */ putenv("TMP="); } dfree = (long) dtable.df_avail * (long) dtable.df_bsec * (long) dtable.df_sclus; if (dfree > savesize) { rect R1; sprintf(tbuf, "%lx.dat", savetail); TempFileName(tbuf2, tbuf); fd = fopen(tbuf2, "wb"); if (fd) { int i; unsigned long cl = farcoreleft(); int lines; long n; if (cl > 2048L) cl -= 2048L; /* Safety margin */ R1 = *R; R1.Ymax = R1.Ymin; i = 1; while (i < R->Ymax) { R1.Ymax = R1.Ymin + i; n = ImageSize(&R1); if (n < cl) { savesize = n; lines = i; } i *= 2; } /* * Let's see how many rows at a time we can * save */ savetail->lines = lines; savetail->blocks = (R->Ymax - R->Ymin + 1) / lines; tmp = farmalloc(savesize); //setvbuf(fd, (char *) tmp, _IOFBF, (size_t) savesize); R1 = *R; R1.Ymax = R1.Ymin + lines - 1; for (i = R->Ymin; i <= R->Ymax; i += lines) { R1.Ymax = min(R1.Ymax, R->Ymax); ReadImage(&R1, tmp); fwrite(tmp, 1, (int) ImageSize(&R1), fd); OffsetRect(&R1, 0, lines); } fclose(fd); farfree(tmp); tmp = NULL; savetail->filename = strdup(tbuf2); *err = 0; return; } } sprintf(tbuf, "Can't allocate %ld bytes", savesize); ErrorBox(tbuf); *err = 1; farfree(savetail->R); savetail->R = NULL; farfree(savetail); savetail = NULL; savetail = lastsave; } else { ReadImage(savetail->R, savetail->im); *err = 0; } }
T_word32 FreeMemory(T_void) { return farcoreleft() ; }