Example #1
0
bool File::try_open(const UTF8String& filename, Mode mode)
{
	return _open(filename, mode, false);
}
Example #2
0
long
readtransfers(char *transferfile, long numpatches)
{
	int		handle;
	long	readpatches = 0, readtransfers = 0, totalbytes = 0;
	long	start, end;
	time((time_t*)&start);
	if ( (handle = _open( transferfile, _O_RDONLY | _O_BINARY )) != -1 )
	{
		long			filepatches;
		unsigned long	bytesread;

		printf("%-20s Restoring [%-13s - ", "MakeAllScales:", transferfile );
		
		if ( (bytesread = _read(handle, &filepatches, sizeof(filepatches))) == sizeof(filepatches) )
		{
			if ( filepatches == numpatches )
			{

				patch_t			*patch;

				totalbytes += bytesread;

				for( patch = patches; readpatches < numpatches; patch++ )
				{
					if ( (bytesread = _read(handle, &patch->numtransfers, sizeof(patch->numtransfers)))
					  == sizeof(patch->numtransfers) )
					{
						if ( patch->transfers = calloc(patch->numtransfers, sizeof(patch->transfers[0])) )
						{
							totalbytes += bytesread;

							if ( patch->numtransfers )
							{
								if ( (bytesread = _read(handle, patch->transfers, patch->numtransfers*sizeof(transfer_t)))
								  == patch->numtransfers*sizeof(transfer_t) )
									{
										totalbytes += bytesread;
										readtransfers += patch->numtransfers;
									}
								else
								{
									printf("\nMissing transfer count!  Save file will now be rebuilt." );
									break;
								}
							}
							readpatches++;
						}
						else
						{
							printf("\nMemory allocation failure creating transfer lists(%d*%d)!\n",
								  patch->numtransfers, sizeof(transfer_t) );
							break;
						}
					}
					else
					{
						printf("\nMissing patch count!  Save file will now be rebuilt." );
						break;
					}
				}
			}
			else
				printf("\nIncorrect transfer patch count found!  Save file will now be rebuilt." );
		}
		_close( handle );
		time((time_t*)&end);
		printf("%10.3fMB] (%d)\n",totalbytes/(1024.0*1024.0), end-start);
	}

	if (readpatches != numpatches )
		unlink(transferfile);
	else
		total_transfer = readtransfers;

	return readpatches;
}
Example #3
0
FILE *
fopen(const char *name, const char *mode)
{
	register int i;
	int rwmode = 0, rwflags = 0;
	FILE *stream;
	struct stat st;
	int fd, flags = 0;

	for (i = 0; __iotab[i] != 0 ; i++) 
		if ( i >= FOPEN_MAX-1 )
			return (FILE *)NULL;

	switch(*mode++) {
	case 'r':
		flags |= _IOREAD | _IOREADING;	
		rwmode = O_RDONLY;
		break;
	case 'w':
		flags |= _IOWRITE | _IOWRITING;
		rwmode = O_WRONLY;
		rwflags = O_CREAT | O_TRUNC;
		break;
	case 'a': 
		flags |= _IOWRITE | _IOWRITING | _IOAPPEND;
		rwmode = O_WRONLY;
		rwflags |= O_APPEND | O_CREAT;
		break;         
	default:
		return (FILE *)NULL;
	}

	while (*mode) {
		switch(*mode++) {
		case 'b':
			continue;
		case '+':
			rwmode = O_RDWR;
			flags |= _IOREAD | _IOWRITE;
			continue;
		/* The sequence may be followed by additional characters */
		default:
			break;
		}
		break;
	}

	/* Perform a creat() when the file should be truncated or when
	 * the file is opened for writing and the open() failed.
	 */
	if ((rwflags & O_TRUNC)
	    || (((fd = _open(name, rwmode)) < 0)
		    && (rwflags & O_CREAT))) {
		if (((fd = _creat(name, PMODE)) > 0) && flags  | _IOREAD) {
			(void) _close(fd);
			fd = _open(name, rwmode);
		}
			
	}

	if (fd < 0) return (FILE *)NULL;

	if ( fstat( fd, &st ) < 0 ) {
		_close(fd);
		return (FILE *)NULL;
	}
	
	if ( st.st_mode & S_IFIFO ) flags |= _IOFIFO;
	
	if (( stream = (FILE *) malloc(sizeof(FILE))) == NULL ) {
		_close(fd);
		return (FILE *)NULL;
	}

	if ((flags & (_IOREAD | _IOWRITE))  == (_IOREAD | _IOWRITE))
		flags &= ~(_IOREADING | _IOWRITING);

	stream->_count = 0;
	stream->_fd = fd;
	stream->_flags = flags;
	stream->_buf = NULL;
	__iotab[i] = stream;
	return stream;
}
bool _Filebuf_base::_M_open(const char* name, ios_base::openmode openmode,
                            long permission)
{
  _STLP_fd file_no;

  if (_M_is_open)
    return false;

#if defined (_STLP_USE_UNIX_IO) || defined (_STLP_USE_UNIX_EMULATION_IO)

  int flags = 0;

  // Unix makes no distinction between text and binary files.
  switch(openmode & (~ios_base::ate & ~ios_base::binary)) {
  case ios_base::out:
  case ios_base::out | ios_base::trunc:
    flags = O_WRONLY | O_CREAT | O_TRUNC;
    break;
  case ios_base::out | ios_base::app:
    flags = O_WRONLY | O_CREAT | O_APPEND;
    break;
  case ios_base::in:
    flags = O_RDONLY;
    permission = 0;             // Irrelevant unless we're writing.
    break;
  case ios_base::in | ios_base::out:
    flags = O_RDWR;
    break;
  case ios_base::in | ios_base::out | ios_base::trunc:
    flags = O_RDWR | O_CREAT | O_TRUNC;
    break;
  default:                      // The above are the only combinations of 
    return false;               // flags allowed by the C++ standard.
  }

# if defined (_STLP_USE_UNIX_EMULATION_IO)

  if (openmode & ios_base::binary)
    flags |= O_BINARY;
  else
    flags |= O_TEXT;

  file_no = _open(name, flags, permission);

# else

  file_no = open(name, flags, permission);

# endif /* _STLP_USE_UNIX_EMULATION_IO */

  if (file_no < 0)
    return false;

  _M_is_open = true;

  if (openmode & ios_base::ate)
    if (LSEEK(file_no, 0, SEEK_END) == -1)
      _M_is_open = false;
  
#elif defined (_STLP_USE_STDIO_IO)
  // use FILE-based i/o
  const char* flags;

  switch(openmode & (~ios_base::ate)) {
  case ios_base::out:
  case ios_base::out | ios_base::trunc:
    flags = "w";
    break;

  case ios_base::out | ios_base::binary:
  case ios_base::out | ios_base::trunc | ios_base::binary:
    flags = "wb";
    break;

  case ios_base::out | ios_base::app:
    flags = "a";
    break;

  case ios_base::out | ios_base::app | ios_base::binary:
    flags = "ab";
    break;

  case ios_base::in:
    flags = "r";
    break;

  case ios_base::in | ios_base::binary:
    flags = "rb";
    break;

  case ios_base::in | ios_base::out:
    flags = "r+";
    break;

  case ios_base::in | ios_base::out | ios_base::binary:
    flags = "r+b";
    break;


  case ios_base::in | ios_base::out | ios_base::trunc:
    flags = "w+";
    break;

  case ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary:
    flags = "w+b";
    break;

  default:                      // The above are the only combinations of 
    return false;               // flags allowed by the C++ standard.
  }

  // fbp : TODO : set permissions !
  (void)permission; // currently unused		//*TY 02/26/2000 - added to suppress warning message
  _M_file = fopen(name, flags);
 
  if (_M_file) {
    file_no = fileno(_M_file);
  }
  else
    return false;

  // unset buffering immediately
  setbuf(_M_file, 0);

  _M_is_open = true;

  if (openmode & ios_base::ate)
    if (fseek(_M_file, 0, SEEK_END) == -1)
      _M_is_open = false;
  
#   elif defined (_STLP_USE_WIN32_IO)

  DWORD dwDesiredAccess, dwShareMode, dwCreationDisposition;
  bool  doTruncate = false;

  switch(openmode & (~ios_base::ate & ~ios_base::binary)) {
  case ios_base::out:
  case ios_base::out | ios_base::trunc:
    dwDesiredAccess = GENERIC_WRITE;
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    dwCreationDisposition = OPEN_ALWAYS;
    // boris : even though it is very non-intuitive, standard
    // requires them both to behave same.
    doTruncate = true;
    break;

  case ios_base::out | ios_base::app:
    dwDesiredAccess = GENERIC_WRITE;
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    dwCreationDisposition = OPEN_ALWAYS;
    break;
  case ios_base::in:
    dwDesiredAccess = GENERIC_READ;
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    dwCreationDisposition = OPEN_EXISTING;
    permission = 0;             // Irrelevant unless we're writing.
    break;
  case ios_base::in | ios_base::out:
    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    dwCreationDisposition = OPEN_EXISTING;
    break;
  case ios_base::in | ios_base::out | ios_base::trunc:
    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    dwCreationDisposition = OPEN_ALWAYS;
    doTruncate = true;
    break;
  default:                      // The above are the only combinations of
    return false;               // flags allowed by the C++ standard.
  }

  #if defined(_STLP_WINCE)
    file_no = CreateFile(__ASCIIToWide(name).c_str(),
  #else
    file_no = CreateFileA(name,
  #endif
                  dwDesiredAccess, dwShareMode, 0,
			dwCreationDisposition, permission, 0);
  
  if ( file_no == INVALID_HANDLE_VALUE )
  return false;

  if ((doTruncate && SetEndOfFile(file_no) == 0) ||
      ((openmode & ios_base::ate) && SetFilePointer(file_no, 0, NULL, FILE_END) == -1)) {
    CloseHandle(file_no);
    return false;
  }

  _M_is_open = true;
 
#else
# error "Port!"  
#endif /* __unix */


  _M_file_id = file_no;
  _M_should_close = _M_is_open;
  _M_openmode = openmode;

  if (_M_is_open)
    _M_regular_file = _SgI::__is_regular_file(_M_file_id);
  
  return _M_is_open;
}
Example #5
0
FTSENT *
__fts_read_44bsd(FTS *sp)
{
	FTSENT *p, *tmp;
	int instr;
	char *t;
	int saved_errno;

	/* If finished or unrecoverable error, return NULL. */
	if (sp->fts_cur == NULL || ISSET(FTS_STOP))
		return (NULL);

	/* Set current node pointer. */
	p = sp->fts_cur;

	/* Save and zero out user instructions. */
	instr = p->fts_instr;
	p->fts_instr = FTS_NOINSTR;

	/* Any type of file may be re-visited; re-stat and re-turn. */
	if (instr == FTS_AGAIN) {
		p->fts_info = fts_stat(sp, p, 0);
		return (p);
	}

	/*
	 * Following a symlink -- SLNONE test allows application to see
	 * SLNONE and recover.  If indirecting through a symlink, have
	 * keep a pointer to current location.  If unable to get that
	 * pointer, follow fails.
	 */
	if (instr == FTS_FOLLOW &&
	    (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
		p->fts_info = fts_stat(sp, p, 1);
		if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
			if ((p->fts_symfd = _open(".", O_RDONLY | O_CLOEXEC,
			    0)) < 0) {
				p->fts_errno = errno;
				p->fts_info = FTS_ERR;
			} else
				p->fts_flags |= FTS_SYMFOLLOW;
		}
		return (p);
	}

	/* Directory in pre-order. */
	if (p->fts_info == FTS_D) {
		/* If skipped or crossed mount point, do post-order visit. */
		if (instr == FTS_SKIP ||
		    (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
			if (p->fts_flags & FTS_SYMFOLLOW)
				(void)_close(p->fts_symfd);
			if (sp->fts_child) {
				fts_lfree(sp->fts_child);
				sp->fts_child = NULL;
			}
			p->fts_info = FTS_DP;
			return (p);
		}

		/* Rebuild if only read the names and now traversing. */
		if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
			CLR(FTS_NAMEONLY);
			fts_lfree(sp->fts_child);
			sp->fts_child = NULL;
		}

		/*
		 * Cd to the subdirectory.
		 *
		 * If have already read and now fail to chdir, whack the list
		 * to make the names come out right, and set the parent errno
		 * so the application will eventually get an error condition.
		 * Set the FTS_DONTCHDIR flag so that when we logically change
		 * directories back to the parent we don't do a chdir.
		 *
		 * If haven't read do so.  If the read fails, fts_build sets
		 * FTS_STOP or the fts_info field of the node.
		 */
		if (sp->fts_child != NULL) {
			if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
				p->fts_errno = errno;
				p->fts_flags |= FTS_DONTCHDIR;
				for (p = sp->fts_child; p != NULL;
				    p = p->fts_link)
					p->fts_accpath =
					    p->fts_parent->fts_accpath;
			}
		} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
			if (ISSET(FTS_STOP))
				return (NULL);
			return (p);
		}
		p = sp->fts_child;
		sp->fts_child = NULL;
		goto name;
	}

	/* Move to the next node on this level. */
next:	tmp = p;
	if ((p = p->fts_link) != NULL) {
		free(tmp);

		/*
		 * If reached the top, return to the original directory (or
		 * the root of the tree), and load the paths for the next root.
		 */
		if (p->fts_level == FTS_ROOTLEVEL) {
			if (FCHDIR(sp, sp->fts_rfd)) {
				SET(FTS_STOP);
				return (NULL);
			}
			fts_load(sp, p);
			return (sp->fts_cur = p);
		}

		/*
		 * User may have called fts_set on the node.  If skipped,
		 * ignore.  If followed, get a file descriptor so we can
		 * get back if necessary.
		 */
		if (p->fts_instr == FTS_SKIP)
			goto next;
		if (p->fts_instr == FTS_FOLLOW) {
			p->fts_info = fts_stat(sp, p, 1);
			if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
				if ((p->fts_symfd =
				    _open(".", O_RDONLY | O_CLOEXEC, 0)) < 0) {
					p->fts_errno = errno;
					p->fts_info = FTS_ERR;
				} else
					p->fts_flags |= FTS_SYMFOLLOW;
			}
			p->fts_instr = FTS_NOINSTR;
		}

name:		t = sp->fts_path + NAPPEND(p->fts_parent);
		*t++ = '/';
		memmove(t, p->fts_name, p->fts_namelen + 1);
		return (sp->fts_cur = p);
	}

	/* Move up to the parent node. */
	p = tmp->fts_parent;
	free(tmp);

	if (p->fts_level == FTS_ROOTPARENTLEVEL) {
		/*
		 * Done; free everything up and set errno to 0 so the user
		 * can distinguish between error and EOF.
		 */
		free(p);
		errno = 0;
		return (sp->fts_cur = NULL);
	}

	/* NUL terminate the pathname. */
	sp->fts_path[p->fts_pathlen] = '\0';

	/*
	 * Return to the parent directory.  If at a root node or came through
	 * a symlink, go back through the file descriptor.  Otherwise, cd up
	 * one directory.
	 */
	if (p->fts_level == FTS_ROOTLEVEL) {
		if (FCHDIR(sp, sp->fts_rfd)) {
			SET(FTS_STOP);
			return (NULL);
		}
	} else if (p->fts_flags & FTS_SYMFOLLOW) {
		if (FCHDIR(sp, p->fts_symfd)) {
			saved_errno = errno;
			(void)_close(p->fts_symfd);
			errno = saved_errno;
			SET(FTS_STOP);
			return (NULL);
		}
		(void)_close(p->fts_symfd);
	} else if (!(p->fts_flags & FTS_DONTCHDIR) &&
	    fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
		SET(FTS_STOP);
		return (NULL);
	}
	p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
	return (sp->fts_cur = p);
}
struct winfd usbi_create_fd(HANDLE handle, int access_mode)
{
	int i, fd;
	struct winfd wfd = INVALID_WINFD;
	OVERLAPPED* overlapped = NULL;

	CHECK_INIT_POLLING;

	if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) {
		return INVALID_WINFD;
	}

	if ((access_mode != _O_RDONLY) && (access_mode != _O_WRONLY)) {
		usbi_warn(NULL, "only one of _O_RDONLY or _O_WRONLY are supported.\n"
			"If you want to poll for R/W simultaneously, create multiple fds from the same handle.");
		return INVALID_WINFD;
	}
	if (access_mode == _O_RDONLY) {
		wfd.rw = RW_READ;
	} else {
		wfd.rw = RW_WRITE;
	}

	
	
	fd = _open(NUL_DEVICE, _O_WRONLY);
	if (fd < 0) {
		return INVALID_WINFD;
	}

	overlapped = create_overlapped();
	if(overlapped == NULL) {
		_close(fd);
		return INVALID_WINFD;
	}

	for (i=0; i<MAX_FDS; i++) {
		if (poll_fd[i].fd < 0) {
			EnterCriticalSection(&_poll_fd[i].mutex);
			
			if (poll_fd[i].fd >= 0) {
				LeaveCriticalSection(&_poll_fd[i].mutex);
				continue;
			}
			wfd.fd = fd;
			
			
			if (!CancelIoEx_Available) {
				_poll_fd[i].thread_id = GetCurrentThreadId();
				if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(),
					&wfd.handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
					usbi_dbg("could not duplicate handle for CancelIo - using original one");
					wfd.handle = handle;
					
					_poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
				} else {
					_poll_fd[i].original_handle = handle;
				}
			} else {
				wfd.handle = handle;
			}
			wfd.overlapped = overlapped;
			memcpy(&poll_fd[i], &wfd, sizeof(struct winfd));
			LeaveCriticalSection(&_poll_fd[i].mutex);
			return wfd;
		}
	}
	free_overlapped(overlapped);
	_close(fd);
	return INVALID_WINFD;
}
Example #7
0
void main(void) {
    uint8_t inputProgramType;
    char *inputProgram;
    uint16_t inputProgramSize;
    ti_var_t programSlot;
    uint8_t selectedProgram, amountOfPrograms, res = VALID, type;
    unsigned int programDataSize, offset, totalSize;
    uint8_t beginList, amountOfProgramsToDisplay;
    uint8_t relativeSelectedProgram;
    const char ICEheader[] = {tii, 0};
    ti_var_t tempProg;
    char buf[30], *temp_name = "", var_name[9];
    sk_key_t key = 0;
    void *search_pos;
    bool didCompile;

    // Install hooks
    ti_CloseAll();
    if ((tempProg = ti_Open("ICEHOOKS", "r"))) {
        ti_SetArchiveStatus(true, tempProg);
        SetHooks(ti_GetDataPtr(tempProg));
    }
    
    // Enable lowercase
    asm("ld iy, 0D00080h");
    asm("set 3, (iy+024h)");

    // check if a program was used as input
    ti_CloseAll();
    ice.usingInputProgram = false;
    inputProgram = os_RclAns(&inputProgramType);
    if (inputProgram && inputProgramType == TI_STRING_TYPE && inputProgram[2] == tProg && (inputProgramSize = *(uint16_t*)inputProgram) < 10) {
        memset(var_name, 0, sizeof var_name);
        memcpy(var_name, inputProgram + 3, inputProgramSize - 1);
        programSlot = ti_OpenVar(var_name, "r", TI_PRGM_TYPE);
        if (programSlot) {
            ice.usingInputProgram = true;
        }
    }

    // Yay, GUI! :)
displayMainScreen:
    gfx_Begin();

    gfx_SetColor(189);
    gfx_FillRectangle_NoClip(0, 0, 320, 10);
    gfx_SetColor(0);
    gfx_SetTextFGColor(0);
    gfx_HorizLine_NoClip(0, 10, 320);
    gfx_PrintStringXY(infoStr, 12, 1);

    // Get all the programs that start with the [i] token
    selectedProgram = 0;
    didCompile = false;
    ti_CloseAll();

    if (ice.usingInputProgram) {
        goto compile_program;
    }

    search_pos = NULL;
    while ((temp_name = ti_DetectAny(&search_pos, ICEheader, &type)) != NULL) {
        if (type == TI_PRGM_TYPE || type == TI_PPRGM_TYPE) {
            // Hidden programs
            if ((uint8_t)(*temp_name) < 64) {
                *temp_name += 64;
            }

            // Save the program name
            inputPrograms[selectedProgram] = malloc(9);
            strcpy(inputPrograms[selectedProgram++], temp_name);
        }
        
        if (selectedProgram >= NUMBEROFPROGRAM) {
            break;
        }
    }

    amountOfPrograms = selectedProgram;
    beginList = 0;
    amountOfProgramsToDisplay = (amountOfPrograms > PROGRAMPERSCREEN ? PROGRAMPERSCREEN : amountOfPrograms);

    // Check if there are ICE programs
    if (!amountOfPrograms) {
        gfx_PrintStringXY("No programs found!", 10, 13);
        goto stop;
    }

    // Display all the sorted programs
    qsort(inputPrograms, amountOfPrograms, sizeof(char *), myCompare);
    displayProgramList(beginList, amountOfProgramsToDisplay);
    
    // Display buttons
    gfx_PrintStringXY("Build", 4, 232);
    printButton(1);
    gfx_PrintStringXY("Debug", 66, 232);
    printButton(65);
    gfx_PrintStringXY("Quit", 285, 232);
    printButton(279);
    gfx_SetColor(0);

    // Select a program
    selectedProgram = 1;
    relativeSelectedProgram = 1;
    while ((key = os_GetCSC()) != sk_Enter && key != sk_2nd && key != sk_Yequ && key != sk_Window) {
        uint8_t selectionOffset = relativeSelectedProgram * 10 + 3;

        gfx_PrintStringXY(">", 1, selectionOffset);

        if (key) {
            gfx_SetColor(255);
            gfx_FillRectangle_NoClip(1, selectionOffset, 8, 8);

            // Stop and quit
            if (key == sk_Clear || key == sk_Graph) {
                goto err;
            }

            // Select the next program
            if (key == sk_Down) {
                if (selectedProgram != amountOfPrograms) {
                    selectedProgram++;
                    relativeSelectedProgram++;
                    if (relativeSelectedProgram > PROGRAMPERSCREEN) {
                        clearProgramList();
                        relativeSelectedProgram--;
                        beginList++;
                        displayProgramList(beginList, amountOfProgramsToDisplay);
                    }
                } else {
                    clearProgramList();
                    selectedProgram = 1;
                    relativeSelectedProgram = 1;
                    beginList = 0;
                    displayProgramList(beginList, amountOfProgramsToDisplay);
                }
            }

            // Select the previous program
            if (key == sk_Up) {
                if (selectedProgram != 1) {
                    selectedProgram--;
                    relativeSelectedProgram--;
                    if(relativeSelectedProgram == 0) {
                        clearProgramList();
                        relativeSelectedProgram++;
                        beginList--;
                        displayProgramList(beginList, amountOfProgramsToDisplay);
                    }
                } else {
                    clearProgramList();
                    selectedProgram = amountOfPrograms;
                    relativeSelectedProgram = (amountOfPrograms > PROGRAMPERSCREEN ? PROGRAMPERSCREEN : amountOfPrograms);
                    beginList = (selectedProgram >= PROGRAMPERSCREEN ? selectedProgram - PROGRAMPERSCREEN : 0);
                    displayProgramList(beginList, amountOfProgramsToDisplay);
                }
            }
        }
    }
    
    // Set some vars
    strcpy(var_name, inputPrograms[selectedProgram - 1]);
    for (selectedProgram = 0; selectedProgram < amountOfPrograms; selectedProgram++) {
        free(inputPrograms[selectedProgram]);
    }

compile_program:

    // Erase screen
    gfx_SetColor(255);
    gfx_FillRectangle_NoClip(0, 11, 320, 210);
    gfx_FillRectangle_NoClip(0, 220, 270, 20);

    didCompile = true;
    memset(&ice, 0, sizeof ice);
    memset(&expr, 0, sizeof expr);
    memset(&reg, 0, sizeof reg);
    memset(&prescan, 0, sizeof prescan);
    memset(&debug, 0, sizeof debug);
    
    // Output debug appvar
    if (key == sk_Window) {
        ice.debug = true;
    }

    gfx_SetTextXY(1, 12);
    displayMessageLineScroll("Prescanning...");
    displayLoadingBarFrame();

    ice.inPrgm = _open(var_name);
    _seek(0, SEEK_END, ice.inPrgm);

    ice.programLength   = _tell(ice.inPrgm);
    ice.programData     = (uint8_t*)0xD52C00;
    ice.programPtr      = ice.programData;
    ice.programDataData = ice.programData + 0xFFFF;
    ice.programDataPtr  = ice.programDataData;
    
    // Get the name/icon/description
    _rewind(ice.inPrgm);
    if ((res = getNameIconDescription()) != VALID) {
        displayError(res);
        goto stop;
    }
    
    // Open debug appvar to store things to
    sprintf(buf, "%.5sDBG", ice.outName);
    debug.dbgPrgm = ti_Open(buf, "w");
    
    if (ice.debug) {
        if (!debug.dbgPrgm) {
            displayError(E_NO_DBG_FILE);
            goto stop;
        }
        
        // Write version bytes to debug appvar
        ti_PutC(DEBUG_VERSION_MAJOR, debug.dbgPrgm);
        ti_PutC(DEBUG_VERSION_MINOR, debug.dbgPrgm);
        
        // Write amount of programs to debug appvar
        ti_PutC(0, debug.dbgPrgm);
    } else if (debug.dbgPrgm) {
        ti_Delete(buf);
    }

    // Prescan the program and output the header
    preScanProgram();
    if ((res = parsePrescan()) != VALID) {
        displayError(res);
        goto stop;
    }
	
	if (prescan.amountOfVariablesUsed > 84) {
		gfx_SetTextFGColor(224);
		sprintf(buf, "Too much variables used: %d", prescan.amountOfVariablesUsed);
		displayMessageLineScroll(buf);
		didCompile = false;
		goto stop;
	}

    // Allow hidden programs from Cesium
    if (*var_name < 64) {
        *var_name += 64;
    }
    sprintf(buf, "Compiling program %s...", var_name);
    displayMessageLineScroll(buf);

    // Create or empty the output program if parsing succeeded
    if ((res = parseProgram()) == VALID) {
        unsigned int previousSize = 0;

        // Get the sizes of both stacks
        ice.programSize = (uintptr_t)ice.programPtr - (uintptr_t)ice.programData;
        programDataSize = (uintptr_t)ice.programDataData - (uintptr_t)ice.programDataPtr;

        // Change the pointers to the data as well, but first calculate the offset
        offset = PRGM_START + ice.programSize - (uintptr_t)ice.programDataPtr;
        while (ice.dataOffsetElements--) {
            unsigned int *tempDataOffsetStackPtr = ice.dataOffsetStack[ice.dataOffsetElements];

            *tempDataOffsetStackPtr += offset;
        }
        totalSize = ice.programSize + programDataSize + 3;

        // Export the program
        ice.outPrgm = _open(ice.outName);
        if (ice.outPrgm) {
            // This program already exists
            if ((uint8_t)ti_GetC(ice.outPrgm) != 0xEF || (uint8_t)ti_GetC(ice.outPrgm) != 0x7B) {
                gfx_SetTextFGColor(224);
                displayMessageLineScroll("Output program already exists!");
                displayMessageLineScroll("Delete program to continue.");
                didCompile = false;
                goto stop;
            }
            
            previousSize = ti_GetSize(ice.outPrgm);
            ti_Close(ice.outPrgm);
        }
        ice.outPrgm = _new(ice.outName);
        if (!ice.outPrgm) {
            displayMessageLineScroll("Failed to open output file");
            goto stop;
        }

        // Write ASM header
        ti_PutC(tExtTok, ice.outPrgm);
        ti_PutC(tAsm84CeCmp, ice.outPrgm);

        // Write ICE header to be recognized by Cesium
        ti_PutC(0x7F, ice.outPrgm);

        // Write the header, main program, and data to output :D
        ti_Write(ice.programData, ice.programSize, 1, ice.outPrgm);
        if (programDataSize) ti_Write(ice.programDataPtr, programDataSize, 1, ice.outPrgm);
        _rewind(ice.outPrgm);
        
        // Write final CRC to debug program, as well as the ending line of the first program and the amount of total programs
        if (ice.debug) {
            uint16_t CRC;
            
            CRC = GetCRC(ti_GetDataPtr(ice.outPrgm), ti_GetSize(ice.outPrgm));
            WriteWordToDebugProg(CRC);
            ti_Seek(3 + offsetof(debug_prog_t, endingLine), SEEK_SET, debug.dbgPrgm);
            WriteWordToDebugProg(debug.currentLine);
            ti_Seek(2, SEEK_SET, debug.dbgPrgm);
            ti_PutC(debug.amountOfPrograms + 1, debug.dbgPrgm);         // +1 because the main program starts at 0
        }

        // Yep, we are really done!
        gfx_SetTextFGColor(4);
        displayMessageLineScroll("Successfully compiled!");
        if (ice.debug) {
            displayMessageLineScroll("Successfully exported debug appvar");
        }

        // Skip line
        displayMessageLineScroll(" ");

        // Display the size
        gfx_SetTextFGColor(0);
        sprintf(buf, "Output size: %u bytes", totalSize);
        displayMessageLineScroll(buf);
        if (previousSize) {
            sprintf(buf, "Previous size: %u bytes", previousSize);
            displayMessageLineScroll(buf);
        }
        sprintf(buf, "Output program: %s", ice.outName);
        displayMessageLineScroll(buf);
    } else if (res != W_VALID) {
        displayError(res);
    }

stop:
    gfx_SetTextFGColor(0);
    if (didCompile) {
        if (res == VALID) {
            gfx_PrintStringXY("Run", 9, 232);
            printButton(1);
        } else if (!ti_IsArchived(ice.inPrgm)) {
            gfx_PrintStringXY("Goto", 222, 232);
            printButton(217);
        }
        gfx_PrintStringXY("Back", 70, 232);
        printButton(65);
        gfx_PrintStringXY("Quit", 285, 232);
        printButton(279);
    }
    while (!(key = os_GetCSC()));
err:
    gfx_End();

    if (key != sk_Graph && didCompile) {
        if (key == sk_Yequ && res == VALID) {
            RunPrgm(ice.outName);
        }
        if (key == sk_Window) {
            // Erase screen
            gfx_SetColor(255);
            gfx_FillRectangle_NoClip(0, 11, 320, 229);

            goto displayMainScreen;
        }
        if (key == sk_Trace && res != VALID && !ti_IsArchived(ice.inPrgm)) {
            char buf[9];
            
            ti_GetName(buf, ice.inPrgm);
            GotoEditor(buf, ti_Tell(ice.inPrgm) - 1);
        }
    }
    ti_CloseAll();
}
Example #8
0
File: td.c Project: ha1t/recfriio
static void test_arib_std_b25(const char *src, const char *dst, OPTION *opt)
{
	int code,i,n,m;
	int sfd,dfd;

	int64_t total;
	int64_t offset;
#if defined(WIN32)
	unsigned long tick,tock;
#else
	struct timeval tick,tock;
	double millisec;
#endif
	double mbps;

	ARIB_STD_B25 *b25;
	B_CAS_CARD   *bcas;

	ARIB_STD_B25_PROGRAM_INFO pgrm;

	uint8_t data[64*1024];

	ARIB_STD_B25_BUFFER sbuf;
	ARIB_STD_B25_BUFFER dbuf;

	sfd = -1;
	dfd = -1;
	b25 = NULL;
	bcas = NULL;

	sfd = _open(src, _O_BINARY|_O_RDONLY|_O_SEQUENTIAL);
	if(sfd < 0){
		fprintf(stderr, "error - failed on _open(%s) [src]\n", src);
		goto LAST;
	}
	
	_lseeki64(sfd, 0, SEEK_END);
	total = _telli64(sfd);
	_lseeki64(sfd, opt->skip, SEEK_SET);

	b25 = create_arib_std_b25();
	if(b25 == NULL){
		fprintf(stderr, "error - failed on create_arib_std_b25()\n");
		goto LAST;
	}

	code = b25->set_multi2_round(b25, opt->round);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::set_multi2_round() : code=%d\n", code);
		goto LAST;
	}

	code = b25->set_strip(b25, opt->strip);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::set_strip() : code=%d\n", code);
		goto LAST;
	}

	code = b25->set_emm_proc(b25, opt->emm);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::set_emm_proc() : code=%d\n", code);
		goto LAST;
	}

	bcas = create_b_cas_card();
	if(bcas == NULL){
		fprintf(stderr, "error - failed on create_b_cas_card()\n");
		goto LAST;
	}

	code = bcas->init(bcas);
	if(code < 0){
		fprintf(stderr, "error - failed on B_CAS_CARD::init() : code=%d\n", code);
		goto LAST;
	}

	code = b25->set_b_cas_card(b25, bcas);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::set_b_cas_card() : code=%d\n", code);
		goto LAST;
	}

	dfd = _open(dst, _O_BINARY|_O_WRONLY|_O_SEQUENTIAL|_O_CREAT|_O_TRUNC, _S_IREAD|_S_IWRITE);
	if(dfd < 0){
		fprintf(stderr, "error - failed on _open(%s) [dst]\n", dst);
		goto LAST;
	}

	offset = 0;
#if defined(WIN32)
	tock = GetTickCount();
#else
	gettimeofday(&tock, NULL);
#endif
	while( (n = _read(sfd, data, sizeof(data))) > 0 ){
		sbuf.data = data;
		sbuf.size = n;

		code = b25->put(b25, &sbuf);
		if(code < 0){
			fprintf(stderr, "error - failed on ARIB_STD_B25::put() : code=%d\n", code);
			goto LAST;
		}

		code = b25->get(b25, &dbuf);
		if(code < 0){
			fprintf(stderr, "error - failed on ARIB_STD_B25::get() : code=%d\n", code);
			goto LAST;
		}

		if(dbuf.size > 0){
			n = _write(dfd, dbuf.data, dbuf.size);
			if(n != dbuf.size){
				fprintf(stderr, "error failed on _write(%d)\n", dbuf.size);
				goto LAST;
			}
		}
		
		offset += sbuf.size;
		if(opt->verbose != 0){
			m = (int)(10000*offset/total);
			mbps = 0.0;
#if defined(WIN32)
			tick = GetTickCount();
			if (tick-tock > 100) {
				mbps = offset;
				mbps /= 1024;
				mbps /= (tick-tock);
			}
#else
			gettimeofday(&tick, NULL);
			millisec = (tick.tv_sec - tock.tv_sec) * 1000;
			millisec += (tick.tv_usec - tock.tv_usec) / 1000;
			if(millisec > 100.0) {
				mbps = offset;
				mbps /= 1024;
				mbps /= millisec;
			}
#endif
			fprintf(stderr, "\rprocessing: %2d.%02d%% [%6.2f MB/sec]", m/100, m%100, mbps);
		}
	}

	code = b25->flush(b25);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::flush() : code=%d\n", code);
		goto LAST;
	}
	
	code = b25->get(b25, &dbuf);
	if(code < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::get() : code=%d\n", code);
		goto LAST;
	}

	if(dbuf.size > 0){
		n = _write(dfd, dbuf.data, dbuf.size);
		if(n != dbuf.size){
			fprintf(stderr, "error - failed on _write(%d)\n", dbuf.size);
			goto LAST;
		}
	}

	if(opt->verbose != 0){
		mbps = 0.0;
#if defined(WIN32)
		tick = GetTickCount();
		if (tick-tock > 100) {
			mbps = offset;
			mbps /= 1024;
			mbps /= (tick-tock);
		}
#else
		gettimeofday(&tick, NULL);
		millisec = (tick.tv_sec - tock.tv_sec) * 1000;
		millisec += (tick.tv_usec - tock.tv_usec) / 1000;
		if(millisec > 100.0) {
			mbps = offset;
			mbps /= 1024;
			mbps /= millisec;
		}
#endif
		fprintf(stderr, "\rprocessing: finish  [%6.2f MB/sec]\n", mbps);
		fflush(stderr);
		fflush(stdout);
	}

	n = b25->get_program_count(b25);
	if(n < 0){
		fprintf(stderr, "error - failed on ARIB_STD_B25::get_program_count() : code=%d\n", code);
		goto LAST;
	}
	for(i=0;i<n;i++){
		code = b25->get_program_info(b25, &pgrm, i);
		if(code < 0){
			fprintf(stderr, "error - failed on ARIB_STD_B25::get_program_info(%d) : code=%d\n", i, code);
			goto LAST;
		}
		if(pgrm.ecm_unpurchased_count > 0){
			fprintf(stderr, "warning - unpurchased ECM is detected\n");
			fprintf(stderr, "  channel:               %d\n", pgrm.program_number);
			fprintf(stderr, "  unpurchased ECM count: %d\n", pgrm.ecm_unpurchased_count);
			fprintf(stderr, "  last ECM error code:   %04x\n", pgrm.last_ecm_error_code);
			#if defined(WIN32)
			fprintf(stderr, "  undecrypted TS packet: %d\n", pgrm.undecrypted_packet_count);
			fprintf(stderr, "  total TS packet:       %d\n", pgrm.total_packet_count);
			#else
			fprintf(stderr, "  undecrypted TS packet: %"PRId64"\n", pgrm.undecrypted_packet_count);
			fprintf(stderr, "  total TS packet:       %"PRId64"\n", pgrm.total_packet_count);
			#endif
		}
	}

	if(opt->power_ctrl != 0){
		show_bcas_power_on_control_info(bcas);
	}

LAST:

	if(sfd >= 0){
		_close(sfd);
		sfd = -1;
	}

	if(dfd >= 0){
		_close(dfd);
		dfd = -1;
	}

	if(b25 != NULL){
		b25->release(b25);
		b25 = NULL;
	}

	if(bcas != NULL){
		bcas->release(bcas);
		bcas = NULL;
	}
}
Example #9
0
/*
 * Create both an fd and an OVERLAPPED from an open Windows handle, so that
 * it can be used with our polling function
 * The handle MUST support overlapped transfers (usually requires CreateFile
 * with FILE_FLAG_OVERLAPPED)
 * Return a pollable file descriptor struct, or INVALID_WINFD on error
 *
 * Note that the fd returned by this function is a per-transfer fd, rather
 * than a per-session fd and cannot be used for anything else but our
 * custom functions (the fd itself points to the NUL: device)
 * if you plan to do R/W on the same handle, you MUST create 2 fds: one for
 * read and one for write. Using a single R/W fd is unsupported and will
 * produce unexpected results
 */
struct winfd usbi_create_fd(HANDLE handle, int access_mode)
{
	int i, fd;
	struct winfd wfd = INVALID_WINFD;
	OVERLAPPED* overlapped = NULL;

	CHECK_INIT_POLLING;

	if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) {
		return INVALID_WINFD;
	}

	if ((access_mode != _O_RDONLY) && (access_mode != _O_WRONLY)) {
		usbi_warn(NULL, "only one of _O_RDONLY or _O_WRONLY are supported.\n"
			"If you want to poll for R/W simultaneously, create multiple fds from the same handle.");
		return INVALID_WINFD;
	}
	if (access_mode == _O_RDONLY) {
		wfd.rw = RW_READ;
	} else {
		wfd.rw = RW_WRITE;
	}

	// Ensure that we get a non system conflicting unique fd, using
	// the same fd attribution system as the pipe ends
	fd = _open(NUL_DEVICE, _O_WRONLY);
	if (fd < 0) {
		return INVALID_WINFD;
	}

	overlapped = create_overlapped();
	if(overlapped == NULL) {
		_close(fd);
		return INVALID_WINFD;
	}

	for (i=0; i<MAX_FDS; i++) {
		if (poll_fd[i].fd < 0) {
			EnterCriticalSection(&_poll_fd[i].mutex);
			// fd might have been removed before we got to critical
			if (poll_fd[i].fd >= 0) {
				LeaveCriticalSection(&_poll_fd[i].mutex);
				continue;
			}
			wfd.fd = fd;
			// Attempt to emulate some of the CancelIoEx behaviour on platforms
			// that don't have it
			if (!CancelIoEx_Available) {
				_poll_fd[i].thread_id = GetCurrentThreadId();
				if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(),
					&wfd.handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
					usbi_dbg("could not duplicate handle for CancelIo - using original one");
					wfd.handle = handle;
					// Make sure we won't close the original handle on fd deletion then
					_poll_fd[i].original_handle = INVALID_HANDLE_VALUE;
				} else {
					_poll_fd[i].original_handle = handle;
				}
			} else {
				wfd.handle = handle;
			}
			wfd.overlapped = overlapped;
			memcpy(&poll_fd[i], &wfd, sizeof(struct winfd));
			LeaveCriticalSection(&_poll_fd[i].mutex);
			return wfd;
		}
	}
	free_overlapped(overlapped);
	_close(fd);
	return INVALID_WINFD;
}
Example #10
0
int prepare(const char *lpCmdLine) {
	char tmp[MAX_ARGS] = {0};
	hModule = GetModuleHandle(NULL);
	if (hModule == NULL) {
		return FALSE;
	}

	// Get executable path
	char exePath[_MAX_PATH] = {0};
	int pathLen = getExePath(exePath);
	if (pathLen == -1) {
		return FALSE;
	}

	// Initialize logging
    if (strstr(lpCmdLine, "--l4j-debug") != NULL) {
		hLog = openLogFile(exePath, pathLen);
		if (hLog == NULL) {
			return FALSE;
		}
		debug("\n\nCmdLine:\t%s %s\n", exePath, lpCmdLine);
	}

    setWow64Flag();

	// Set default error message, title and optional support web site url.
	loadString(SUPPORT_URL, errUrl);
	loadString(ERR_TITLE, errTitle);
	if (!loadString(STARTUP_ERR, errMsg)) {
		return FALSE;
	}

	// Single instance
	loadString(MUTEX_NAME, mutexName);
	if (*mutexName) {
		SECURITY_ATTRIBUTES security;
		security.nLength = sizeof(SECURITY_ATTRIBUTES);
		security.bInheritHandle = TRUE;
		security.lpSecurityDescriptor = NULL;
		CreateMutexA(&security, FALSE, mutexName);
		if (GetLastError() == ERROR_ALREADY_EXISTS) {
			debug("Instance already exists.");
			return ERROR_ALREADY_EXISTS;
		}
	}

	// Working dir
	char tmp_path[_MAX_PATH] = {0};
	GetCurrentDirectory(_MAX_PATH, oldPwd);
	if (loadString(CHDIR, tmp_path)) {
		strncpy(workingDir, exePath, pathLen);
		appendPath(workingDir, tmp_path);
		_chdir(workingDir);
		debug("Working dir:\t%s\n", workingDir);
	}

	// Use bundled jre or find java
	if (loadString(JRE_PATH, tmp_path)) {
		char jrePath[MAX_ARGS] = {0};
		expandVars(jrePath, tmp_path, exePath, pathLen);
		debug("Bundled JRE:\t%s\n", jrePath);
		if (jrePath[0] == '\\' || jrePath[1] == ':') {
			// Absolute
			strcpy(cmd, jrePath);
		} else {
			// Relative
			strncpy(cmd, exePath, pathLen);
			appendPath(cmd, jrePath);
		}
    }
	if (!isJrePathOk(cmd)) {
		if (!loadString(JAVA_MIN_VER, javaMinVer)) {
			loadString(BUNDLED_JRE_ERR, errMsg);
			return FALSE;
		}
		loadString(JAVA_MAX_VER, javaMaxVer);
		if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE))) {
			loadString(JRE_VERSION_ERR, errMsg);
			strcat(errMsg, " ");
			strcat(errMsg, javaMinVer);
			if (*javaMaxVer) {
				strcat(errMsg, " - ");
				strcat(errMsg, javaMaxVer);
			}
			loadString(DOWNLOAD_URL, errUrl);
			return FALSE;
		}
		if (!isJrePathOk(cmd)) {
			loadString(LAUNCHER_ERR, errMsg);
			return FALSE;
		}
	}

    // Append a path to the Path environment variable
	char jreBinPath[_MAX_PATH];
	strcpy(jreBinPath, cmd);
	strcat(jreBinPath, "\\bin");
	if (!appendToPathVar(jreBinPath)) {
		return FALSE;
	}

	// Set environment variables
	char envVars[MAX_VAR_SIZE] = {0};
	loadString(ENV_VARIABLES, envVars);
	char *var = strtok(envVars, "\t");
	while (var != NULL) {
		char *varValue = strchr(var, '=');
		*varValue++ = 0;
		*tmp = 0;
		expandVars(tmp, varValue, exePath, pathLen);
		debug("Set var:\t%s = %s\n", var, tmp);
		SetEnvironmentVariable(var, tmp);
		var = strtok(NULL, "\t");
	}
	*tmp = 0;

	// Process priority
	priority = loadInt(PRIORITY_CLASS);

	// Custom process name
	const BOOL setProcName = loadBool(SET_PROC_NAME)
			&& strstr(lpCmdLine, "--l4j-default-proc") == NULL;
	const BOOL wrapper = loadBool(WRAPPER);

    char jdk_path[_MAX_PATH] = {0};  // fry
    strcpy(jdk_path, cmd);
    //msgBox(jdk_path);

	appendLauncher(setProcName, exePath, pathLen, cmd);

	// Heap sizes
	appendHeapSizes(args);

    // JVM options
	if (loadString(JVM_OPTIONS, tmp)) {
		strcat(tmp, " ");
	} else {
        *tmp = 0;
    }
	/*
	 * Load additional JVM options from .l4j.ini file
	 * Options are separated by spaces or CRLF
	 * # starts an inline comment
	 */
	strncpy(tmp_path, exePath, strlen(exePath) - 3);
	strcat(tmp_path, "l4j.ini");
	long hFile;
	if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) {
		const int jvmOptLen = strlen(tmp);
		char* src = tmp + jvmOptLen;
		char* dst = src;
		const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR);
		BOOL copy = TRUE;
		int i;
		for (i = 0; i < len; i++, src++) {
			if (*src == '#') {
				copy = FALSE;
			} else if (*src == 13 || *src == 10) {
				copy = TRUE;
				if (dst > tmp && *(dst - 1) != ' ') {
					*dst++ = ' ';
				}
			} else if (copy) {
				*dst++ = *src;
			}
		}
		*dst = 0;
		if (len > 0 && *(dst - 1) != ' ') {
			strcat(tmp, " ");
		}
		_close(hFile);
	}

    // Expand environment %variables%
	expandVars(args, tmp, exePath, pathLen);

	// MainClass + Classpath or Jar
	char mainClass[STR] = {0};
	char jar[_MAX_PATH] = {0};
	loadString(JAR, jar);
	if (loadString(MAIN_CLASS, mainClass)) {
		if (!loadString(CLASSPATH, tmp)) {
			return FALSE;
		}
		char exp[MAX_ARGS] = {0};
		expandVars(exp, tmp, exePath, pathLen);
		strcat(args, "-classpath \"");
		if (wrapper) {
			appendAppClasspath(args, exePath, exp);
		} else if (*jar) {
			appendAppClasspath(args, jar, exp);
		}

	// add tools.jar for JDK  [fry]
	char tools[_MAX_PATH] = { 0 };
	sprintf(tools, "%s\\lib\\tools.jar", jdk_path);
	appendAppClasspath(args, tools, exp);

		// Deal with wildcards or >> strcat(args, exp); <<
		char* cp = strtok(exp, ";");
		while(cp != NULL) {
			debug("Add classpath:\t%s\n", cp);
			if (strpbrk(cp, "*?") != NULL) {
				int len = strrchr(cp, '\\') - cp + 1;
				strncpy(tmp_path, cp, len);
				char* filename = tmp_path + len;
				*filename = 0;
				struct _finddata_t c_file;
				long hFile;
				if ((hFile = _findfirst(cp, &c_file)) != -1L) {
					do {
						strcpy(filename, c_file.name);
						strcat(args, tmp_path);
						strcat(args, ";");
						debug("      \"      :\t%s\n", tmp_path);
					} while (_findnext(hFile, &c_file) == 0);
				}
				_findclose(hFile);
			} else {
				strcat(args, cp);
				strcat(args, ";");
			}
			cp = strtok(NULL, ";");
		}
		*(args + strlen(args) - 1) = 0;

		strcat(args, "\" ");
		strcat(args, mainClass);
	} else if (wrapper) {
       	strcat(args, "-jar \"");
		strcat(args, exePath);
   		strcat(args, "\"");
    } else {
       	strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
       	strcat(args, "\"");
    }

	// Constant command line args
	if (loadString(CMD_LINE, tmp)) {
		strcat(args, " ");
		strcat(args, tmp);
	}

	// Command line args
	if (*lpCmdLine) {
		strcpy(tmp, lpCmdLine);
		char* dst;
		while ((dst = strstr(tmp, "--l4j-")) != NULL) {
			char* src = strchr(dst, ' ');
			if (src == NULL || *(src + 1) == 0) {
				*dst = 0;
			} else {
				strcpy(dst, src + 1);
			}
		}
		if (*tmp) {
			strcat(args, " ");
			strcat(args, tmp);
		}
	}

	debug("Launcher:\t%s\n", cmd);
	debug("Launcher args:\t%s\n", args);
	debug("Args length:\t%d/32768 chars\n", strlen(args));
	return TRUE;
}
Example #11
0
int main (int argc, char* argv[])
{
	
	HANDLE				printer;
	int					fd;
	BYTE				buffer[256];
	DWORD				bytes, wrote;
	DOC_INFO_1			buffer1;
	PRINTER_DEFAULTS	print_defaults;

	if (argc < 3)
	{
		fprintf (stderr, "useage: %s <printername> <filename>\n", argv[0]);
		exit (-1);
	}

	printf ("This test program exercises the following win32 functions:\n");
	printf ("\tResetPrinter()\n");
	printf ("\tStartDocPrinter()\n");
	printf ("\tEndDocPrinter()\n");
	printf ("\tStartPagePrinter()\n");
	printf ("\tEndPagePrinter()\n");
	printf ("\tWritePrinter()\n");
	printf ("\n\n");

	printf ("This test program exercises both the StartPagePrinter()\n");
	printf ("and EndPagePrinter() Win32 functions.\n\n");

	if (!OpenPrinter (argv[1], &printer, NULL))
	{
		fprintf (stderr, "Unable to open %s!\n", argv[1]);
		exit (-1);
	}
	else
	{
		printf ("Printer [%s] opened successfully.\n\n", argv[1]);
	}

	/* set the printer defaults */
	print_defaults.pDatatype		= strdup ("RAW");
	print_defaults.DesiredAccess	= NULL;
	print_defaults.pDevMode			= NULL;
	if (ResetPrinter(printer, &print_defaults))
		printf ("ResetPrinter call succeeded\n");
	else
		PrintLastError();
	printf ("\n");

	/* StartDocPrinter */
	buffer1.pDocName	= strdup("Testing Printer");
	buffer1.pDatatype	= strdup("RAW");
	buffer1.pOutputFile	= NULL;

	printf ("Attempting to call StartDocPrinter() using DOC_INFO_1 :\n");
	print_doc_info_1 (&buffer1);
	printf ("\n");

	if (StartDocPrinter (printer, 1, (LPBYTE)&buffer1))
		printf ("StartDocPrinter called successfully\n");
	else
		PrintLastError();
	printf ("\n");


	if (StartPagePrinter(printer))
	{
		printf ("StartPagePrinter returned success.\n");

		if ((fd=_open(argv[2], _O_RDONLY)) == -1)
		{
			fprintf (stderr, "ERROR: Unable to open [%s] for read access!\n", argv[2]);
			ClosePrinter (printer);
			exit (-1);
		}

		while ((bytes=_read(fd, buffer, 256)) != 0)
		{
			if (!WritePrinter(printer, (LPVOID)buffer, bytes, &wrote))
			{
				fprintf (stderr, "ERROR: WritePrinter failed for [%d] bytes!\n", bytes);
				PrintLastError();
			}
			else
				printf ("Successfully wrote [%d] bytes to the printer\n", bytes);
		}
		_close (fd);

		if (EndPagePrinter (printer))
			printf ("EndPagePrinter returned success.\n");
		else
			PrintLastError();
	}
	else
		PrintLastError();
	printf ("\n");
			
	printf ("Attempting to call EndDocPrinter\n");
	if (EndDocPrinter (printer))
		printf ("EndDocPrinter called successfully\n");
	else
		PrintLastError();
	printf ("\n");



	if (!ClosePrinter(printer))
	{
		fprintf (stderr, "Error closing printer!\n");
		exit (-1);
	}
	else
	{
		printf ("Printer [%s] closed successfully.\n", argv[1]);
	}

	return 0;

}
Example #12
0
int mxf_page_file_forward_truncate(MXFPageFile *mxfPageFile)
{
    MXFFileSysData *sysData = mxfPageFile->mxfFile->sysData;
    int page = (int)(sysData->position / sysData->pageSize);
    int i;
    char filename[4096];
#if defined(_WIN32)
    int fileid;
#endif

    if (sysData->mode == READ_MODE)
    {
        mxf_log_error("Cannot forward truncate read-only mxf page file\n");
        return 0;
    }

    /* close and truncate to zero length page files before the current one */
    for (i = 0; i < page; i++)
    {
        if (sysData->pages[i].wasRemoved)
        {
            continue;
        }

        if (sysData->pages[i].fileDescriptor != NULL)
        {
            /* close the file */
            disk_file_close(sysData->pages[i].fileDescriptor);

            /* remove the file descriptor from the list */
            if (sysData->fileDescriptorHead == sysData->pages[i].fileDescriptor)
            {
                sysData->fileDescriptorHead = sysData->fileDescriptorHead->next;
            }
            else
            {
                sysData->pages[i].fileDescriptor->prev->next = sysData->pages[i].fileDescriptor->next;
            }
            if (sysData->fileDescriptorTail == sysData->pages[i].fileDescriptor)
            {
                sysData->fileDescriptorTail = sysData->fileDescriptorTail->prev;
            }
            else
            {
                sysData->pages[i].fileDescriptor->next->prev = sysData->pages[i].fileDescriptor->prev;
            }
            SAFE_FREE(sysData->pages[i].fileDescriptor);
        }

        /* truncate the file to zero length */
        mxf_snprintf(filename, sizeof(filename), sysData->filenameTemplate, sysData->pages[i].index);

#if defined(_WIN32)
        /* WIN32 does not have truncate() so open the file with _O_TRUNC then close it */
        if ((fileid = _open(filename, _O_CREAT | _O_TRUNC, _S_IWRITE)) == -1 ||
            _close(fileid) == -1)
#else
        if (truncate(filename, 0) != 0)
#endif
        {
            mxf_log_warn("Failed to truncate '%s' to zero length: %s\n", filename, strerror(errno));
        }
        sysData->pages[i].wasRemoved = 1;
    }

    return 1;
}
Example #13
0
FILE *
freopen(const char *name, const char *mode, FILE *stream)
{
	register int i;
	int rwmode = 0, rwflags = 0;
	int fd, flags = stream->_flags & (_IONBF | _IOFBF | _IOLBF | _IOMYBUF);

	(void) fflush(stream);				/* ignore errors */
	(void) _close(fileno(stream));

	switch(*mode++) {
	case 'r':
		flags |= _IOREAD;	
		rwmode = O_RDONLY;
		break;
	case 'w':
		flags |= _IOWRITE;
		rwmode = O_WRONLY;
		rwflags = O_CREAT | O_TRUNC;
		break;
	case 'a': 
		flags |= _IOWRITE | _IOAPPEND;
		rwmode = O_WRONLY;
		rwflags |= O_APPEND | O_CREAT;
		break;         
	default:
		return (FILE *)NULL;
	}

	while (*mode) {
		switch(*mode++) {
		case 'b':
			continue;
		case '+':
			rwmode = O_RDWR;
			flags |= _IOREAD | _IOWRITE;
			continue;
		/* The sequence may be followed by aditional characters */
		default:
			break;
		}
		break;
	}

	if ((rwflags & O_TRUNC)
	    || (((fd = _open(name, rwmode)) < 0)
		    && (rwflags & O_CREAT))) {
		if (((fd = _creat(name, PMODE)) < 0) && flags | _IOREAD) {
			(void) _close(fd);
			fd = _open(name, rwmode);
		}
	}

	if (fd < 0) {
		for( i = 0; i < FOPEN_MAX; i++) {
			if (stream == __iotab[i]) {
				__iotab[i] = 0;
				break;
			}
		}
		if (stream != stdin && stream != stdout && stream != stderr)
			free((void *)stream);
		return (FILE *)NULL;
	}

	stream->_count = 0;
	stream->_fd = fd;
	stream->_flags = flags;
	return stream;
}
Example #14
0
bool File::try_open(const char* filename, Mode mode)
{
	return _open(UTF8String(filename), mode, false);
}
bool VolHandleMgr::open (wchar_t Letter)
{
    return _open (Letter - L'A');
}
static int _mkstemp(const char * t){
  size_t l = strlen(t) + 1;
  char s[50];
  strncpy(s, t, l);
  return _mktemp_s(s, l) ? -1 : _open(s, _O_CREAT|_O_EXCL);
}
Example #17
0
int Tmr::open(int flags){
	return _open(PERIPH_NAME, flags);
}
Example #18
0
BOOL
AtaDiskInitialize(
	PNDEMU_DEV		EmuDev,
	PNDEMU_DEV		LowerDev,
	NDEMU_DEV_INIT	EmuDevInit
){
	PNDEMU_ATADISK_INIT	ataDiskInit = (PNDEMU_ATADISK_INIT)EmuDevInit;
	PATADISK_DEVCTX		ataDiskCtx;
	PCHAR				buffer;
	INT					iret;
	LONGLONG			loc;
	CHAR				fileNameBuffer[64];

	if(EmuDev == NULL)
		return FALSE;
	if(EmuDevInit == NULL)
		return FALSE;
	if(ataDiskInit->Capacity == 0)
		return FALSE;
	if(ataDiskInit->BytesInBlock == 0)
		return FALSE;

	//
	//	ATA disk only can stand alone.
	//

	if(LowerDev)
		return FALSE;

	EmuDev->LowerDevice = LowerDev;
	ataDiskCtx = (PATADISK_DEVCTX)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ATADISK_DEVCTX));
	if(ataDiskCtx == NULL)
		return FALSE;

	EmuDev->DevContext = (NDEMU_DEVCTX)ataDiskCtx;
	ataDiskCtx->DeviceId = ataDiskInit->DeviceId;
	ataDiskCtx->Capacity = ataDiskInit->Capacity;
	ataDiskCtx->BytesInBlock = ataDiskInit->BytesInBlock;
	ataDiskCtx->BytesInBlockBitShift = ataDiskInit->BytesInBlockBitShift;
	ataDiskCtx->LBA = TRUE;
	ataDiskCtx->LBA48 = TRUE;
	ataDiskCtx->PIO = 0;
	ataDiskCtx->MWDMA = 0x0407;
	ataDiskCtx->UDMA = 0x003f;


	//
	//	Open the disk file for this unit disk.
	//
	_snprintf(fileNameBuffer, 64, ATADISK_FILENAME_FORMAT, ataDiskCtx->DeviceId);

	ataDiskCtx->DiskFileHandle = _open(fileNameBuffer, _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);
	if(ataDiskCtx->DiskFileHandle < 0) {
		char	buffer[512];
		_int64	loc;

		//
		//	Create a file.
		//

		ataDiskCtx->DiskFileHandle = _open(fileNameBuffer, _O_RDWR | _O_CREAT | _O_BINARY, _S_IREAD | _S_IWRITE);
		if(ataDiskCtx->DiskFileHandle < 0) {
			printf("Can not open file '%s'\n", fileNameBuffer);
			return 1;
		}

	}

	//
	//	Write init DIB
	//
	buffer = (PCHAR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ataDiskCtx->BytesInBlock);
	loc = _lseeki64(	ataDiskCtx->DiskFileHandle,
						(ataDiskCtx->Capacity - 1) << ataDiskCtx->BytesInBlockBitShift,
						SEEK_SET);

	printf("Loc : %I64d\n", loc);
	iret = _write(ataDiskCtx->DiskFileHandle, buffer, ataDiskCtx->BytesInBlock);
	if(iret == -1) {
		perror( "Can not write ND" );
		return FALSE;
	}

	return TRUE;
}
Example #19
0
/* ARGSUSED */
DB *
__hash_open(const char *file, int flags, mode_t mode,
    const HASHINFO *info,	/* Special directives for create */
    int dflags)
{
	HTAB *hashp;
	struct stat statbuf;
	DB *dbp;
	int bpages, hdrsize, new_table, nsegs, save_errno;

	if ((flags & O_ACCMODE) == O_WRONLY) {
		errno = EINVAL;
		return (NULL);
	}

	if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
		return (NULL);
	hashp->fp = -1;

	/*
	 * Even if user wants write only, we need to be able to read
	 * the actual file, so we need to open it read/write. But, the
	 * field in the hashp structure needs to be accurate so that
	 * we can check accesses.
	 */
	hashp->flags = flags;

	if (file) {
		if ((hashp->fp = _open(file, flags, mode)) == -1)
			RETURN_ERROR(errno, error0);
		_fcntl(hashp->fp, F_SETFD, 1);
		new_table = _fstat(hashp->fp, &statbuf) == 0 &&
		    statbuf.st_size == 0 && (flags & O_ACCMODE) != O_RDONLY;
	} else
		new_table = 1;

	if (new_table) {
		if (!(hashp = init_hash(hashp, file, info)))
			RETURN_ERROR(errno, error1);
	} else {
		/* Table already exists */
		if (info && info->hash)
			hashp->hash = info->hash;
		else
			hashp->hash = __default_hash;

		hdrsize = _read(hashp->fp, &hashp->hdr, sizeof(HASHHDR));
#if BYTE_ORDER == LITTLE_ENDIAN
		swap_header(hashp);
#endif
		if (hdrsize == -1)
			RETURN_ERROR(errno, error1);
		if (hdrsize != sizeof(HASHHDR))
			RETURN_ERROR(EFTYPE, error1);
		/* Verify file type, versions and hash function */
		if (hashp->MAGIC != HASHMAGIC)
			RETURN_ERROR(EFTYPE, error1);
#define	OLDHASHVERSION	1
		if (hashp->VERSION != HASHVERSION &&
		    hashp->VERSION != OLDHASHVERSION)
			RETURN_ERROR(EFTYPE, error1);
		if ((int32_t)hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY)
			RETURN_ERROR(EFTYPE, error1);
		/*
		 * Figure out how many segments we need.  Max_Bucket is the
		 * maximum bucket number, so the number of buckets is
		 * max_bucket + 1.
		 */
		nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
			 hashp->SGSIZE;
		if (alloc_segs(hashp, nsegs))
			/*
			 * If alloc_segs fails, table will have been destroyed
			 * and errno will have been set.
			 */
			return (NULL);
		/* Read in bitmaps */
		bpages = (hashp->SPARES[hashp->OVFL_POINT] +
		    (hashp->BSIZE << BYTE_SHIFT) - 1) >>
		    (hashp->BSHIFT + BYTE_SHIFT);

		hashp->nmaps = bpages;
		memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *));
	}

	/* Initialize Buffer Manager */
	if (info && info->cachesize)
		__buf_init(hashp, info->cachesize);
	else
		__buf_init(hashp, DEF_BUFSIZE);

	hashp->new_file = new_table;
	hashp->save_file = file && (hashp->flags & O_RDWR);
	hashp->cbucket = -1;
	if (!(dbp = (DB *)malloc(sizeof(DB)))) {
		save_errno = errno;
		hdestroy(hashp);
		errno = save_errno;
		return (NULL);
	}
	dbp->internal = hashp;
	dbp->close = hash_close;
	dbp->del = hash_delete;
	dbp->fd = hash_fd;
	dbp->get = hash_get;
	dbp->put = hash_put;
	dbp->seq = hash_seq;
	dbp->sync = hash_sync;
	dbp->type = DB_HASH;

#ifdef DEBUG
	fprintf(stderr,
"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
	    "init_htab:",
	    "TABLE POINTER   ", hashp,
	    "BUCKET SIZE     ", hashp->BSIZE,
	    "BUCKET SHIFT    ", hashp->BSHIFT,
	    "DIRECTORY SIZE  ", hashp->DSIZE,
	    "SEGMENT SIZE    ", hashp->SGSIZE,
	    "SEGMENT SHIFT   ", hashp->SSHIFT,
	    "FILL FACTOR     ", hashp->FFACTOR,
	    "MAX BUCKET      ", hashp->MAX_BUCKET,
	    "OVFL POINT	     ", hashp->OVFL_POINT,
	    "LAST FREED      ", hashp->LAST_FREED,
	    "HIGH MASK       ", hashp->HIGH_MASK,
	    "LOW  MASK       ", hashp->LOW_MASK,
	    "NSEGS           ", hashp->nsegs,
	    "NKEYS           ", hashp->NKEYS);
#endif
#ifdef HASH_STATISTICS
	hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
#endif
	return (dbp);

error1:
	if (hashp != NULL)
		_close(hashp->fp);

error0:
	free(hashp);
	errno = save_errno;
	return (NULL);
}
Example #20
0
File: tee.c Project: ahundiak/isdp
int	main(int argc, char *argv[])
{
	char	buf[BUFSIZE];
	int	bytes = -1;
	int	append = 0;	/* append stdin to existing file. */
	int	file = 1;	/* index into argv of filename. */
	int	oflag;		/* flags for _open call. */
	int	ofh;		/* output file handle. */
	
	/*
	*	Process the command line args.
	*/
	
	oflag = _O_CREAT | _O_BINARY | _O_WRONLY;

	if (argc <= 1)
		usage();
	else
	{
		if ('-' == argv[1][0] || '/' == argv[1][0])
		{
			/*
			*	Check for append switch.
			*/

			file = 2;
			if ('a' != argv[1][1])
				usage();
			else
			{
				append = 1;
				oflag |= _O_APPEND;
			}
		}
		if (!argv[file])
			usage();
			
		if (-1 == (ofh = _open(argv[file], oflag, _S_IREAD | _S_IWRITE)))
		{
			fprintf(stderr, "%s: error: %s: unable to open for write: ", Image, argv[file]);
			perror(0);
			exit(++Errors);
		}
	}

	while (bytes = _read(_fileno(stdin), buf, BUFSIZE))
	{
		if (-1 == bytes)
		{
			if (EPIPE == errno)
			{
				/*
				*	EOF on a pipe.
				*/
				break;
			}
			fprintf(stderr, "%s: error %d: reading from stdin: ", Image, errno);
			perror(0);
			_close(ofh);
			exit(++Errors);
		}
		if (bytes != _write(_fileno(stdout), buf, bytes))
		{
			fprintf(stderr, "%s: error: writing %d bytes to stdout: ", Image, bytes);
			perror(0);
			_close(ofh);
			exit(++Errors);
		}
		if (bytes != _write(ofh, buf, bytes))
		{
			fprintf(stderr, "%s: error: %s: writing %d bytes: ", Image, argv[file], bytes);
			perror(0);
			_close(ofh);
			exit(++Errors);
		}
	}

	_close(ofh);	
	exit(Errors);
	return Errors;
}	
Example #21
0
File: fs.c Project: ebugsky/node
void fs__open(uv_fs_t* req, const char* path, int flags, int mode) {
  int result = _open(path, flags, mode);
  SET_REQ_RESULT(req, result);
}
Example #22
0
DB *
__rec_open(const char *fname, int flags, mode_t mode, const RECNOINFO *openinfo,
    int dflags)
{
	BTREE *t;
	BTREEINFO btopeninfo;
	DB *dbp;
	PAGE *h;
	struct stat sb;
	int rfd, sverrno;

	/* Open the user's file -- if this fails, we're done. */
	if (fname != NULL && (rfd = _open(fname, flags, mode)) < 0)
		return (NULL);

	/* Create a btree in memory (backed by disk). */
	dbp = NULL;
	if (openinfo) {
		if (openinfo->flags & ~(R_FIXEDLEN | R_NOKEY | R_SNAPSHOT))
			goto einval;
		btopeninfo.flags = 0;
		btopeninfo.cachesize = openinfo->cachesize;
		btopeninfo.maxkeypage = 0;
		btopeninfo.minkeypage = 0;
		btopeninfo.psize = openinfo->psize;
		btopeninfo.compare = NULL;
		btopeninfo.prefix = NULL;
		btopeninfo.lorder = openinfo->lorder;
		dbp = __bt_open(openinfo->bfname,
		    O_RDWR, S_IRUSR | S_IWUSR, &btopeninfo, dflags);
	} else
		dbp = __bt_open(NULL, O_RDWR, S_IRUSR | S_IWUSR, NULL, dflags);
	if (dbp == NULL)
		goto err;

	/*
	 * Some fields in the tree structure are recno specific.  Fill them
	 * in and make the btree structure look like a recno structure.  We
	 * don't change the bt_ovflsize value, it's close enough and slightly
	 * bigger.
	 */
	t = dbp->internal;
	if (openinfo) {
		if (openinfo->flags & R_FIXEDLEN) {
			F_SET(t, R_FIXLEN);
			t->bt_reclen = openinfo->reclen;
			if (t->bt_reclen == 0)
				goto einval;
		}
		t->bt_bval = openinfo->bval;
	} else
		t->bt_bval = '\n';

	F_SET(t, R_RECNO);
	if (fname == NULL)
		F_SET(t, R_EOF | R_INMEM);
	else
		t->bt_rfd = rfd;

	if (fname != NULL) {
		/*
		 * In 4.4BSD, stat(2) returns true for ISSOCK on pipes.
		 * Unfortunately, that's not portable, so we use lseek
		 * and check the errno values.
		 */
		errno = 0;
		if (lseek(rfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) {
			switch (flags & O_ACCMODE) {
			case O_RDONLY:
				F_SET(t, R_RDONLY);
				break;
			default:
				goto einval;
			}
slow:			if ((t->bt_rfp = fdopen(rfd, "r")) == NULL)
				goto err;
			F_SET(t, R_CLOSEFP);
			t->bt_irec =
			    F_ISSET(t, R_FIXLEN) ? __rec_fpipe : __rec_vpipe;
		} else {
			switch (flags & O_ACCMODE) {
			case O_RDONLY:
				F_SET(t, R_RDONLY);
				break;
			case O_RDWR:
				break;
			default:
				goto einval;
			}

			if (_fstat(rfd, &sb))
				goto err;
			/*
			 * Kluge -- we'd like to test to see if the file is too
			 * big to mmap.  Since, we don't know what size or type
			 * off_t's or size_t's are, what the largest unsigned
			 * integral type is, or what random insanity the local
			 * C compiler will perpetrate, doing the comparison in
			 * a portable way is flatly impossible.  Hope that mmap
			 * fails if the file is too large.
			 */
			if (sb.st_size == 0)
				F_SET(t, R_EOF);
			else {
#ifdef MMAP_NOT_AVAILABLE
				/*
				 * XXX
				 * Mmap doesn't work correctly on many current
				 * systems.  In particular, it can fail subtly,
				 * with cache coherency problems.  Don't use it
				 * for now.
				 */
				t->bt_msize = sb.st_size;
				if ((t->bt_smap = mmap(NULL, t->bt_msize,
				    PROT_READ, MAP_PRIVATE, rfd,
				    (off_t)0)) == MAP_FAILED)
					goto slow;
				t->bt_cmap = t->bt_smap;
				t->bt_emap = t->bt_smap + sb.st_size;
				t->bt_irec = F_ISSET(t, R_FIXLEN) ?
				    __rec_fmap : __rec_vmap;
				F_SET(t, R_MEMMAPPED);
#else
				goto slow;
#endif
			}
		}
	}

	/* Use the recno routines. */
	dbp->close = __rec_close;
	dbp->del = __rec_delete;
	dbp->fd = __rec_fd;
	dbp->get = __rec_get;
	dbp->put = __rec_put;
	dbp->seq = __rec_seq;
	dbp->sync = __rec_sync;

	/* If the root page was created, reset the flags. */
	if ((h = mpool_get(t->bt_mp, P_ROOT, 0)) == NULL)
		goto err;
	if ((h->flags & P_TYPE) == P_BLEAF) {
		F_CLR(h, P_TYPE);
		F_SET(h, P_RLEAF);
		mpool_put(t->bt_mp, h, MPOOL_DIRTY);
	} else
		mpool_put(t->bt_mp, h, 0);

	if (openinfo && openinfo->flags & R_SNAPSHOT &&
	    !F_ISSET(t, R_EOF | R_INMEM) &&
	    t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR)
		goto err;
	return (dbp);

einval:	errno = EINVAL;
err:	sverrno = errno;
	if (dbp != NULL)
		__bt_close(dbp);
	if (fname != NULL)
		_close(rfd);
	errno = sverrno;
	return (NULL);
}
Example #23
0
FTS *
__fts_open_44bsd(char * const *argv, int options,
    int (*compar)(const FTSENT * const *, const FTSENT * const *))
{
	struct _fts_private *priv;
	FTS *sp;
	FTSENT *p, *root;
	int nitems;
	FTSENT *parent, *tmp;
	int len;

	/* Options check. */
	if (options & ~FTS_OPTIONMASK) {
		errno = EINVAL;
		return (NULL);
	}

	/* Allocate/initialize the stream. */
	if ((priv = calloc(1, sizeof(*priv))) == NULL)
		return (NULL);
	sp = &priv->ftsp_fts;
	sp->fts_compar = compar;
	sp->fts_options = options;

	/* Shush, GCC. */
	tmp = NULL;

	/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
	if (ISSET(FTS_LOGICAL))
		SET(FTS_NOCHDIR);

	/*
	 * Start out with 1K of path space, and enough, in any case,
	 * to hold the user's paths.
	 */
	if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
		goto mem1;

	/* Allocate/initialize root's parent. */
	if ((parent = fts_alloc(sp, "", 0)) == NULL)
		goto mem2;
	parent->fts_level = FTS_ROOTPARENTLEVEL;

	/* Allocate/initialize root(s). */
	for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
		/* Don't allow zero-length paths. */
		if ((len = strlen(*argv)) == 0) {
			errno = ENOENT;
			goto mem3;
		}

		p = fts_alloc(sp, *argv, len);
		p->fts_level = FTS_ROOTLEVEL;
		p->fts_parent = parent;
		p->fts_accpath = p->fts_name;
		p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));

		/* Command-line "." and ".." are real directories. */
		if (p->fts_info == FTS_DOT)
			p->fts_info = FTS_D;

		/*
		 * If comparison routine supplied, traverse in sorted
		 * order; otherwise traverse in the order specified.
		 */
		if (compar) {
			p->fts_link = root;
			root = p;
		} else {
			p->fts_link = NULL;
			if (root == NULL)
				tmp = root = p;
			else {
				tmp->fts_link = p;
				tmp = p;
			}
		}
	}
	if (compar && nitems > 1)
		root = fts_sort(sp, root, nitems);

	/*
	 * Allocate a dummy pointer and make fts_read think that we've just
	 * finished the node before the root(s); set p->fts_info to FTS_INIT
	 * so that everything about the "current" node is ignored.
	 */
	if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
		goto mem3;
	sp->fts_cur->fts_link = root;
	sp->fts_cur->fts_info = FTS_INIT;

	/*
	 * If using chdir(2), grab a file descriptor pointing to dot to ensure
	 * that we can get back here; this could be avoided for some paths,
	 * but almost certainly not worth the effort.  Slashes, symbolic links,
	 * and ".." are all fairly nasty problems.  Note, if we can't get the
	 * descriptor we run anyway, just more slowly.
	 */
	if (!ISSET(FTS_NOCHDIR) &&
	    (sp->fts_rfd = _open(".", O_RDONLY | O_CLOEXEC, 0)) < 0)
		SET(FTS_NOCHDIR);

	return (sp);

mem3:	fts_lfree(root);
	free(parent);
mem2:	free(sp->fts_path);
mem1:	free(sp);
	return (NULL);
}
Example #24
0
/*
 *  This function extracts a file from a MPQ archive
 *  by the given number.
 */
int libmpq_file_extract(mpq_archive *mpq_a, const int number, const char *filename) {
	int blockindex = number; //-1;
	int fd = 0;
	int i = 0;
	char buffer[0x1000];
	//char tempfile[PATH_MAX];
	unsigned int transferred = 1;
	mpq_file *mpq_f = NULL;
	mpq_block *mpq_b = NULL;
	mpq_hash *mpq_h = NULL;

/*	if (number < 1 || number > mpq_a->header->blocktablesize) {
		return LIBMPQ_EINV_RANGE;
	}*/
/*
	sprintf(tempfile, libmpq_file_name(mpq_a, number));
*/
	/* check if mpq_f->filename could be written here. */
	fd = _open(filename, O_RDWR|O_CREAT|O_TRUNC, 0644);
	if (fd == LIBMPQ_EFILE) {
		return LIBMPQ_EFILE;
	}

	/* search for correct hashtable */
	/*for (i = 0; i < mpq_a->header->hashtablesize; i++) {
		if ((number - 1) == (mpq_a->hashtable[i]).blockindex) {
			blockindex = (mpq_a->hashtable[i]).blockindex;
			mpq_h = &(mpq_a->hashtable[i]);
			break;
		}
	}*/

	/* check if file was found */
	if (blockindex == -1 || blockindex > mpq_a->header->blocktablesize) {
		return LIBMPQ_EFILE_NOT_FOUND;
	}

	/* check if sizes are correct */
	mpq_b = mpq_a->blocktable + blockindex;
	if (mpq_b->filepos > (mpq_a->header->archivesize + mpq_a->mpqpos) || mpq_b->csize > mpq_a->header->archivesize) {
		return LIBMPQ_EFILE_CORRUPT;
	}

	/* check if file exists */
	if ((mpq_b->flags & LIBMPQ_FILE_EXISTS) == 0) {
		return LIBMPQ_EFILE_NOT_FOUND;
	}

	/* allocate memory for file structure */
	mpq_f = (mpq_file *)malloc(sizeof(mpq_file));
	if (!mpq_f) {
		return LIBMPQ_EALLOCMEM;
	}

	/* initialize file structure */
	memset(mpq_f, 0, sizeof(mpq_file));
	mpq_f->fd             = fd;
	mpq_f->mpq_b          = mpq_b;
	mpq_f->nblocks        = (mpq_f->mpq_b->fsize + mpq_a->blocksize - 1) / mpq_a->blocksize;
	mpq_f->mpq_h          = mpq_h;
	mpq_f->accessed       = FALSE;
	mpq_f->blockposloaded = FALSE;
	sprintf((char *)mpq_f->filename, filename);

	/* allocate buffers for decompression. */
	if (mpq_f->mpq_b->flags & LIBMPQ_FILE_COMPRESSED) {

		/*
		 *  Allocate buffer for block positions. At the begin of file are stored
		 *  unsigned ints holding positions of each block relative from begin of
		 *  file in the archive.
		 */
		if ((mpq_f->blockpos = (unsigned int *)malloc(sizeof(int) * mpq_f->nblocks + 1)) == NULL) {
			return LIBMPQ_EALLOCMEM;
		}
	}

	while (transferred > 0) {
		transferred = libmpq_file_read_file(mpq_a, mpq_f, mpq_f->filepos, buffer, sizeof(buffer));
		if (transferred == 0) {
			break;
		} else {
			mpq_f->accessed  = TRUE;
			mpq_f->filepos  += transferred;
		}

		transferred = _write(mpq_f->fd, buffer, transferred);
		if (transferred == 0) {
			break;
		}
	}

	_close(fd);

	/* freeing the file structure */
	free(mpq_f);
	return LIBMPQ_TOOLS_SUCCESS;
}
Example #25
0
FTSENT *
__fts_children_44bsd(FTS *sp, int instr)
{
	FTSENT *p;
	int fd;

	if (instr != 0 && instr != FTS_NAMEONLY) {
		errno = EINVAL;
		return (NULL);
	}

	/* Set current node pointer. */
	p = sp->fts_cur;

	/*
	 * Errno set to 0 so user can distinguish empty directory from
	 * an error.
	 */
	errno = 0;

	/* Fatal errors stop here. */
	if (ISSET(FTS_STOP))
		return (NULL);

	/* Return logical hierarchy of user's arguments. */
	if (p->fts_info == FTS_INIT)
		return (p->fts_link);

	/*
	 * If not a directory being visited in pre-order, stop here.  Could
	 * allow FTS_DNR, assuming the user has fixed the problem, but the
	 * same effect is available with FTS_AGAIN.
	 */
	if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
		return (NULL);

	/* Free up any previous child list. */
	if (sp->fts_child != NULL)
		fts_lfree(sp->fts_child);

	if (instr == FTS_NAMEONLY) {
		SET(FTS_NAMEONLY);
		instr = BNAMES;
	} else
		instr = BCHILD;

	/*
	 * If using chdir on a relative path and called BEFORE fts_read does
	 * its chdir to the root of a traversal, we can lose -- we need to
	 * chdir into the subdirectory, and we don't know where the current
	 * directory is, so we can't get back so that the upcoming chdir by
	 * fts_read will work.
	 */
	if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
	    ISSET(FTS_NOCHDIR))
		return (sp->fts_child = fts_build(sp, instr));

	if ((fd = _open(".", O_RDONLY | O_CLOEXEC, 0)) < 0)
		return (NULL);
	sp->fts_child = fts_build(sp, instr);
	if (fchdir(fd))
		return (NULL);
	(void)_close(fd);
	return (sp->fts_child);
}
Example #26
0
/*
 *  This function reads a file and verify if it is a legit MPQ archive
 *  or not. Then it fills the mpq_header structure and reads the hash
 *  table.
 */
int libmpq_archive_open(mpq_archive *mpq_a, unsigned char *mpq_filename) {
	int fd = 0;
	int rb = 0;
	int ncnt = FALSE;
	struct stat fileinfo;

	/* allocate memory */
	mpq_a->mpq_l = (mpq_list *)malloc(sizeof(mpq_list));
	memset(mpq_a->mpq_l, 0, sizeof(mpq_list));
	mpq_a->header = (mpq_header *)malloc(sizeof(mpq_header));
	memset(mpq_a->header, 0, sizeof(mpq_header));

	/* Check if file exists and is readable */
	fd = _open((char *)mpq_filename, MPQ_FILE_OPEN_FLAGS);
	if (fd == LIBMPQ_EFILE) {
		return LIBMPQ_EFILE;
	}

	/* fill the structures with informations */
	strcpy((char *)mpq_a->filename, (char *)mpq_filename);
	libmpq_init_buffer(mpq_a);
	mpq_a->fd               = fd;
	mpq_a->header->id       = 0;
	mpq_a->maxblockindex    = 0;
	mpq_a->mpq_l->mpq_files = NULL;

    mpq_a->mpqpos = 0; //k

	while (!ncnt) {
		mpq_a->header->id = 0;
		#ifdef WIN32
			_lseeki64(mpq_a->fd, mpq_a->mpqpos, SEEK_SET);
		#else
			lseek64(mpq_a->fd, mpq_a->mpqpos, SEEK_SET);
		#endif
		rb = _read(mpq_a->fd, mpq_a->header, sizeof(mpq_header));

		/* if different number of bytes read, break the loop */
		if (rb != sizeof(mpq_header)) {
			return LIBMPQ_EFILE_FORMAT;
		}

		/* special offset for protected MPQs */
		if (mpq_a->header->offset == LIBMPQ_HEADER_W3M) {
			mpq_a->flags |= LIBMPQ_FLAG_PROTECTED;
			mpq_a->header->offset = sizeof(mpq_header);
		}

		/* if valid signature has been found, break the loop */
        if (mpq_a->header->id == LIBMPQ_ID_MPQ) {
            ncnt = true;
        }
        /*if (mpq_a->header->id == LIBMPQ_ID_MPQ &&
		    mpq_a->header->offset == sizeof(mpq_header) &&
		    mpq_a->header->hashtablepos < mpq_a->header->archivesize &&
		    mpq_a->header->blocktablepos < mpq_a->header->archivesize) {
			ncnt = TRUE;
		}*/

		/* move to the next possible offset */
		if (!ncnt) {
			mpq_a->mpqpos += 0x200;
		}
	}

	/* get the right positions of the hash table and the block table. */
	mpq_a->blocksize = (0x200 << mpq_a->header->blocksize);
	fstat(mpq_a->fd, &fileinfo);

	/* Normal MPQs must have position of */
	/*if (mpq_a->header->hashtablepos + mpq_a->mpqpos < fileinfo.st_size &&
	    mpq_a->header->blocktablepos + mpq_a->mpqpos < fileinfo.st_size) {
		mpq_a->header->hashtablepos  += mpq_a->mpqpos;
		mpq_a->header->blocktablepos += mpq_a->mpqpos;
	} else {
		return LIBMPQ_EFILE_FORMAT;
	}*/

	/* Try to read and decrypt the hashtable */
	if (libmpq_read_hashtable(mpq_a) != 0) {
		return LIBMPQ_EHASHTABLE;
	}

	/* Try to read and decrypt the blocktable */
	if (libmpq_read_blocktable(mpq_a) != 0) {
		return LIBMPQ_EBLOCKTABLE;
	}

	return LIBMPQ_TOOLS_SUCCESS;
}
Example #27
0
void djvDpxLoad::read(djvImage & image, const djvImageIoFrameInfo & frame)
    throw (djvError)
{
    //DJV_DEBUG("djvDpxLoad::read");
    //DJV_DEBUG_PRINT("frame = " << frame);

    // Open the file.

    const QString fileName =
        _file.fileName(frame.frame != -1 ? frame.frame : _file.sequence().start());

    //DJV_DEBUG_PRINT("file name = " << fileName);

    djvImageIoInfo info;
    
    QScopedPointer<djvFileIo> io(new djvFileIo);
    
    _open(fileName, info, *io);

    image.tags = info.tags;
    
    // Set the color profile.

    if ((djvCineon::COLOR_PROFILE_FILM_PRINT == _options.inputColorProfile) ||
        (djvCineon::COLOR_PROFILE_AUTO == _options.inputColorProfile &&
            _filmPrint))
    {
        //DJV_DEBUG_PRINT("color profile");

        image.colorProfile.type = djvColorProfile::LUT;

        if (! _filmPrintLut.isValid())
        {
            _filmPrintLut = djvCineon::filmPrintToLinearLut(
                _options.inputFilmPrint);
        }

        image.colorProfile.lut = _filmPrintLut;
    }
    else
    {
        image.colorProfile = djvColorProfile();
    }

    // Read the file.

    io->readAhead();

    bool mmap = true;

    if ((io->size() - io->pos()) < djvPixelDataUtil::dataByteCount(info))
    {
        mmap = false;
    }
    
    //DJV_DEBUG_PRINT("mmap = " << mmap);
    
    if (mmap)
    {
        if (! frame.proxy)
        {
            image.set(info, io->mmapP(), io.data());

            io.take();
        }
        else
        {
            _tmp.set(info, io->mmapP());

            info.size = djvPixelDataUtil::proxyScale(info.size, frame.proxy);
            info.proxy = frame.proxy;

            image.set(info);

            djvPixelDataUtil::proxyScale(_tmp, image, frame.proxy);
        }
    }
    else
    {
        djvPixelData * data = frame.proxy ? &_tmp : &image;
        data->set(info);
        
        djvError error;
        bool     errorValid = false;
        
        try
        {
            for (int y = 0; y < info.size.y; ++y)
            {
                io->get(
                    data->data(0, y),
                    info.size.x * djvPixel::byteCount(info.pixel));
            }
        }
        catch (const djvError & otherError)
        {
            error      = otherError;
            errorValid = true;
        }
        
        if (frame.proxy)
        {
            info.size = djvPixelDataUtil::proxyScale(info.size, frame.proxy);
            info.proxy = frame.proxy;

            image.set(info);

            djvPixelDataUtil::proxyScale(_tmp, image, frame.proxy);
        }
        
        if (errorValid)
            throw error;
    }
    
    //DJV_DEBUG_PRINT("image = " << image);
}
bool VolHandleMgr::open (char Letter)
{
    return _open (Letter - 'A');
}
Example #29
0
/** Opens a file and return the file handle.
* This functions opens a file with read and write permission. 
* @param file	the file name to be opened.
* @return the file handle. If an error occurs, the return value is less than zero. 
* 
*/
int	RalOpenFile(const char * file)
{
    return _open(file, _O_BINARY | _O_RDWR);
}
Example #30
0
void File::open(const char* filename, Mode mode)
{
	_open(UTF8String(filename), mode, true);
}