src/file/SDL_rwops.c
author Sam Lantinga <slouken@libsdl.org>
Wed, 17 May 2006 08:18:28 +0000
branchSDL-1.3
changeset 1659 14717b52abc0
parent 1465 8dfa9a6d69a5
child 1662 782fd950bd46
child 1895 c121d94672cb
child 3975 e85e65aec22f
permissions -rw-r--r--
Merge trunk-1.3-3
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997-2006 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 /* This file provides a general interface for SDL to read and write
    25    data sources.  It can easily be extended to files, memory, etc.
    26 */
    27 
    28 #include "SDL_endian.h"
    29 #include "SDL_rwops.h"
    30 
    31 
    32 #if defined(__WIN32__)
    33 
    34 /* Functions to read/write Win32 API file pointers */
    35 /* Will not use it on WinCE because stdio is buffered, it means
    36    faster, and all stdio functions anyway are embedded in coredll.dll - 
    37    the main wince dll*/
    38 
    39 #define WINDOWS_LEAN_AND_MEAN
    40 #include <windows.h>
    41 
    42 #ifndef INVALID_SET_FILE_POINTER
    43 #define INVALID_SET_FILE_POINTER 0xFFFFFFFF
    44 #endif
    45 
    46 static int SDLCALL win32_file_open(SDL_RWops *context, const char *filename, const char *mode)
    47 {
    48 #ifndef _WIN32_WCE
    49 	UINT	old_error_mode;
    50 #endif
    51 	HANDLE	h;
    52 	DWORD	r_right, w_right;
    53 	DWORD	must_exist, truncate;
    54 	int		a_mode;
    55 
    56 	if (!context)
    57 		return -1;
    58 		
    59 	context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* mark this as unusable */
    60 
    61 	/* "r" = reading, file must exist */
    62 	/* "w" = writing, truncate existing, file may not exist */
    63 	/* "r+"= reading or writing, file must exist            */
    64 	/* "a" = writing, append file may not exist             */
    65 	/* "a+"= append + read, file may not exist              */
    66 	/* "w+" = read, write, truncate. file may not exist    */
    67 	
    68 	must_exist = ( SDL_strchr(mode,'r') != NULL ) ? OPEN_EXISTING : 0;
    69 	truncate   = ( SDL_strchr(mode,'w') != NULL ) ? CREATE_ALWAYS : 0;
    70 	r_right    = ( SDL_strchr(mode,'+') != NULL || must_exist ) ? GENERIC_READ : 0;
    71 	a_mode     = ( SDL_strchr(mode,'a') != NULL ) ? OPEN_ALWAYS : 0;
    72 	w_right    = ( a_mode || SDL_strchr(mode,'+') || truncate ) ? GENERIC_WRITE : 0;
    73 
    74 	if (!r_right && !w_right) /* inconsistent mode */
    75 		return -1; /* failed (invalid call)*/
    76 
    77 #ifdef _WIN32_WCE
    78 	{
    79 		size_t size = SDL_strlen(filename)+1;
    80 		wchar_t *filenameW = SDL_stack_alloc(wchar_t, size);
    81 
    82 		if ( MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, size) == 0 ) {
    83 			SDL_SetError("Unable to convert filename to Unicode");
    84 			SDL_stack_free(filenameW);
    85 			return -1;
    86 		}
    87 		h = CreateFile(filenameW, (w_right|r_right), (w_right)? 0 : FILE_SHARE_READ, 
    88 					   NULL, (must_exist|truncate|a_mode), FILE_ATTRIBUTE_NORMAL,NULL);
    89 		SDL_stack_free(filenameW);
    90 	}
    91 #else
    92 	/* Do not open a dialog box if failure */
    93 	old_error_mode = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);
    94 
    95 	h = CreateFile(filename, (w_right|r_right), (w_right)? 0 : FILE_SHARE_READ, 
    96 		           NULL, (must_exist|truncate|a_mode), FILE_ATTRIBUTE_NORMAL,NULL);
    97 
    98 	/* restore old behaviour */
    99 	SetErrorMode(old_error_mode);
   100 #endif /* _WIN32_WCE */
   101 
   102 	if (h==INVALID_HANDLE_VALUE) {
   103 		SDL_SetError("Couldn't open %s",filename);
   104 		return -2; /* failed (CreateFile) */
   105 	}
   106 	context->hidden.win32io.h = h;
   107 	context->hidden.win32io.append = a_mode;
   108 	
   109 	return 0; /* ok */
   110 }
   111 static int SDLCALL win32_file_seek(SDL_RWops *context, int offset, int whence)
   112 {
   113 	DWORD win32whence;
   114 	int   file_pos;
   115 	
   116 	if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE) {
   117 		SDL_SetError("win32_file_seek: invalid context/file not opened");
   118 		return -1;
   119 	}
   120 	
   121 	switch (whence) {
   122 		case RW_SEEK_SET:		
   123 			win32whence = FILE_BEGIN; break;
   124 		case RW_SEEK_CUR:
   125 			win32whence = FILE_CURRENT; break;
   126 		case RW_SEEK_END:
   127 			win32whence = FILE_END; break;
   128 		default:
   129 			SDL_SetError("win32_file_seek: Unknown value for 'whence'");			
   130 			return -1;
   131 	}
   132 	
   133 	file_pos = SetFilePointer(context->hidden.win32io.h,offset,NULL,win32whence);
   134 
   135 	if ( file_pos != INVALID_SET_FILE_POINTER )
   136 		return file_pos; /* success */
   137 	
   138 	SDL_Error(SDL_EFSEEK);
   139 	return -1; /* error */
   140 }
   141 static int SDLCALL win32_file_read(SDL_RWops *context, void *ptr, int size, int maxnum)
   142 {
   143 	
   144 	int		total_bytes; 
   145 	DWORD	byte_read,nread;
   146 	
   147 	total_bytes = size*maxnum;
   148 	
   149 	if (!context || context->hidden.win32io.h == INVALID_HANDLE_VALUE || total_bytes<=0 || !size) 	
   150 		return 0;
   151 	
   152 	if (!ReadFile(context->hidden.win32io.h,ptr,total_bytes,&byte_read,NULL)) {
   153 		SDL_Error(SDL_EFREAD);
   154 		return 0;
   155 	}
   156 	nread = byte_read/size;
   157 	return nread;
   158 }
   159 static int SDLCALL win32_file_write(SDL_RWops *context, const void *ptr, int size, int num)
   160 {
   161 	
   162 	int		total_bytes; 
   163 	DWORD	byte_written,nwritten;
   164 	
   165 	total_bytes = size*num;
   166 
   167 	if (!context || context->hidden.win32io.h==INVALID_HANDLE_VALUE || total_bytes<=0 || !size) 	
   168 		return 0;
   169 
   170 	/* if in append mode, we must go to the EOF before write */
   171 	if (context->hidden.win32io.append) {
   172 		if ( SetFilePointer(context->hidden.win32io.h,0L,NULL,FILE_END) == INVALID_SET_FILE_POINTER ) {
   173 			SDL_Error(SDL_EFWRITE);
   174 			return 0;
   175 		}
   176 	}
   177 	
   178 	if (!WriteFile(context->hidden.win32io.h,ptr,total_bytes,&byte_written,NULL)) {
   179 		SDL_Error(SDL_EFWRITE);
   180 		return 0;
   181 	}
   182 	
   183 	nwritten = byte_written/size;
   184 	return nwritten;
   185 }
   186 static int SDLCALL win32_file_close(SDL_RWops *context)
   187 {
   188 	
   189 	if ( context ) {								
   190 		if (context->hidden.win32io.h != INVALID_HANDLE_VALUE) {
   191 			CloseHandle(context->hidden.win32io.h);
   192 			context->hidden.win32io.h = INVALID_HANDLE_VALUE; /* to be sure */
   193 		}
   194 		SDL_FreeRW(context);
   195 	}
   196 	return(0);
   197 }
   198 #endif /* __WIN32__ */
   199 
   200 #ifdef HAVE_STDIO_H
   201 
   202 /* Functions to read/write stdio file pointers */
   203 
   204 static int SDLCALL stdio_seek(SDL_RWops *context, int offset, int whence)
   205 {
   206 	if ( fseek(context->hidden.stdio.fp, offset, whence) == 0 ) {
   207 		return(ftell(context->hidden.stdio.fp));
   208 	} else {
   209 		SDL_Error(SDL_EFSEEK);
   210 		return(-1);
   211 	}
   212 }
   213 static int SDLCALL stdio_read(SDL_RWops *context, void *ptr, int size, int maxnum)
   214 {
   215 	size_t nread;
   216 
   217 	nread = fread(ptr, size, maxnum, context->hidden.stdio.fp); 
   218 	if ( nread == 0 && ferror(context->hidden.stdio.fp) ) {
   219 		SDL_Error(SDL_EFREAD);
   220 	}
   221 	return(nread);
   222 }
   223 static int SDLCALL stdio_write(SDL_RWops *context, const void *ptr, int size, int num)
   224 {
   225 	size_t nwrote;
   226 
   227 	nwrote = fwrite(ptr, size, num, context->hidden.stdio.fp);
   228 	if ( nwrote == 0 && ferror(context->hidden.stdio.fp) ) {
   229 		SDL_Error(SDL_EFWRITE);
   230 	}
   231 	return(nwrote);
   232 }
   233 static int SDLCALL stdio_close(SDL_RWops *context)
   234 {
   235 	if ( context ) {
   236 		if ( context->hidden.stdio.autoclose ) {
   237 			/* WARNING:  Check the return value here! */
   238 			fclose(context->hidden.stdio.fp);
   239 		}
   240 		SDL_FreeRW(context);
   241 	}
   242 	return(0);
   243 }
   244 #endif /* !HAVE_STDIO_H */
   245 
   246 /* Functions to read/write memory pointers */
   247 
   248 static int SDLCALL mem_seek(SDL_RWops *context, int offset, int whence)
   249 {
   250 	Uint8 *newpos;
   251 
   252 	switch (whence) {
   253 		case RW_SEEK_SET:
   254 			newpos = context->hidden.mem.base+offset;
   255 			break;
   256 		case RW_SEEK_CUR:
   257 			newpos = context->hidden.mem.here+offset;
   258 			break;
   259 		case RW_SEEK_END:
   260 			newpos = context->hidden.mem.stop+offset;
   261 			break;
   262 		default:
   263 			SDL_SetError("Unknown value for 'whence'");
   264 			return(-1);
   265 	}
   266 	if ( newpos < context->hidden.mem.base ) {
   267 		newpos = context->hidden.mem.base;
   268 	}
   269 	if ( newpos > context->hidden.mem.stop ) {
   270 		newpos = context->hidden.mem.stop;
   271 	}
   272 	context->hidden.mem.here = newpos;
   273 	return(context->hidden.mem.here-context->hidden.mem.base);
   274 }
   275 static int SDLCALL mem_read(SDL_RWops *context, void *ptr, int size, int maxnum)
   276 {
   277 	size_t total_bytes;
   278 	size_t mem_available;
   279 
   280 	total_bytes = (maxnum * size);
   281 	if ( (maxnum <= 0) || (size <= 0) || ((total_bytes / maxnum) != (size_t) size) ) {
   282 		return 0;
   283 	}
   284 
   285 	mem_available = (context->hidden.mem.stop - context->hidden.mem.here);
   286 	if (total_bytes > mem_available) {
   287 		total_bytes = mem_available;
   288 	}
   289 
   290 	SDL_memcpy(ptr, context->hidden.mem.here, total_bytes);
   291 	context->hidden.mem.here += total_bytes;
   292 
   293 	return (total_bytes / size);
   294 }
   295 static int SDLCALL mem_write(SDL_RWops *context, const void *ptr, int size, int num)
   296 {
   297 	if ( (context->hidden.mem.here + (num*size)) > context->hidden.mem.stop ) {
   298 		num = (context->hidden.mem.stop-context->hidden.mem.here)/size;
   299 	}
   300 	SDL_memcpy(context->hidden.mem.here, ptr, num*size);
   301 	context->hidden.mem.here += num*size;
   302 	return(num);
   303 }
   304 static int SDLCALL mem_writeconst(SDL_RWops *context, const void *ptr, int size, int num)
   305 {
   306 	SDL_SetError("Can't write to read-only memory");
   307 	return(-1);
   308 }
   309 static int SDLCALL mem_close(SDL_RWops *context)
   310 {
   311 	if ( context ) {
   312 		SDL_FreeRW(context);
   313 	}
   314 	return(0);
   315 }
   316 
   317 
   318 /* Functions to create SDL_RWops structures from various data sources */
   319 
   320 #ifdef __MACOS__
   321 /*
   322  * translate unix-style slash-separated filename to mac-style colon-separated
   323  * name; return malloced string
   324  */
   325 static char *unix_to_mac(const char *file)
   326 {
   327 	int flen = SDL_strlen(file);
   328 	char *path = SDL_malloc(flen + 2);
   329 	const char *src = file;
   330 	char *dst = path;
   331 	if(*src == '/') {
   332 		/* really depends on filesystem layout, hope for the best */
   333 		src++;
   334 	} else {
   335 		/* Check if this is a MacOS path to begin with */
   336 		if(*src != ':')
   337 			*dst++ = ':';   /* relative paths begin with ':' */
   338 	}
   339 	while(src < file + flen) {
   340 		const char *end = SDL_strchr(src, '/');
   341 		int len;
   342 		if(!end)
   343 			end = file + flen; /* last component */
   344 		len = end - src;
   345 		if(len == 0 || (len == 1 && src[0] == '.')) {
   346 			/* remove repeated slashes and . */
   347 		} else {
   348 			if(len == 2 && src[0] == '.' && src[1] == '.') {
   349 				/* replace .. with the empty string */
   350 			} else {
   351 				SDL_memcpy(dst, src, len);
   352 				dst += len;
   353 			}
   354 			if(end < file + flen)
   355 				*dst++ = ':';
   356 		}
   357 		src = end + 1;
   358 	}
   359 	*dst++ = '\0';
   360 	return path;
   361 }
   362 #endif /* __MACOS__ */
   363 
   364 SDL_RWops *SDL_RWFromFile(const char *file, const char *mode)
   365 {
   366 	SDL_RWops *rwops = NULL;
   367 #ifdef HAVE_STDIO_H
   368 	FILE *fp = NULL;
   369 #endif
   370 	if ( !file || !*file || !mode || !*mode ) {
   371 		SDL_SetError("SDL_RWFromFile(): No file or no mode specified");
   372 		return NULL;
   373 	}
   374 
   375 #if defined(__WIN32__)
   376 	rwops = SDL_AllocRW();
   377 	if (!rwops)
   378 		return NULL; /* SDL_SetError already setup by SDL_AllocRW() */
   379 	rwops->hidden.win32io.h = INVALID_HANDLE_VALUE;
   380 	if (win32_file_open(rwops,file,mode)) {
   381 		SDL_FreeRW(rwops);
   382 		return NULL;
   383 	}	
   384 	rwops->seek  = win32_file_seek;
   385 	rwops->read  = win32_file_read;
   386 	rwops->write = win32_file_write;
   387 	rwops->close = win32_file_close;
   388 
   389 #elif HAVE_STDIO_H
   390 
   391 #ifdef __MACOS__
   392 	{
   393 		char *mpath = unix_to_mac(file);
   394 		fp = fopen(mpath, mode);
   395 		SDL_free(mpath);
   396 	}
   397 #else
   398 	fp = fopen(file, mode);
   399 #endif
   400 	if ( fp == NULL ) {
   401 		SDL_SetError("Couldn't open %s", file);
   402 	} else {
   403 		rwops = SDL_RWFromFP(fp, 1);
   404 	}
   405 #else
   406 	SDL_SetError("SDL not compiled with stdio support");
   407 #endif /* !HAVE_STDIO_H */
   408 
   409 	return(rwops);
   410 }
   411 
   412 #ifdef HAVE_STDIO_H
   413 SDL_RWops *SDL_RWFromFP(FILE *fp, int autoclose)
   414 {
   415 	SDL_RWops *rwops = NULL;
   416 
   417 	rwops = SDL_AllocRW();
   418 	if ( rwops != NULL ) {
   419 		rwops->seek = stdio_seek;
   420 		rwops->read = stdio_read;
   421 		rwops->write = stdio_write;
   422 		rwops->close = stdio_close;
   423 		rwops->hidden.stdio.fp = fp;
   424 		rwops->hidden.stdio.autoclose = autoclose;
   425 	}
   426 	return(rwops);
   427 }
   428 #endif /* HAVE_STDIO_H */
   429 
   430 SDL_RWops *SDL_RWFromMem(void *mem, int size)
   431 {
   432 	SDL_RWops *rwops;
   433 
   434 	rwops = SDL_AllocRW();
   435 	if ( rwops != NULL ) {
   436 		rwops->seek = mem_seek;
   437 		rwops->read = mem_read;
   438 		rwops->write = mem_write;
   439 		rwops->close = mem_close;
   440 		rwops->hidden.mem.base = (Uint8 *)mem;
   441 		rwops->hidden.mem.here = rwops->hidden.mem.base;
   442 		rwops->hidden.mem.stop = rwops->hidden.mem.base+size;
   443 	}
   444 	return(rwops);
   445 }
   446 
   447 SDL_RWops *SDL_RWFromConstMem(const void *mem, int size)
   448 {
   449 	SDL_RWops *rwops;
   450 
   451 	rwops = SDL_AllocRW();
   452 	if ( rwops != NULL ) {
   453 		rwops->seek = mem_seek;
   454 		rwops->read = mem_read;
   455 		rwops->write = mem_writeconst;
   456 		rwops->close = mem_close;
   457 		rwops->hidden.mem.base = (Uint8 *)mem;
   458 		rwops->hidden.mem.here = rwops->hidden.mem.base;
   459 		rwops->hidden.mem.stop = rwops->hidden.mem.base+size;
   460 	}
   461 	return(rwops);
   462 }
   463 
   464 SDL_RWops *SDL_AllocRW(void)
   465 {
   466 	SDL_RWops *area;
   467 
   468 	area = (SDL_RWops *)SDL_malloc(sizeof *area);
   469 	if ( area == NULL ) {
   470 		SDL_OutOfMemory();
   471 	}
   472 	return(area);
   473 }
   474 
   475 void SDL_FreeRW(SDL_RWops *area)
   476 {
   477 	SDL_free(area);
   478 }
   479 
   480 /* Functions for dynamically reading and writing endian-specific values */
   481 
   482 Uint16 SDL_ReadLE16 (SDL_RWops *src)
   483 {
   484 	Uint16 value;
   485 
   486 	SDL_RWread(src, &value, (sizeof value), 1);
   487 	return(SDL_SwapLE16(value));
   488 }
   489 Uint16 SDL_ReadBE16 (SDL_RWops *src)
   490 {
   491 	Uint16 value;
   492 
   493 	SDL_RWread(src, &value, (sizeof value), 1);
   494 	return(SDL_SwapBE16(value));
   495 }
   496 Uint32 SDL_ReadLE32 (SDL_RWops *src)
   497 {
   498 	Uint32 value;
   499 
   500 	SDL_RWread(src, &value, (sizeof value), 1);
   501 	return(SDL_SwapLE32(value));
   502 }
   503 Uint32 SDL_ReadBE32 (SDL_RWops *src)
   504 {
   505 	Uint32 value;
   506 
   507 	SDL_RWread(src, &value, (sizeof value), 1);
   508 	return(SDL_SwapBE32(value));
   509 }
   510 Uint64 SDL_ReadLE64 (SDL_RWops *src)
   511 {
   512 	Uint64 value;
   513 
   514 	SDL_RWread(src, &value, (sizeof value), 1);
   515 	return(SDL_SwapLE64(value));
   516 }
   517 Uint64 SDL_ReadBE64 (SDL_RWops *src)
   518 {
   519 	Uint64 value;
   520 
   521 	SDL_RWread(src, &value, (sizeof value), 1);
   522 	return(SDL_SwapBE64(value));
   523 }
   524 
   525 int SDL_WriteLE16 (SDL_RWops *dst, Uint16 value)
   526 {
   527 	value = SDL_SwapLE16(value);
   528 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   529 }
   530 int SDL_WriteBE16 (SDL_RWops *dst, Uint16 value)
   531 {
   532 	value = SDL_SwapBE16(value);
   533 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   534 }
   535 int SDL_WriteLE32 (SDL_RWops *dst, Uint32 value)
   536 {
   537 	value = SDL_SwapLE32(value);
   538 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   539 }
   540 int SDL_WriteBE32 (SDL_RWops *dst, Uint32 value)
   541 {
   542 	value = SDL_SwapBE32(value);
   543 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   544 }
   545 int SDL_WriteLE64 (SDL_RWops *dst, Uint64 value)
   546 {
   547 	value = SDL_SwapLE64(value);
   548 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   549 }
   550 int SDL_WriteBE64 (SDL_RWops *dst, Uint64 value)
   551 {
   552 	value = SDL_SwapBE64(value);
   553 	return(SDL_RWwrite(dst, &value, (sizeof value), 1));
   554 }