file.c 105 KB
Newer Older
1 2 3 4 5 6 7
/*
 * msvcrt.dll file functions
 *
 * Copyright 1996,1998 Marcus Meissner
 * Copyright 1996 Jukka Iivonen
 * Copyright 1997,2000 Uwe Bonnes
 * Copyright 2000 Jon Griffiths
8
 * Copyright 2004 Eric Pouech
9
 * Copyright 2004 Juan Lang
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 25 26
 *
 * TODO
 * Use the file flag hints O_SEQUENTIAL, O_RANDOM, O_SHORT_LIVED
27
 */
28 29 30 31

#include "config.h"
#include "wine/port.h"

32
#include <time.h>
33
#include <stdarg.h>
34
#include <stdio.h>
35 36 37
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
38
#include <sys/types.h>
39

40 41
#include "windef.h"
#include "winbase.h"
42
#include "winternl.h"
43
#include "msvcrt.h"
44
#include "mtdll.h"
45

46
#include "wine/unicode.h"
47

48 49 50
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
51 52

/* for stat mode, permissions apply to all,owner and group */
53 54 55
#define ALL_S_IREAD  (MSVCRT__S_IREAD  | (MSVCRT__S_IREAD  >> 3) | (MSVCRT__S_IREAD  >> 6))
#define ALL_S_IWRITE (MSVCRT__S_IWRITE | (MSVCRT__S_IWRITE >> 3) | (MSVCRT__S_IWRITE >> 6))
#define ALL_S_IEXEC  (MSVCRT__S_IEXEC  | (MSVCRT__S_IEXEC  >> 3) | (MSVCRT__S_IEXEC  >> 6))
56 57

/* _access() bit flags FIXME: incomplete */
58
#define MSVCRT_W_OK      0x02
59
#define MSVCRT_R_OK      0x04
60

61
/* values for wxflag in file descriptor */
62 63
#define WX_OPEN           0x01
#define WX_ATEOF          0x02
64
#define WX_READEOF        0x04  /* like ATEOF, but for underlying file rather than buffer */
65
#define WX_READCR         0x08  /* underlying file is at \r */
66 67 68
#define WX_DONTINHERIT    0x10
#define WX_APPEND         0x20
#define WX_TEXT           0x80
69

70
/* FIXME: this should be allocated dynamically */
71
#define MSVCRT_MAX_FILES 2048
72
#define MSVCRT_FD_BLOCK_SIZE 32
73

74
/* ioinfo structure size is different in msvcrXX.dll's */
75
typedef struct {
76
    HANDLE              handle;
77
    unsigned char       wxflag;
78 79 80
    char                unk1;
    BOOL                crit_init;
    CRITICAL_SECTION    crit;
81 82
} ioinfo;

83 84
/*********************************************************************
 *		__pioinfo (MSVCRT.@)
85
 * array of pointers to ioinfo arrays [32]
86 87 88 89 90 91 92
 */
ioinfo * MSVCRT___pioinfo[MSVCRT_MAX_FILES/MSVCRT_FD_BLOCK_SIZE] = { 0 };

/*********************************************************************
 *		__badioinfo (MSVCRT.@)
 */
ioinfo MSVCRT___badioinfo = { INVALID_HANDLE_VALUE, WX_TEXT };
93

94 95 96
static int MSVCRT_fdstart = 3; /* first unallocated fd */
static int MSVCRT_fdend = 3; /* highest allocated fd */

97 98 99 100 101 102 103 104
typedef struct {
    MSVCRT_FILE file;
    CRITICAL_SECTION crit;
} file_crit;

MSVCRT_FILE MSVCRT__iob[_IOB_ENTRIES] = { { 0 } };
static file_crit* MSVCRT_fstream[MSVCRT_MAX_FILES/MSVCRT_FD_BLOCK_SIZE];
static int MSVCRT_max_streams = 512, MSVCRT_stream_idx;
105

106 107 108
/* INTERNAL: process umask */
static int MSVCRT_umask = 0;

109 110
/* INTERNAL: static data for tmpnam and _wtmpname functions */
static int tmpnam_unique;
111 112 113 114 115 116

static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';

117
#define TOUL(x) (ULONGLONG)(x)
118 119 120 121 122
static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');

123
/* This critical section protects the tables MSVCRT___pioinfo and MSVCRT_fstreams,
124 125 126 127 128 129 130
 * and their related indexes, MSVCRT_fdstart, MSVCRT_fdend,
 * and MSVCRT_stream_idx, from race conditions.
 * It doesn't protect against race conditions manipulating the underlying files
 * or flags; doing so would probably be better accomplished with per-file
 * protection, rather than locking the whole table for every change.
 */
static CRITICAL_SECTION MSVCRT_file_cs;
131 132 133 134 135 136 137
static CRITICAL_SECTION_DEBUG MSVCRT_file_cs_debug =
{
    0, 0, &MSVCRT_file_cs,
    { &MSVCRT_file_cs_debug.ProcessLocksList, &MSVCRT_file_cs_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": MSVCRT_file_cs") }
};
static CRITICAL_SECTION MSVCRT_file_cs = { &MSVCRT_file_cs_debug, -1, 0, 0, 0, 0 };
138 139
#define LOCK_FILES()    do { EnterCriticalSection(&MSVCRT_file_cs); } while (0)
#define UNLOCK_FILES()  do { LeaveCriticalSection(&MSVCRT_file_cs); } while (0)
140

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
static void msvcrt_stat64_to_stat(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stat *buf)
{
    buf->st_dev   = buf64->st_dev;
    buf->st_ino   = buf64->st_ino;
    buf->st_mode  = buf64->st_mode;
    buf->st_nlink = buf64->st_nlink;
    buf->st_uid   = buf64->st_uid;
    buf->st_gid   = buf64->st_gid;
    buf->st_rdev  = buf64->st_rdev;
    buf->st_size  = buf64->st_size;
    buf->st_atime = buf64->st_atime;
    buf->st_mtime = buf64->st_mtime;
    buf->st_ctime = buf64->st_ctime;
}

static void msvcrt_stat64_to_stati64(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stati64 *buf)
{
    buf->st_dev   = buf64->st_dev;
    buf->st_ino   = buf64->st_ino;
    buf->st_mode  = buf64->st_mode;
    buf->st_nlink = buf64->st_nlink;
    buf->st_uid   = buf64->st_uid;
    buf->st_gid   = buf64->st_gid;
    buf->st_rdev  = buf64->st_rdev;
    buf->st_size  = buf64->st_size;
    buf->st_atime = buf64->st_atime;
    buf->st_mtime = buf64->st_mtime;
    buf->st_ctime = buf64->st_ctime;
169
}
170

171 172 173 174 175 176 177 178 179 180
static void time_to_filetime( MSVCRT___time64_t time, FILETIME *ft )
{
    /* 1601 to 1970 is 369 years plus 89 leap days */
    static const __int64 secs_1601_to_1970 = ((369 * 365 + 89) * (__int64)86400);

    __int64 ticks = (time + secs_1601_to_1970) * 10000000;
    ft->dwHighDateTime = ticks >> 32;
    ft->dwLowDateTime = ticks;
}

181 182 183 184 185 186 187 188 189 190 191
static inline ioinfo* msvcrt_get_ioinfo(int fd)
{
    ioinfo *ret = NULL;
    if(fd < MSVCRT_MAX_FILES)
        ret = MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE];
    if(!ret)
        return &MSVCRT___badioinfo;

    return ret + (fd%MSVCRT_FD_BLOCK_SIZE);
}

192 193 194 195 196 197 198 199 200 201 202 203 204 205
static inline MSVCRT_FILE* msvcrt_get_file(int i)
{
    file_crit *ret;

    if(i >= MSVCRT_max_streams)
        return NULL;

    if(i < _IOB_ENTRIES)
        return &MSVCRT__iob[i];

    ret = MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE];
    if(!ret) {
        MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE] = MSVCRT_calloc(MSVCRT_FD_BLOCK_SIZE, sizeof(file_crit));
        if(!MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE]) {
206
            ERR("out of memory\n");
207 208 209 210 211 212 213 214 215 216 217
            *MSVCRT__errno() = MSVCRT_ENOMEM;
            return NULL;
        }

        ret = MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE] + (i%MSVCRT_FD_BLOCK_SIZE);
    } else
        ret += i%MSVCRT_FD_BLOCK_SIZE;

    return &ret->file;
}

218 219
static inline BOOL msvcrt_is_valid_fd(int fd)
{
220
    return fd >= 0 && fd < MSVCRT_fdend && (msvcrt_get_ioinfo(fd)->wxflag & WX_OPEN);
221 222
}

223 224 225 226 227 228
/* INTERNAL: Get the HANDLE for a fd
 * This doesn't lock the table, because a failure will result in
 * INVALID_HANDLE_VALUE being returned, which should be handled correctly.  If
 * it returns a valid handle which is about to be closed, a subsequent call
 * will fail, most likely in a sane way.
 */
229
static HANDLE msvcrt_fdtoh(int fd)
230
{
231
  if (!msvcrt_is_valid_fd(fd))
232 233
  {
    WARN(":fd (%d) - no handle!\n",fd);
234
    *MSVCRT___doserrno() = 0;
235
    *MSVCRT__errno() = MSVCRT_EBADF;
236
    return INVALID_HANDLE_VALUE;
237
  }
238
  if (msvcrt_get_ioinfo(fd)->handle == INVALID_HANDLE_VALUE)
239
      WARN("returning INVALID_HANDLE_VALUE for %d\n", fd);
240
  return msvcrt_get_ioinfo(fd)->handle;
241 242 243
}

/* INTERNAL: free a file entry fd */
244
static void msvcrt_free_fd(int fd)
245
{
246
  HANDLE old_handle;
247
  ioinfo *fdinfo;
248

249
  LOCK_FILES();
250 251 252 253 254 255 256
  fdinfo = msvcrt_get_ioinfo(fd);
  old_handle = fdinfo->handle;
  if(fdinfo != &MSVCRT___badioinfo)
  {
    fdinfo->handle = INVALID_HANDLE_VALUE;
    fdinfo->wxflag = 0;
  }
257
  TRACE(":fd (%d) freed\n",fd);
258 259 260 261
  if (fd < 3) /* don't use 0,1,2 for user files */
  {
    switch (fd)
    {
262 263 264 265 266 267 268 269 270
    case 0:
        if (GetStdHandle(STD_INPUT_HANDLE) == old_handle) SetStdHandle(STD_INPUT_HANDLE, 0);
        break;
    case 1:
        if (GetStdHandle(STD_OUTPUT_HANDLE) == old_handle) SetStdHandle(STD_OUTPUT_HANDLE, 0);
        break;
    case 2:
        if (GetStdHandle(STD_ERROR_HANDLE) == old_handle) SetStdHandle(STD_ERROR_HANDLE, 0);
        break;
271 272 273 274 275 276 277 278 279
    }
  }
  else
  {
    if (fd == MSVCRT_fdend - 1)
      MSVCRT_fdend--;
    if (fd < MSVCRT_fdstart)
      MSVCRT_fdstart = fd;
  }
280
  UNLOCK_FILES();
281 282
}

283
/* INTERNAL: Allocate an fd slot from a Win32 HANDLE, starting from fd */
284
/* caller must hold the files lock */
285
static int msvcrt_alloc_fd_from(HANDLE hand, int flag, int fd)
286
{
287 288
  ioinfo *fdinfo;

289 290 291
  if (fd >= MSVCRT_MAX_FILES)
  {
    WARN(":files exhausted!\n");
292
    *MSVCRT__errno() = MSVCRT_ENFILE;
293 294
    return -1;
  }
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

  fdinfo = msvcrt_get_ioinfo(fd);
  if(fdinfo == &MSVCRT___badioinfo) {
    int i;

    MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE] = MSVCRT_calloc(MSVCRT_FD_BLOCK_SIZE, sizeof(ioinfo));
    if(!MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE]) {
      WARN(":out of memory!\n");
      *MSVCRT__errno() = MSVCRT_ENOMEM;
      return -1;
    }

    for(i=0; i<MSVCRT_FD_BLOCK_SIZE; i++)
      MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE][i].handle = INVALID_HANDLE_VALUE;

    fdinfo = msvcrt_get_ioinfo(fd);
  }

  fdinfo->handle = hand;
  fdinfo->wxflag = WX_OPEN | (flag & (WX_DONTINHERIT | WX_APPEND | WX_TEXT));
315 316

  /* locate next free slot */
317 318
  if (fd == MSVCRT_fdstart && fd == MSVCRT_fdend)
    MSVCRT_fdstart = MSVCRT_fdend + 1;
319
  else
320
    while (MSVCRT_fdstart < MSVCRT_fdend &&
321
      msvcrt_get_ioinfo(MSVCRT_fdstart)->handle != INVALID_HANDLE_VALUE)
322
      MSVCRT_fdstart++;
323 324 325 326
  /* update last fd in use */
  if (fd >= MSVCRT_fdend)
    MSVCRT_fdend = fd + 1;
  TRACE("fdstart is %d, fdend is %d\n", MSVCRT_fdstart, MSVCRT_fdend);
327

328 329 330 331 332 333 334
  switch (fd)
  {
  case 0: SetStdHandle(STD_INPUT_HANDLE,  hand); break;
  case 1: SetStdHandle(STD_OUTPUT_HANDLE, hand); break;
  case 2: SetStdHandle(STD_ERROR_HANDLE,  hand); break;
  }

335 336 337
  return fd;
}

338 339 340
/* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
static int msvcrt_alloc_fd(HANDLE hand, int flag)
{
341 342 343
  int ret;

  LOCK_FILES();
344
  TRACE(":handle (%p) allocating fd (%d)\n",hand,MSVCRT_fdstart);
345 346 347
  ret = msvcrt_alloc_fd_from(hand, flag, MSVCRT_fdstart);
  UNLOCK_FILES();
  return ret;
348 349
}

350 351
/* INTERNAL: Allocate a FILE* for an fd slot */
/* caller must hold the files lock */
352 353
static MSVCRT_FILE* msvcrt_alloc_fp(void)
{
354
  unsigned int i;
355
  MSVCRT_FILE *file;
356

357
  for (i = 3; i < MSVCRT_max_streams; i++)
358
  {
359 360 361 362 363
    file = msvcrt_get_file(i);
    if (!file)
      return NULL;

    if (file->_flag == 0)
364
    {
365 366
      if (i == MSVCRT_stream_idx)
      {
367 368 369 370 371
          if (file<MSVCRT__iob || file>=MSVCRT__iob+_IOB_ENTRIES)
          {
              InitializeCriticalSection(&((file_crit*)file)->crit);
              ((file_crit*)file)->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": file_crit.crit");
          }
372 373
          MSVCRT_stream_idx++;
      }
374
      return file;
375 376
    }
  }
377

378 379 380 381 382
  return NULL;
}

/* INTERNAL: initialize a FILE* from an open fd */
static int msvcrt_init_fp(MSVCRT_FILE* file, int fd, unsigned stream_flags)
383 384
{
  TRACE(":fd (%d) allocating FILE*\n",fd);
385
  if (!msvcrt_is_valid_fd(fd))
386 387
  {
    WARN(":invalid fd %d\n",fd);
388
    *MSVCRT___doserrno() = 0;
389
    *MSVCRT__errno() = MSVCRT_EBADF;
390
    return -1;
391
  }
392 393 394 395 396 397
  memset(file, 0, sizeof(*file));
  file->_file = fd;
  file->_flag = stream_flags;

  TRACE(":got FILE* (%p)\n",file);
  return 0;
398 399
}

400 401 402 403 404 405
/* INTERNAL: Create an inheritance data block (for spawned process)
 * The inheritance block is made of:
 *      00      int     nb of file descriptor (NBFD)
 *      04      char    file flags (wxflag): repeated for each fd
 *      4+NBFD  HANDLE  file handle: repeated for each fd
 */
406
unsigned msvcrt_create_io_inherit_block(WORD *size, BYTE **block)
407 408 409 410
{
  int         fd;
  char*       wxflag_ptr;
  HANDLE*     handle_ptr;
411
  ioinfo*     fdinfo;
412

413 414 415
  *size = sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * MSVCRT_fdend;
  *block = MSVCRT_calloc(*size, 1);
  if (!*block)
416
  {
417
    *size = 0;
418 419
    return FALSE;
  }
420
  wxflag_ptr = (char*)*block + sizeof(unsigned);
421 422
  handle_ptr = (HANDLE*)(wxflag_ptr + MSVCRT_fdend * sizeof(char));

423
  *(unsigned*)*block = MSVCRT_fdend;
424 425 426
  for (fd = 0; fd < MSVCRT_fdend; fd++)
  {
    /* to be inherited, we need it to be open, and that DONTINHERIT isn't set */
427 428
    fdinfo = msvcrt_get_ioinfo(fd);
    if ((fdinfo->wxflag & (WX_OPEN | WX_DONTINHERIT)) == WX_OPEN)
429
    {
430 431
      *wxflag_ptr = fdinfo->wxflag;
      *handle_ptr = fdinfo->handle;
432 433 434 435 436 437 438 439 440 441
    }
    else
    {
      *wxflag_ptr = 0;
      *handle_ptr = INVALID_HANDLE_VALUE;
    }
    wxflag_ptr++; handle_ptr++;
  } 
  return TRUE;
}
442

443 444 445
/* INTERNAL: Set up all file descriptors, 
 * as well as default streams (stdin, stderr and stdout) 
 */
446
void msvcrt_init_io(void)
447
{
448 449
  STARTUPINFOA  si;
  int           i;
450
  ioinfo        *fdinfo;
451

452
  GetStartupInfoA(&si);
453
  if (si.cbReserved2 >= sizeof(unsigned int) && si.lpReserved2 != NULL)
454
  {
455
    BYTE*       wxflag_ptr;
456
    HANDLE*     handle_ptr;
457
    unsigned int count;
458

459 460 461
    count = *(unsigned*)si.lpReserved2;
    wxflag_ptr = si.lpReserved2 + sizeof(unsigned);
    handle_ptr = (HANDLE*)(wxflag_ptr + count);
462

463
    count = min(count, (si.cbReserved2 - sizeof(unsigned)) / (sizeof(HANDLE) + 1));
464
    count = min(count, MSVCRT_MAX_FILES);
465
    for (i = 0; i < count; i++)
466 467
    {
      if ((*wxflag_ptr & WX_OPEN) && *handle_ptr != INVALID_HANDLE_VALUE)
468 469
        msvcrt_alloc_fd_from(*handle_ptr, *wxflag_ptr, i);

470 471
      wxflag_ptr++; handle_ptr++;
    }
472
    MSVCRT_fdend = max( 3, count );
473
    for (MSVCRT_fdstart = 3; MSVCRT_fdstart < MSVCRT_fdend; MSVCRT_fdstart++)
474
        if (msvcrt_get_ioinfo(MSVCRT_fdstart)->handle == INVALID_HANDLE_VALUE) break;
475 476
  }

477 478 479 480 481
  if(!MSVCRT___pioinfo[0])
      msvcrt_alloc_fd_from(INVALID_HANDLE_VALUE, 0, 3);

  fdinfo = msvcrt_get_ioinfo(0);
  if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE)
482
  {
483 484
      HANDLE std = GetStdHandle(STD_INPUT_HANDLE);
      if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
485
                                                         GetCurrentProcess(), &fdinfo->handle,
486
                                                         0, TRUE, DUPLICATE_SAME_ACCESS))
487
          fdinfo->wxflag = WX_OPEN | WX_TEXT;
488
  }
489 490 491

  fdinfo = msvcrt_get_ioinfo(1);
  if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE)
492
  {
493 494
      HANDLE std = GetStdHandle(STD_OUTPUT_HANDLE);
      if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
495
                                                         GetCurrentProcess(), &fdinfo->handle,
496
                                                         0, TRUE, DUPLICATE_SAME_ACCESS))
497
          fdinfo->wxflag = WX_OPEN | WX_TEXT;
498
  }
499 500 501

  fdinfo = msvcrt_get_ioinfo(2);
  if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE)
502
  {
503 504
      HANDLE std = GetStdHandle(STD_ERROR_HANDLE);
      if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
505
                                                         GetCurrentProcess(), &fdinfo->handle,
506
                                                         0, TRUE, DUPLICATE_SAME_ACCESS))
507
          fdinfo->wxflag = WX_OPEN | WX_TEXT;
508
  }
509

510 511
  TRACE(":handles (%p)(%p)(%p)\n", msvcrt_get_ioinfo(0)->handle,
	msvcrt_get_ioinfo(1)->handle, msvcrt_get_ioinfo(2)->handle);
512

513
  memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
514 515 516 517
  for (i = 0; i < 3; i++)
  {
    /* FILE structs for stdin/out/err are static and never deleted */
    MSVCRT__iob[i]._file = i;
518 519
    MSVCRT__iob[i]._tmpfname = NULL;
    MSVCRT__iob[i]._flag = (i == 0) ? MSVCRT__IOREAD : MSVCRT__IOWRT;
520
  }
521
  MSVCRT_stream_idx = 3;
522 523
}

524 525 526 527 528
/* INTERNAL: Flush stdio file buffer */
static int msvcrt_flush_buffer(MSVCRT_FILE* file)
{
  if(file->_bufsiz) {
        int cnt=file->_ptr-file->_base;
529
        if(cnt>0 && MSVCRT__write(file->_file, file->_base, cnt) != cnt) {
530 531
            file->_flag |= MSVCRT__IOERR;
            return MSVCRT_EOF;
532 533 534 535 536 537 538 539 540 541 542 543 544 545
        }
        file->_ptr=file->_base;
        file->_cnt=file->_bufsiz;
  }
  return 0;
}

/* INTERNAL: Allocate stdio file buffer */
static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
{
	file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
	if(file->_base) {
		file->_bufsiz = MSVCRT_BUFSIZ;
		file->_flag |= MSVCRT__IOMYBUF;
546
	} else {
Mike McCormack's avatar
Mike McCormack committed
547
		file->_base = (char*)(&file->_charbuf);
548 549 550 551 552 553 554
		/* put here 2 ??? */
		file->_bufsiz = sizeof(file->_charbuf);
	}
	file->_ptr = file->_base;
	file->_cnt = 0;
}

555
/* INTERNAL: Convert integer to base32 string (0-9a-v), 0 becomes "" */
556
static int msvcrt_int_to_base32(int num, char *str)
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
{
  char *p;
  int n = num;
  int digits = 0;

  while (n != 0)
  {
    n >>= 5;
    digits++;
  }
  p = str + digits;
  *p = 0;
  while (--p >= str)
  {
    *p = (num & 31) + '0';
    if (*p > '9')
      *p += ('a' - '0' - 10);
    num >>= 5;
  }
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

  return digits;
}

/* INTERNAL: wide character version of msvcrt_int_to_base32 */
static int msvcrt_int_to_base32_w(int num, MSVCRT_wchar_t *str)
{
    MSVCRT_wchar_t *p;
    int n = num;
    int digits = 0;

    while (n != 0)
    {
        n >>= 5;
        digits++;
    }
    p = str + digits;
    *p = 0;
    while (--p >= str)
    {
        *p = (num & 31) + '0';
        if (*p > '9')
            *p += ('a' - '0' - 10);
        num >>= 5;
    }

    return digits;
603 604
}

605
/*********************************************************************
606
 *		__iob_func(MSVCRT.@)
607
 */
608
MSVCRT_FILE * CDECL MSVCRT___iob_func(void)
609 610 611 612 613 614 615
{
 return &MSVCRT__iob[0];
}

/*********************************************************************
 *		_access (MSVCRT.@)
 */
616
int CDECL MSVCRT__access(const char *filename, int mode)
617 618 619
{
  DWORD attr = GetFileAttributesA(filename);

620
  TRACE("(%s,%d) %d\n",filename,mode,attr);
621

622
  if (!filename || attr == INVALID_FILE_ATTRIBUTES)
623
  {
624
    msvcrt_set_errno(GetLastError());
625 626
    return -1;
  }
627
  if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
628
  {
629
    msvcrt_set_errno(ERROR_ACCESS_DENIED);
630 631 632 633 634
    return -1;
  }
  return 0;
}

635 636 637 638 639
/*********************************************************************
 *		_access_s (MSVCRT.@)
 */
int CDECL _access_s(const char *filename, int mode)
{
640 641
  if (!MSVCRT_CHECK_PMT(filename != NULL)) return -1;
  if (!MSVCRT_CHECK_PMT((mode & ~(MSVCRT_R_OK | MSVCRT_W_OK)) == 0)) return -1;
642 643 644 645

  return MSVCRT__access(filename, mode);
}

646 647 648
/*********************************************************************
 *		_waccess (MSVCRT.@)
 */
649
int CDECL MSVCRT__waccess(const MSVCRT_wchar_t *filename, int mode)
650 651 652
{
  DWORD attr = GetFileAttributesW(filename);

653
  TRACE("(%s,%d) %d\n",debugstr_w(filename),mode,attr);
654

655
  if (!filename || attr == INVALID_FILE_ATTRIBUTES)
656
  {
657
    msvcrt_set_errno(GetLastError());
658 659
    return -1;
  }
660
  if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
661
  {
662
    msvcrt_set_errno(ERROR_ACCESS_DENIED);
663 664 665 666
    return -1;
  }
  return 0;
}
667

668 669 670 671 672
/*********************************************************************
 *		_waccess_s (MSVCRT.@)
 */
int CDECL _waccess_s(const MSVCRT_wchar_t *filename, int mode)
{
673 674
  if (!MSVCRT_CHECK_PMT(filename != NULL)) return -1;
  if (!MSVCRT_CHECK_PMT((mode & ~(MSVCRT_R_OK | MSVCRT_W_OK)) == 0)) return -1;
675

676
  return MSVCRT__waccess(filename, mode);
677 678
}

679 680 681
/*********************************************************************
 *		_chmod (MSVCRT.@)
 */
682
int CDECL MSVCRT__chmod(const char *path, int flags)
683 684 685
{
  DWORD oldFlags = GetFileAttributesA(path);

686
  if (oldFlags != INVALID_FILE_ATTRIBUTES)
687
  {
688
    DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
689 690 691 692 693
      oldFlags | FILE_ATTRIBUTE_READONLY;

    if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
      return 0;
  }
694
  msvcrt_set_errno(GetLastError());
695 696 697
  return -1;
}

698 699 700
/*********************************************************************
 *		_wchmod (MSVCRT.@)
 */
701
int CDECL MSVCRT__wchmod(const MSVCRT_wchar_t *path, int flags)
702 703 704
{
  DWORD oldFlags = GetFileAttributesW(path);

705
  if (oldFlags != INVALID_FILE_ATTRIBUTES)
706
  {
707
    DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
708 709 710 711 712
      oldFlags | FILE_ATTRIBUTE_READONLY;

    if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
      return 0;
  }
713
  msvcrt_set_errno(GetLastError());
714 715 716
  return -1;
}

717 718 719
/*********************************************************************
 *		_unlink (MSVCRT.@)
 */
720
int CDECL MSVCRT__unlink(const char *path)
721
{
722
  TRACE("%s\n",debugstr_a(path));
723 724
  if(DeleteFileA(path))
    return 0;
725
  TRACE("failed (%d)\n",GetLastError());
726
  msvcrt_set_errno(GetLastError());
727 728 729 730 731 732
  return -1;
}

/*********************************************************************
 *		_wunlink (MSVCRT.@)
 */
733
int CDECL MSVCRT__wunlink(const MSVCRT_wchar_t *path)
734 735 736 737
{
  TRACE("(%s)\n",debugstr_w(path));
  if(DeleteFileW(path))
    return 0;
738
  TRACE("failed (%d)\n",GetLastError());
739
  msvcrt_set_errno(GetLastError());
740 741 742
  return -1;
}

743
/* flush_all_buffers calls MSVCRT_fflush which calls flush_all_buffers */
744
int CDECL MSVCRT_fflush(MSVCRT_FILE* file);
745

746 747
/* INTERNAL: Flush all stream buffer */
static int msvcrt_flush_all_buffers(int mask)
748 749
{
  int i, num_flushed = 0;
750
  MSVCRT_FILE *file;
751

752
  LOCK_FILES();
753 754 755 756
  for (i = 3; i < MSVCRT_stream_idx; i++) {
    file = msvcrt_get_file(i);

    if (file->_flag)
757
    {
758
      if(file->_flag & mask) {
759
	MSVCRT_fflush(file);
760 761 762
        num_flushed++;
      }
    }
763
  }
764
  UNLOCK_FILES();
765 766 767 768 769

  TRACE(":flushed (%d) handles\n",num_flushed);
  return num_flushed;
}

770 771 772 773 774
/*********************************************************************
 *		_flushall (MSVCRT.@)
 */
int CDECL MSVCRT__flushall(void)
{
775
    return msvcrt_flush_all_buffers(MSVCRT__IOWRT | MSVCRT__IOREAD);
776 777
}

778 779 780
/*********************************************************************
 *		fflush (MSVCRT.@)
 */
781
int CDECL MSVCRT_fflush(MSVCRT_FILE* file)
782
{
783
    if(!file) {
784
        msvcrt_flush_all_buffers(MSVCRT__IOWRT);
785 786 787 788 789 790 791 792
    } else if(file->_flag & MSVCRT__IOWRT) {
        int res;

        MSVCRT__lock_file(file);
        res = msvcrt_flush_buffer(file);
        MSVCRT__unlock_file(file);

        return res;
793 794 795 796 797 798 799
    } else if(file->_flag & MSVCRT__IOREAD) {
        MSVCRT__lock_file(file);
        file->_cnt = 0;
        file->_ptr = file->_base;
        MSVCRT__unlock_file(file);

        return 0;
800 801
    }
    return 0;
802 803
}

804 805 806
/*********************************************************************
 *		_close (MSVCRT.@)
 */
807
int CDECL MSVCRT__close(int fd)
808
{
809 810
  HANDLE hand;
  int ret;
811

812 813
  LOCK_FILES();
  hand = msvcrt_fdtoh(fd);
814
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
815
  if (!msvcrt_is_valid_fd(fd)) {
816
    ret = -1;
817
  } else {
818
    msvcrt_free_fd(fd);
819 820 821 822 823
    ret = CloseHandle(hand) ? 0 : -1;
    if (ret) {
      WARN(":failed-last error (%d)\n",GetLastError());
      msvcrt_set_errno(GetLastError());
    }
824 825
  }
  UNLOCK_FILES();
826
  TRACE(":ok\n");
827
  return ret;
828 829 830 831 832
}

/*********************************************************************
 *		_commit (MSVCRT.@)
 */
833
int CDECL MSVCRT__commit(int fd)
834
{
835
  HANDLE hand = msvcrt_fdtoh(fd);
836

837
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
838 839 840 841 842 843 844 845 846 847 848 849
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (!FlushFileBuffers(hand))
  {
    if (GetLastError() == ERROR_INVALID_HANDLE)
    {
      /* FlushFileBuffers fails for console handles
       * so we ignore this error.
       */
      return 0;
    }
850
    TRACE(":failed-last error (%d)\n",GetLastError());
851
    msvcrt_set_errno(GetLastError());
852 853 854 855 856 857
    return -1;
  }
  TRACE(":ok\n");
  return 0;
}

858 859 860
/*********************************************************************
 *		_dup2 (MSVCRT.@)
 * NOTES
861
 * MSDN isn't clear on this point, but the remarks for _pipe
862 863 864
 * indicate file descriptors duplicated with _dup and _dup2 are always
 * inheritable.
 */
865
int CDECL MSVCRT__dup2(int od, int nd)
866 867 868 869
{
  int ret;

  TRACE("(od=%d, nd=%d)\n", od, nd);
870
  LOCK_FILES();
871
  if (nd < MSVCRT_MAX_FILES && nd >= 0 && msvcrt_is_valid_fd(od))
872 873 874
  {
    HANDLE handle;

875
    if (DuplicateHandle(GetCurrentProcess(), msvcrt_get_ioinfo(od)->handle,
876 877
     GetCurrentProcess(), &handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
    {
878
      int wxflag = msvcrt_get_ioinfo(od)->wxflag & ~MSVCRT__O_NOINHERIT;
879 880

      if (msvcrt_is_valid_fd(nd))
881
        MSVCRT__close(nd);
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
      ret = msvcrt_alloc_fd_from(handle, wxflag, nd);
      if (ret == -1)
      {
        CloseHandle(handle);
        *MSVCRT__errno() = MSVCRT_EMFILE;
      }
      else
      {
        /* _dup2 returns 0, not nd, on success */
        ret = 0;
      }
    }
    else
    {
      ret = -1;
      msvcrt_set_errno(GetLastError());
    }
  }
  else
  {
    *MSVCRT__errno() = MSVCRT_EBADF;
    ret = -1;
  }
905
  UNLOCK_FILES();
906 907 908 909 910 911
  return ret;
}

/*********************************************************************
 *		_dup (MSVCRT.@)
 */
912
int CDECL MSVCRT__dup(int od)
913
{
914 915 916 917
  int fd, ret;
 
  LOCK_FILES();
  fd = MSVCRT_fdstart;
918
  if (MSVCRT__dup2(od, fd) == 0)
919 920 921 922 923
    ret = fd;
  else
    ret = -1;
  UNLOCK_FILES();
  return ret;
924 925
}

926 927 928
/*********************************************************************
 *		_eof (MSVCRT.@)
 */
929
int CDECL MSVCRT__eof(int fd)
930
{
Mike McCormack's avatar
Mike McCormack committed
931 932
  DWORD curpos,endpos;
  LONG hcurpos,hendpos;
933
  HANDLE hand = msvcrt_fdtoh(fd);
934

935
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
936 937 938 939

  if (hand == INVALID_HANDLE_VALUE)
    return -1;

940
  if (msvcrt_get_ioinfo(fd)->wxflag & WX_ATEOF) return TRUE;
941 942

  /* Otherwise we do it the hard way */
943
  hcurpos = hendpos = 0;
Mike McCormack's avatar
Mike McCormack committed
944
  curpos = SetFilePointer(hand, 0, &hcurpos, FILE_CURRENT);
945
  endpos = SetFilePointer(hand, 0, &hendpos, FILE_END);
946

947
  if (curpos == endpos && hcurpos == hendpos)
948 949
  {
    /* FIXME: shouldn't WX_ATEOF be set here? */
950
    return TRUE;
951
  }
952

953
  SetFilePointer(hand, curpos, &hcurpos, FILE_BEGIN);
954 955 956 957 958 959
  return FALSE;
}

/*********************************************************************
 *		_fcloseall (MSVCRT.@)
 */
960
int CDECL MSVCRT__fcloseall(void)
961 962
{
  int num_closed = 0, i;
963
  MSVCRT_FILE *file;
964

965
  LOCK_FILES();
966 967 968 969
  for (i = 3; i < MSVCRT_stream_idx; i++) {
    file = msvcrt_get_file(i);

    if (file->_flag && !MSVCRT_fclose(file))
970
      num_closed++;
971
  }
972
  UNLOCK_FILES();
973 974 975 976 977

  TRACE(":closed (%d) handles\n",num_closed);
  return num_closed;
}

978 979 980
/* free everything on process exit */
void msvcrt_free_io(void)
{
981 982
    int i;

983
    MSVCRT__fcloseall();
984 985 986 987 988 989 990
    /* The Win32 _fcloseall() function explicitly doesn't close stdin,
     * stdout, and stderr (unlike GNU), so we need to fclose() them here
     * or they won't get flushed.
     */
    MSVCRT_fclose(&MSVCRT__iob[0]);
    MSVCRT_fclose(&MSVCRT__iob[1]);
    MSVCRT_fclose(&MSVCRT__iob[2]);
991 992 993 994

    for(i=0; i<sizeof(MSVCRT___pioinfo)/sizeof(MSVCRT___pioinfo[0]); i++)
        MSVCRT_free(MSVCRT___pioinfo[i]);

995 996 997 998 999 1000 1001 1002 1003 1004
    for(i=0; i<MSVCRT_stream_idx; i++)
    {
        MSVCRT_FILE *file = msvcrt_get_file(i);
        if(file<MSVCRT__iob || file>=MSVCRT__iob+_IOB_ENTRIES)
        {
            ((file_crit*)file)->crit.DebugInfo->Spare[0] = 0;
            DeleteCriticalSection(&((file_crit*)file)->crit);
        }
    }

1005 1006 1007
    for(i=0; i<sizeof(MSVCRT_fstream)/sizeof(MSVCRT_fstream[0]); i++)
        MSVCRT_free(MSVCRT_fstream[i]);

1008
    DeleteCriticalSection(&MSVCRT_file_cs);
1009 1010
}

1011
/*********************************************************************
1012
 *		_lseeki64 (MSVCRT.@)
1013
 */
1014
__int64 CDECL MSVCRT__lseeki64(int fd, __int64 offset, int whence)
1015
{
1016
  HANDLE hand = msvcrt_fdtoh(fd);
1017
  LARGE_INTEGER ofs;
1018

1019
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1020 1021 1022 1023 1024
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (whence < 0 || whence > 2)
  {
1025
    *MSVCRT__errno() = MSVCRT_EINVAL;
1026 1027 1028
    return -1;
  }

Mike McCormack's avatar
Mike McCormack committed
1029
  TRACE(":fd (%d) to %s pos %s\n",
1030
        fd,wine_dbgstr_longlong(offset),
1031
        (whence==SEEK_SET)?"SEEK_SET":
1032 1033 1034
        (whence==SEEK_CUR)?"SEEK_CUR":
        (whence==SEEK_END)?"SEEK_END":"UNKNOWN");

1035 1036
  /* The MoleBox protection scheme expects msvcrt to use SetFilePointer only,
   * so a LARGE_INTEGER offset cannot be passed directly via SetFilePointerEx. */
Mike McCormack's avatar
Mike McCormack committed
1037
  ofs.QuadPart = offset;
1038
  if ((ofs.u.LowPart = SetFilePointer(hand, ofs.u.LowPart, &ofs.u.HighPart, whence)) != INVALID_SET_FILE_POINTER ||
1039
      GetLastError() == ERROR_SUCCESS)
1040
  {
1041
    msvcrt_get_ioinfo(fd)->wxflag &= ~(WX_ATEOF|WX_READEOF);
1042
    /* FIXME: What if we seek _to_ EOF - is EOF set? */
1043

1044
    return ofs.QuadPart;
1045
  }
1046
  TRACE(":error-last error (%d)\n",GetLastError());
1047
  msvcrt_set_errno(GetLastError());
1048 1049 1050
  return -1;
}

1051 1052 1053
/*********************************************************************
 *		_lseek (MSVCRT.@)
 */
1054
LONG CDECL MSVCRT__lseek(int fd, LONG offset, int whence)
1055
{
1056
    return MSVCRT__lseeki64(fd, offset, whence);
1057 1058
}

1059 1060 1061 1062 1063
/*********************************************************************
 *              _lock_file (MSVCRT.@)
 */
void CDECL MSVCRT__lock_file(MSVCRT_FILE *file)
{
1064 1065 1066 1067
    if(file>=MSVCRT__iob && file<MSVCRT__iob+_IOB_ENTRIES)
        _lock(_STREAM_LOCKS+(file-MSVCRT__iob));
    else
        EnterCriticalSection(&((file_crit*)file)->crit);
1068 1069 1070 1071 1072 1073 1074
}

/*********************************************************************
 *              _unlock_file (MSVCRT.@)
 */
void CDECL MSVCRT__unlock_file(MSVCRT_FILE *file)
{
1075 1076 1077 1078
    if(file>=MSVCRT__iob && file<MSVCRT__iob+_IOB_ENTRIES)
        _unlock(_STREAM_LOCKS+(file-MSVCRT__iob));
    else
        LeaveCriticalSection(&((file_crit*)file)->crit);
1079 1080
}

1081 1082 1083 1084 1085
/*********************************************************************
 *		_locking (MSVCRT.@)
 *
 * This is untested; the underlying LockFile doesn't work yet.
 */
1086
int CDECL MSVCRT__locking(int fd, int mode, LONG nbytes)
1087 1088 1089 1090 1091
{
  BOOL ret;
  DWORD cur_locn;
  HANDLE hand = msvcrt_fdtoh(fd);

1092
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1093 1094 1095 1096 1097
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (mode < 0 || mode > 4)
  {
1098
    *MSVCRT__errno() = MSVCRT_EINVAL;
1099 1100 1101
    return -1;
  }

1102
  TRACE(":fd (%d) by 0x%08x mode %s\n",
1103 1104 1105 1106 1107
        fd,nbytes,(mode==MSVCRT__LK_UNLCK)?"_LK_UNLCK":
        (mode==MSVCRT__LK_LOCK)?"_LK_LOCK":
        (mode==MSVCRT__LK_NBLCK)?"_LK_NBLCK":
        (mode==MSVCRT__LK_RLCK)?"_LK_RLCK":
        (mode==MSVCRT__LK_NBRLCK)?"_LK_NBRLCK":
1108 1109
                          "UNKNOWN");

1110
  if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == INVALID_SET_FILE_POINTER)
1111 1112
  {
    FIXME ("Seek failed\n");
1113
    *MSVCRT__errno() = MSVCRT_EINVAL; /* FIXME */
1114 1115
    return -1;
  }
1116
  if (mode == MSVCRT__LK_LOCK || mode == MSVCRT__LK_RLCK)
1117 1118 1119 1120 1121 1122 1123
  {
    int nretry = 10;
    ret = 1; /* just to satisfy gcc */
    while (nretry--)
    {
      ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
      if (ret) break;
1124
      Sleep(1);
1125 1126
    }
  }
1127
  else if (mode == MSVCRT__LK_UNLCK)
1128 1129 1130 1131 1132 1133 1134
    ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
  else
    ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
  /* FIXME - what about error settings? */
  return ret ? 0 : -1;
}

1135
/*********************************************************************
1136
 *		_fseeki64 (MSVCRT.@)
1137
 */
1138
int CDECL MSVCRT__fseeki64(MSVCRT_FILE* file, __int64 offset, int whence)
1139
{
1140 1141 1142
  int ret;

  MSVCRT__lock_file(file);
1143 1144 1145 1146 1147 1148
  /* Flush output if needed */
  if(file->_flag & MSVCRT__IOWRT)
	msvcrt_flush_buffer(file);

  if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
	offset -= file->_cnt;
1149
	if (msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT) {
1150 1151 1152 1153 1154 1155
		/* Black magic correction for CR removal */
		int i;
		for (i=0; i<file->_cnt; i++) {
			if (file->_ptr[i] == '\n')
				offset--;
		}
1156
		/* Black magic when reading CR at buffer boundary*/
1157
		if(msvcrt_get_ioinfo(file->_file)->wxflag & WX_READCR)
1158
		    offset--;
1159
	}
1160 1161 1162 1163 1164 1165 1166 1167
  }
  /* Discard buffered input */
  file->_cnt = 0;
  file->_ptr = file->_base;
  /* Reset direction of i/o */
  if(file->_flag & MSVCRT__IORW) {
        file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
  }
1168 1169
  /* Clear end of file flag */
  file->_flag &= ~MSVCRT__IOEOF;
1170 1171 1172 1173
  ret = (MSVCRT__lseeki64(file->_file,offset,whence) == -1)?-1:0;

  MSVCRT__unlock_file(file);
  return ret;
1174 1175 1176 1177 1178 1179 1180 1181
}

/*********************************************************************
 *		fseek (MSVCRT.@)
 */
int CDECL MSVCRT_fseek(MSVCRT_FILE* file, MSVCRT_long offset, int whence)
{
    return MSVCRT__fseeki64( file, offset, whence );
1182 1183
}

1184 1185 1186
/*********************************************************************
 *		_chsize (MSVCRT.@)
 */
1187
int CDECL MSVCRT__chsize(int fd, MSVCRT_long size)
1188 1189 1190 1191 1192
{
    LONG cur, pos;
    HANDLE handle;
    BOOL ret = FALSE;

1193
    TRACE("(fd=%d, size=%d)\n", fd, size);
1194 1195 1196 1197 1198 1199 1200

    LOCK_FILES();

    handle = msvcrt_fdtoh(fd);
    if (handle != INVALID_HANDLE_VALUE)
    {
        /* save the current file pointer */
1201
        cur = MSVCRT__lseek(fd, 0, SEEK_CUR);
1202 1203
        if (cur >= 0)
        {
1204
            pos = MSVCRT__lseek(fd, size, SEEK_SET);
1205 1206 1207 1208 1209 1210 1211
            if (pos >= 0)
            {
                ret = SetEndOfFile(handle);
                if (!ret) msvcrt_set_errno(GetLastError());
            }

            /* restore the file pointer */
1212
            MSVCRT__lseek(fd, cur, SEEK_SET);
1213 1214 1215 1216 1217 1218 1219
        }
    }

    UNLOCK_FILES();
    return ret ? 0 : -1;
}

1220 1221 1222
/*********************************************************************
 *		clearerr (MSVCRT.@)
 */
1223
void CDECL MSVCRT_clearerr(MSVCRT_FILE* file)
1224 1225
{
  TRACE(":file (%p) fd (%d)\n",file,file->_file);
1226 1227

  MSVCRT__lock_file(file);
1228
  file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1229
  MSVCRT__unlock_file(file);
1230 1231
}

1232 1233 1234
/*********************************************************************
 *		rewind (MSVCRT.@)
 */
1235
void CDECL MSVCRT_rewind(MSVCRT_FILE* file)
1236 1237
{
  TRACE(":file (%p) fd (%d)\n",file,file->_file);
1238 1239

  MSVCRT__lock_file(file);
1240 1241
  MSVCRT_fseek(file, 0L, SEEK_SET);
  MSVCRT_clearerr(file);
1242
  MSVCRT__unlock_file(file);
1243 1244
}

1245
static int msvcrt_get_flags(const MSVCRT_wchar_t* mode, int *open_flags, int* stream_flags)
1246
{
1247
  int plus = strchrW(mode, '+') != NULL;
1248 1249 1250 1251

  switch(*mode++)
  {
  case 'R': case 'r':
1252
    *open_flags = plus ? MSVCRT__O_RDWR : MSVCRT__O_RDONLY;
1253 1254 1255
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOREAD;
    break;
  case 'W': case 'w':
1256
    *open_flags = MSVCRT__O_CREAT | MSVCRT__O_TRUNC | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
1257 1258 1259
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
    break;
  case 'A': case 'a':
1260
    *open_flags = MSVCRT__O_CREAT | MSVCRT__O_APPEND | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
1261 1262 1263
    *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
    break;
  default:
1264 1265
    MSVCRT__invalid_parameter(NULL, NULL, NULL, 0, 0);
    *MSVCRT__errno() = MSVCRT_EINVAL;
1266 1267 1268 1269 1270 1271 1272
    return -1;
  }

  while (*mode)
    switch (*mode++)
    {
    case 'B': case 'b':
1273 1274
      *open_flags |=  MSVCRT__O_BINARY;
      *open_flags &= ~MSVCRT__O_TEXT;
1275
      break;
1276
    case 't':
1277 1278
      *open_flags |=  MSVCRT__O_TEXT;
      *open_flags &= ~MSVCRT__O_BINARY;
1279
      break;
1280 1281 1282 1283 1284 1285
    case 'D':
      *open_flags |= MSVCRT__O_TEMPORARY;
      break;
    case 'T':
      *open_flags |= MSVCRT__O_SHORT_LIVED;
      break;
1286
    case '+':
1287
    case ' ':
1288 1289 1290 1291 1292 1293 1294
      break;
    default:
      FIXME(":unknown flag %c not supported\n",mode[-1]);
    }
  return 0;
}

1295 1296 1297
/*********************************************************************
 *		_fdopen (MSVCRT.@)
 */
1298
MSVCRT_FILE* CDECL MSVCRT__fdopen(int fd, const char *mode)
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
{
    MSVCRT_FILE *ret;
    MSVCRT_wchar_t *modeW = NULL;

    if (mode && !(modeW = msvcrt_wstrdupa(mode))) return NULL;

    ret = MSVCRT__wfdopen(fd, modeW);

    MSVCRT_free(modeW);
    return ret;
}

/*********************************************************************
 *		_wfdopen (MSVCRT.@)
 */
MSVCRT_FILE* CDECL MSVCRT__wfdopen(int fd, const MSVCRT_wchar_t *mode)
1315
{
1316 1317
  int open_flags, stream_flags;
  MSVCRT_FILE* file;
1318

1319 1320
  if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1) return NULL;

1321 1322 1323 1324
  LOCK_FILES();
  if (!(file = msvcrt_alloc_fp()))
    file = NULL;
  else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
1325 1326 1327 1328
  {
    file->_flag = 0;
    file = NULL;
  }
1329
  else TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
1330
  UNLOCK_FILES();
1331 1332 1333 1334 1335 1336 1337

  return file;
}

/*********************************************************************
 *		_filelength (MSVCRT.@)
 */
1338
LONG CDECL MSVCRT__filelength(int fd)
1339
{
1340
  LONG curPos = MSVCRT__lseek(fd, 0, SEEK_CUR);
1341 1342
  if (curPos != -1)
  {
1343
    LONG endPos = MSVCRT__lseek(fd, 0, SEEK_END);
1344 1345 1346
    if (endPos != -1)
    {
      if (endPos != curPos)
1347
        MSVCRT__lseek(fd, curPos, SEEK_SET);
1348 1349 1350 1351 1352 1353
      return endPos;
    }
  }
  return -1;
}

1354 1355 1356
/*********************************************************************
 *		_filelengthi64 (MSVCRT.@)
 */
1357
__int64 CDECL MSVCRT__filelengthi64(int fd)
1358
{
1359
  __int64 curPos = MSVCRT__lseeki64(fd, 0, SEEK_CUR);
1360 1361
  if (curPos != -1)
  {
1362
    __int64 endPos = MSVCRT__lseeki64(fd, 0, SEEK_END);
1363 1364 1365
    if (endPos != -1)
    {
      if (endPos != curPos)
1366
        MSVCRT__lseeki64(fd, curPos, SEEK_SET);
1367 1368 1369 1370 1371 1372
      return endPos;
    }
  }
  return -1;
}

1373 1374 1375
/*********************************************************************
 *		_fileno (MSVCRT.@)
 */
1376
int CDECL MSVCRT__fileno(MSVCRT_FILE* file)
1377 1378
{
  TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
1379
  return file->_file;
1380 1381 1382
}

/*********************************************************************
1383
 *		_fstat64 (MSVCRT.@)
1384
 */
1385
int CDECL MSVCRT__fstat64(int fd, struct MSVCRT__stat64* buf)
1386 1387
{
  DWORD dw;
1388
  DWORD type;
1389
  BY_HANDLE_FILE_INFORMATION hfi;
1390
  HANDLE hand = msvcrt_fdtoh(fd);
1391 1392 1393 1394 1395 1396 1397 1398

  TRACE(":fd (%d) stat (%p)\n",fd,buf);
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

  if (!buf)
  {
    WARN(":failed-NULL buf\n");
1399
    msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1400 1401 1402 1403
    return -1;
  }

  memset(&hfi, 0, sizeof(hfi));
1404
  memset(buf, 0, sizeof(struct MSVCRT__stat64));
1405 1406
  type = GetFileType(hand);
  if (type == FILE_TYPE_PIPE)
1407
  {
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
    buf->st_dev = buf->st_rdev = fd;
    buf->st_mode = S_IFIFO;
    buf->st_nlink = 1;
  }
  else if (type == FILE_TYPE_CHAR)
  {
    buf->st_dev = buf->st_rdev = fd;
    buf->st_mode = S_IFCHR;
    buf->st_nlink = 1;
  }
  else /* FILE_TYPE_DISK etc. */
  {
    if (!GetFileInformationByHandle(hand, &hfi))
    {
      WARN(":failed-last error (%d)\n",GetLastError());
      msvcrt_set_errno(ERROR_INVALID_PARAMETER);
      return -1;
    }
1426
    buf->st_mode = S_IFREG | 0444;
1427
    if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1428
      buf->st_mode |= 0222;
1429 1430 1431 1432 1433 1434
    buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
    RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
    buf->st_atime = dw;
    RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
    buf->st_mtime = buf->st_ctime = dw;
    buf->st_nlink = hfi.nNumberOfLinks;
1435
  }
1436
  TRACE(":dwFileAttributes = 0x%x, mode set to 0x%x\n",hfi.dwFileAttributes,
1437
   buf->st_mode);
1438 1439 1440
  return 0;
}

1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
/*********************************************************************
 *		_fstati64 (MSVCRT.@)
 */
int CDECL MSVCRT__fstati64(int fd, struct MSVCRT__stati64* buf)
{
  int ret;
  struct MSVCRT__stat64 buf64;

  ret = MSVCRT__fstat64(fd, &buf64);
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

1455 1456 1457
/*********************************************************************
 *		_fstat (MSVCRT.@)
 */
1458
int CDECL MSVCRT__fstat(int fd, struct MSVCRT__stat* buf)
1459
{ int ret;
1460
  struct MSVCRT__stat64 buf64;
1461

1462
  ret = MSVCRT__fstat64(fd, &buf64);
1463
  if (!ret)
1464
      msvcrt_stat64_to_stat(&buf64, buf);
1465 1466 1467
  return ret;
}

1468
/*********************************************************************
1469
 *		_futime64 (MSVCRT.@)
1470
 */
1471
int CDECL _futime64(int fd, struct MSVCRT___utimbuf64 *t)
1472
{
1473
  HANDLE hand = msvcrt_fdtoh(fd);
1474 1475 1476 1477
  FILETIME at, wt;

  if (!t)
  {
1478 1479
      time_to_filetime( MSVCRT__time64(NULL), &at );
      wt = at;
1480 1481 1482
  }
  else
  {
1483 1484
      time_to_filetime( t->actime, &at );
      time_to_filetime( t->modtime, &wt );
1485 1486 1487 1488
  }

  if (!SetFileTime(hand, NULL, &at, &wt))
  {
1489
    msvcrt_set_errno(GetLastError());
1490 1491 1492 1493 1494
    return -1 ;
  }
  return 0;
}

1495 1496 1497 1498 1499
/*********************************************************************
 *		_futime32 (MSVCRT.@)
 */
int CDECL _futime32(int fd, struct MSVCRT___utimbuf32 *t)
{
1500 1501 1502 1503 1504 1505 1506 1507 1508
    if (t)
    {
        struct MSVCRT___utimbuf64 t64;
        t64.actime = t->actime;
        t64.modtime = t->modtime;
        return _futime64( fd, &t64 );
    }
    else
        return _futime64( fd, NULL );
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
}

/*********************************************************************
 *		_futime (MSVCRT.@)
 */
#ifdef _WIN64
int CDECL _futime(int fd, struct MSVCRT___utimbuf64 *t)
{
    return _futime64( fd, t );
}
#else
int CDECL _futime(int fd, struct MSVCRT___utimbuf32 *t)
{
    return _futime32( fd, t );
}
#endif

1526 1527 1528
/*********************************************************************
 *		_get_osfhandle (MSVCRT.@)
 */
1529
MSVCRT_intptr_t CDECL MSVCRT__get_osfhandle(int fd)
1530
{
1531
  HANDLE hand = msvcrt_fdtoh(fd);
1532
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1533

1534
  return (MSVCRT_intptr_t)hand;
1535 1536 1537 1538 1539
}

/*********************************************************************
 *		_isatty (MSVCRT.@)
 */
1540
int CDECL MSVCRT__isatty(int fd)
1541
{
1542
  HANDLE hand = msvcrt_fdtoh(fd);
1543

1544
  TRACE(":fd (%d) handle (%p)\n",fd,hand);
1545 1546 1547
  if (hand == INVALID_HANDLE_VALUE)
    return 0;

1548
  return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
1549 1550 1551 1552 1553
}

/*********************************************************************
 *		_mktemp (MSVCRT.@)
 */
1554
char * CDECL MSVCRT__mktemp(char *pattern)
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
{
  int numX = 0;
  char *retVal = pattern;
  int id;
  char letter = 'a';

  while(*pattern)
    numX = (*pattern++ == 'X')? numX + 1 : 0;
  if (numX < 5)
    return NULL;
  pattern--;
  id = GetCurrentProcessId();
  numX = 6;
  while(numX--)
  {
    int tempNum = id / 10;
    *pattern-- = id - (tempNum * 10) + '0';
    id = tempNum;
  }
  pattern++;
  do
  {
1577
    *pattern = letter++;
1578
    if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES &&
1579
        GetLastError() == ERROR_FILE_NOT_FOUND)
1580
      return retVal;
1581
  } while(letter <= 'z');
1582 1583 1584
  return NULL;
}

1585 1586 1587
/*********************************************************************
 *		_wmktemp (MSVCRT.@)
 */
1588
MSVCRT_wchar_t * CDECL MSVCRT__wmktemp(MSVCRT_wchar_t *pattern)
1589 1590
{
  int numX = 0;
1591
  MSVCRT_wchar_t *retVal = pattern;
1592
  int id;
1593
  MSVCRT_wchar_t letter = 'a';
1594 1595

  while(*pattern)
1596
    numX = (*pattern++ == 'X')? numX + 1 : 0;
1597 1598 1599 1600 1601 1602 1603 1604
  if (numX < 5)
    return NULL;
  pattern--;
  id = GetCurrentProcessId();
  numX = 6;
  while(numX--)
  {
    int tempNum = id / 10;
1605
    *pattern-- = id - (tempNum * 10) + '0';
1606 1607 1608 1609 1610
    id = tempNum;
  }
  pattern++;
  do
  {
1611
    if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES &&
1612 1613 1614
        GetLastError() == ERROR_FILE_NOT_FOUND)
      return retVal;
    *pattern = letter++;
1615
  } while(letter != '|');
1616 1617 1618
  return NULL;
}

1619 1620 1621
static unsigned split_oflags(unsigned oflags)
{
    int         wxflags = 0;
1622
    unsigned unsupp; /* until we support everything */
1623 1624

    if (oflags & MSVCRT__O_APPEND)              wxflags |= WX_APPEND;
1625
    if (oflags & MSVCRT__O_BINARY)              {/* Nothing to do */}
1626
    else if (oflags & MSVCRT__O_TEXT)           wxflags |= WX_TEXT;
1627
    else if (*__p__fmode() & MSVCRT__O_BINARY)  {/* Nothing to do */}
1628 1629 1630
    else                                        wxflags |= WX_TEXT; /* default to TEXT*/
    if (oflags & MSVCRT__O_NOINHERIT)           wxflags |= WX_DONTINHERIT;

1631 1632 1633 1634 1635 1636 1637 1638
    if ((unsupp = oflags & ~(
                    MSVCRT__O_BINARY|MSVCRT__O_TEXT|MSVCRT__O_APPEND|
                    MSVCRT__O_TRUNC|MSVCRT__O_EXCL|MSVCRT__O_CREAT|
                    MSVCRT__O_RDWR|MSVCRT__O_WRONLY|MSVCRT__O_TEMPORARY|
                    MSVCRT__O_NOINHERIT|
                    MSVCRT__O_SEQUENTIAL|MSVCRT__O_RANDOM|MSVCRT__O_SHORT_LIVED
                    )))
        ERR(":unsupported oflags 0x%04x\n",unsupp);
1639 1640 1641 1642

    return wxflags;
}

1643 1644 1645
/*********************************************************************
 *              _pipe (MSVCRT.@)
 */
1646
int CDECL MSVCRT__pipe(int *pfds, unsigned int psize, int textmode)
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
{
  int ret = -1;
  SECURITY_ATTRIBUTES sa;
  HANDLE readHandle, writeHandle;

  if (!pfds)
  {
    *MSVCRT__errno() = MSVCRT_EINVAL;
    return -1;
  }

  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.bInheritHandle = !(textmode & MSVCRT__O_NOINHERIT);
  sa.lpSecurityDescriptor = NULL;
  if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
  {
    unsigned int wxflags = split_oflags(textmode);
    int fd;

1666
    LOCK_FILES();
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    fd = msvcrt_alloc_fd(readHandle, wxflags);
    if (fd != -1)
    {
      pfds[0] = fd;
      fd = msvcrt_alloc_fd(writeHandle, wxflags);
      if (fd != -1)
      {
        pfds[1] = fd;
        ret = 0;
      }
      else
      {
1679
        MSVCRT__close(pfds[0]);
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
        CloseHandle(writeHandle);
        *MSVCRT__errno() = MSVCRT_EMFILE;
      }
    }
    else
    {
      CloseHandle(readHandle);
      CloseHandle(writeHandle);
      *MSVCRT__errno() = MSVCRT_EMFILE;
    }
1690
    UNLOCK_FILES();
1691 1692 1693 1694 1695 1696 1697
  }
  else
    msvcrt_set_errno(GetLastError());

  return ret;
}

1698
/*********************************************************************
1699
 *              _sopen_s (MSVCRT.@)
1700
 */
1701
int CDECL MSVCRT__sopen_s( int *fd, const char *path, int oflags, int shflags, int pmode )
1702
{
1703
  DWORD access = 0, creation = 0, attrib;
1704
  DWORD sharing;
1705
  int wxflag;
1706
  HANDLE hand;
1707
  SECURITY_ATTRIBUTES sa;
1708

1709 1710
  TRACE("fd*: %p file: (%s) oflags: 0x%04x shflags: 0x%04x pmode: 0x%04x\n",
        fd, path, oflags, shflags, pmode);
1711

1712
  if (!MSVCRT_CHECK_PMT( fd != NULL )) return MSVCRT_EINVAL;
1713

1714
  *fd = -1;
1715 1716
  wxflag = split_oflags(oflags);
  switch (oflags & (MSVCRT__O_RDONLY | MSVCRT__O_WRONLY | MSVCRT__O_RDWR))
1717
  {
1718 1719 1720
  case MSVCRT__O_RDONLY: access |= GENERIC_READ; break;
  case MSVCRT__O_WRONLY: access |= GENERIC_WRITE; break;
  case MSVCRT__O_RDWR:   access |= GENERIC_WRITE | GENERIC_READ; break;
1721 1722
  }

1723
  if (oflags & MSVCRT__O_CREAT)
1724
  {
1725
    if(pmode & ~(MSVCRT__S_IREAD | MSVCRT__S_IWRITE))
1726 1727 1728
      FIXME(": pmode 0x%04x ignored\n", pmode);
    else
      WARN(": pmode 0x%04x ignored\n", pmode);
1729

1730
    if (oflags & MSVCRT__O_EXCL)
1731
      creation = CREATE_NEW;
1732
    else if (oflags & MSVCRT__O_TRUNC)
1733 1734 1735 1736
      creation = CREATE_ALWAYS;
    else
      creation = OPEN_ALWAYS;
  }
1737
  else  /* no MSVCRT__O_CREAT */
1738
  {
1739
    if (oflags & MSVCRT__O_TRUNC)
1740 1741 1742 1743
      creation = TRUNCATE_EXISTING;
    else
      creation = OPEN_EXISTING;
  }
1744
  
1745 1746
  switch( shflags )
  {
1747
    case MSVCRT__SH_DENYRW:
1748 1749
      sharing = 0L;
      break;
1750
    case MSVCRT__SH_DENYWR:
1751 1752
      sharing = FILE_SHARE_READ;
      break;
1753
    case MSVCRT__SH_DENYRD:
1754 1755
      sharing = FILE_SHARE_WRITE;
      break;
1756
    case MSVCRT__SH_DENYNO:
1757 1758 1759 1760
      sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
      break;
    default:
      ERR( "Unhandled shflags 0x%x\n", shflags );
1761
      return MSVCRT_EINVAL;
1762
  }
1763 1764
  attrib = FILE_ATTRIBUTE_NORMAL;

1765
  if (oflags & MSVCRT__O_TEMPORARY)
1766 1767 1768 1769 1770
  {
      attrib |= FILE_FLAG_DELETE_ON_CLOSE;
      access |= DELETE;
      sharing |= FILE_SHARE_DELETE;
  }
1771

1772 1773
  sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
  sa.lpSecurityDescriptor = NULL;
1774
  sa.bInheritHandle       = !(oflags & MSVCRT__O_NOINHERIT);
1775

1776
  hand = CreateFileA(path, access, sharing, &sa, creation, attrib, 0);
1777
  if (hand == INVALID_HANDLE_VALUE)  {
1778
    WARN(":failed-last error (%d)\n", GetLastError());
1779
    msvcrt_set_errno(GetLastError());
1780
    return *MSVCRT__errno();
1781 1782
  }

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
  *fd = msvcrt_alloc_fd(hand, wxflag);

  TRACE(":fd (%d) handle (%p)\n", *fd, hand);
  return 0;
}

/*********************************************************************
 *              _sopen (MSVCRT.@)
 */
int CDECL MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
{
  int pmode;
  int fd;

  if (oflags & MSVCRT__O_CREAT)
  {
    __ms_va_list ap;

    __ms_va_start(ap, shflags);
    pmode = va_arg(ap, int);
    __ms_va_end(ap);
  }
  else
    pmode = 0;
1807

1808
  MSVCRT__sopen_s(&fd, path, oflags, shflags, pmode);
1809 1810 1811
  return fd;
}

1812
/*********************************************************************
1813
 *              _wsopen_s (MSVCRT.@)
1814
 */
1815
int CDECL MSVCRT__wsopen_s( int *fd, const MSVCRT_wchar_t* path, int oflags, int shflags, int pmode )
1816
{
1817
  DWORD access = 0, creation = 0, attrib;
1818
  SECURITY_ATTRIBUTES sa;
1819
  DWORD sharing;
1820
  int wxflag;
1821 1822
  HANDLE hand;

1823 1824
  TRACE("fd*: %p :file (%s) oflags: 0x%04x shflags: 0x%04x pmode: 0x%04x\n",
        fd, debugstr_w(path), oflags, shflags, pmode);
1825

1826
  if (!MSVCRT_CHECK_PMT( fd != NULL )) return MSVCRT_EINVAL;
1827

1828
  *fd = -1;
1829 1830 1831 1832 1833 1834 1835
  wxflag = split_oflags(oflags);
  switch (oflags & (MSVCRT__O_RDONLY | MSVCRT__O_WRONLY | MSVCRT__O_RDWR))
  {
  case MSVCRT__O_RDONLY: access |= GENERIC_READ; break;
  case MSVCRT__O_WRONLY: access |= GENERIC_WRITE; break;
  case MSVCRT__O_RDWR:   access |= GENERIC_WRITE | GENERIC_READ; break;
  }
1836

1837
  if (oflags & MSVCRT__O_CREAT)
1838
  {
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
    if(pmode & ~(MSVCRT__S_IREAD | MSVCRT__S_IWRITE))
      FIXME(": pmode 0x%04x ignored\n", pmode);
    else
      WARN(": pmode 0x%04x ignored\n", pmode);

    if (oflags & MSVCRT__O_EXCL)
      creation = CREATE_NEW;
    else if (oflags & MSVCRT__O_TRUNC)
      creation = CREATE_ALWAYS;
    else
      creation = OPEN_ALWAYS;
  }
  else  /* no MSVCRT__O_CREAT */
  {
    if (oflags & MSVCRT__O_TRUNC)
      creation = TRUNCATE_EXISTING;
    else
      creation = OPEN_EXISTING;
1857 1858
  }

1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
  switch( shflags )
  {
    case MSVCRT__SH_DENYRW:
      sharing = 0L;
      break;
    case MSVCRT__SH_DENYWR:
      sharing = FILE_SHARE_READ;
      break;
    case MSVCRT__SH_DENYRD:
      sharing = FILE_SHARE_WRITE;
      break;
    case MSVCRT__SH_DENYNO:
      sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
      break;
    default:
      ERR( "Unhandled shflags 0x%x\n", shflags );
1875
      return MSVCRT_EINVAL;
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
  }
  attrib = FILE_ATTRIBUTE_NORMAL;

  if (oflags & MSVCRT__O_TEMPORARY)
  {
      attrib |= FILE_FLAG_DELETE_ON_CLOSE;
      access |= DELETE;
      sharing |= FILE_SHARE_DELETE;
  }

  sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
  sa.lpSecurityDescriptor = NULL;
1888
  sa.bInheritHandle       = !(oflags & MSVCRT__O_NOINHERIT);
1889 1890 1891 1892 1893 1894

  hand = CreateFileW(path, access, sharing, &sa, creation, attrib, 0);

  if (hand == INVALID_HANDLE_VALUE)  {
    WARN(":failed-last error (%d)\n",GetLastError());
    msvcrt_set_errno(GetLastError());
1895 1896
    msvcrt_set_errno(GetLastError());
    return *MSVCRT__errno();
1897 1898
  }

1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
  *fd = msvcrt_alloc_fd(hand, wxflag);

  TRACE(":fd (%d) handle (%p)\n", *fd, hand);
  return 0;
}

/*********************************************************************
 *              _wsopen (MSVCRT.@)
 */
int CDECL MSVCRT__wsopen( const MSVCRT_wchar_t *path, int oflags, int shflags, ... )
{
  int pmode;
  int fd;

  if (oflags & MSVCRT__O_CREAT)
  {
    __ms_va_list ap;

    __ms_va_start(ap, shflags);
    pmode = va_arg(ap, int);
    __ms_va_end(ap);
  }
  else
    pmode = 0;
1923

1924
  MSVCRT__wsopen_s(&fd, path, oflags, shflags, pmode);
1925
  return fd;
1926 1927
}

Eric Kohl's avatar
Eric Kohl committed
1928
/*********************************************************************
1929 1930
 *              _open (MSVCRT.@)
 */
1931
int CDECL MSVCRT__open( const char *path, int flags, ... )
1932
{
1933
  __ms_va_list ap;
1934

1935
  if (flags & MSVCRT__O_CREAT)
1936 1937
  {
    int pmode;
1938
    __ms_va_start(ap, flags);
1939
    pmode = va_arg(ap, int);
1940
    __ms_va_end(ap);
1941
    return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO, pmode );
1942 1943
  }
  else
1944
    return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO);
1945 1946 1947 1948
}

/*********************************************************************
 *              _wopen (MSVCRT.@)
Eric Kohl's avatar
Eric Kohl committed
1949
 */
1950
int CDECL MSVCRT__wopen(const MSVCRT_wchar_t *path,int flags,...)
Eric Kohl's avatar
Eric Kohl committed
1951
{
1952
  __ms_va_list ap;
1953

1954
  if (flags & MSVCRT__O_CREAT)
1955
  {
1956 1957 1958 1959 1960
    int pmode;
    __ms_va_start(ap, flags);
    pmode = va_arg(ap, int);
    __ms_va_end(ap);
    return MSVCRT__wsopen( path, flags, MSVCRT__SH_DENYNO, pmode );
1961
  }
1962 1963
  else
    return MSVCRT__wsopen( path, flags, MSVCRT__SH_DENYNO);
Eric Kohl's avatar
Eric Kohl committed
1964 1965
}

1966 1967 1968
/*********************************************************************
 *		_creat (MSVCRT.@)
 */
1969
int CDECL MSVCRT__creat(const char *path, int flags)
1970
{
1971
  int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1972
  return MSVCRT__open(path, usedFlags);
1973 1974
}

1975 1976 1977
/*********************************************************************
 *		_wcreat (MSVCRT.@)
 */
1978
int CDECL MSVCRT__wcreat(const MSVCRT_wchar_t *path, int flags)
1979
{
1980
  int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1981
  return MSVCRT__wopen(path, usedFlags);
1982 1983
}

1984 1985 1986
/*********************************************************************
 *		_open_osfhandle (MSVCRT.@)
 */
1987
int CDECL MSVCRT__open_osfhandle(MSVCRT_intptr_t handle, int oflags)
1988
{
1989 1990
  int fd;

1991
  /* MSVCRT__O_RDONLY (0) always matches, so set the read flag
1992
   * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1993 1994
   * file, so set the write flag. It also only sets MSVCRT__O_TEXT if it wants
   * text - it never sets MSVCRT__O_BINARY.
1995
   */
1996 1997
  /* don't let split_oflags() decide the mode if no mode is passed */
  if (!(oflags & (MSVCRT__O_BINARY | MSVCRT__O_TEXT)))
1998
      oflags |= MSVCRT__O_BINARY;
1999

2000 2001
  fd = msvcrt_alloc_fd((HANDLE)handle, split_oflags(oflags));
  TRACE(":handle (%ld) fd (%d) flags 0x%08x\n", handle, fd, oflags);
2002 2003 2004 2005 2006 2007
  return fd;
}

/*********************************************************************
 *		_rmtmp (MSVCRT.@)
 */
2008
int CDECL MSVCRT__rmtmp(void)
2009 2010
{
  int num_removed = 0, i;
2011
  MSVCRT_FILE *file;
2012

2013
  LOCK_FILES();
2014 2015 2016 2017
  for (i = 3; i < MSVCRT_stream_idx; i++) {
    file = msvcrt_get_file(i);

    if (file->_tmpfname)
2018
    {
2019
      MSVCRT_fclose(file);
2020 2021
      num_removed++;
    }
2022
  }
2023
  UNLOCK_FILES();
2024 2025 2026 2027 2028 2029 2030

  if (num_removed)
    TRACE(":removed (%d) temp files\n",num_removed);
  return num_removed;
}

/*********************************************************************
2031
 * (internal) read_i
2032 2033 2034 2035
 *
 * When reading \r as last character in text mode, read() positions
 * the file pointer on the \r character while getc() goes on to
 * the following \n
2036
 */
2037
static int read_i(int fd, void *buf, unsigned int count)
2038
{
2039
  DWORD num_read;
2040
  char *bufstart = buf;
2041
  HANDLE hand = msvcrt_fdtoh(fd);
2042
  ioinfo *fdinfo = msvcrt_get_ioinfo(fd);
2043

2044 2045 2046
  if (count == 0)
    return 0;

2047 2048
  if (fdinfo->wxflag & WX_READEOF) {
     fdinfo->wxflag |= WX_ATEOF;
2049 2050 2051
     TRACE("already at EOF, returning 0\n");
     return 0;
  }
2052
  /* Don't trace small reads, it gets *very* annoying */
2053
  if (count > 4)
2054
    TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
2055 2056 2057
  if (hand == INVALID_HANDLE_VALUE)
    return -1;

2058
  /* Reading single bytes in O_TEXT mode makes things slow
2059
   * So read big chunks
2060
   */
2061 2062
    if (ReadFile(hand, bufstart, count, &num_read, NULL))
    {
2063 2064
        if (count != 0 && num_read == 0)
        {
2065
            fdinfo->wxflag |= (WX_ATEOF|WX_READEOF);
2066 2067
            TRACE(":EOF %s\n",debugstr_an(buf,num_read));
        }
2068
        else if (fdinfo->wxflag & WX_TEXT)
2069
        {
2070
            DWORD i, j;
2071 2072
            if (bufstart[num_read-1] == '\r')
            {
2073 2074
                if(count == 1)
                {
2075
                    fdinfo->wxflag  &=  ~WX_READCR;
2076 2077 2078 2079
                    ReadFile(hand, bufstart, 1, &num_read, NULL);
                }
                else
                {
2080
                    fdinfo->wxflag  |= WX_READCR;
2081 2082
                    num_read--;
                }
2083 2084
            }
	    else
2085
	      fdinfo->wxflag  &=  ~WX_READCR;
2086
            for (i=0, j=0; i<num_read; i++)
2087
            {
2088
                /* in text mode, a ctrl-z signals EOF */
2089 2090
                if (bufstart[i] == 0x1a)
                {
2091
                    fdinfo->wxflag |= (WX_ATEOF|WX_READEOF);
2092
                    TRACE(":^Z EOF %s\n",debugstr_an(buf,num_read));
2093 2094
                    break;
                }
2095 2096 2097 2098 2099 2100 2101
                /* in text mode, strip \r if followed by \n.
                 * BUG: should save state across calls somehow, so CR LF that
                 * straddles buffer boundary gets recognized properly?
                 */
		if ((bufstart[i] != '\r')
                ||  ((i+1) < num_read && bufstart[i+1] != '\n'))
		    bufstart[j++] = bufstart[i];
2102
            }
2103
            num_read = j;
2104
        }
2105 2106 2107
    }
    else
    {
2108 2109 2110
        if (GetLastError() == ERROR_BROKEN_PIPE)
        {
            TRACE(":end-of-pipe\n");
2111
            fdinfo->wxflag |= (WX_ATEOF|WX_READEOF);
2112 2113 2114 2115 2116 2117 2118
            return 0;
        }
        else
        {
            TRACE(":failed-last error (%d)\n",GetLastError());
            return -1;
        }
2119
    }
2120 2121

  if (count > 4)
2122
      TRACE("(%u), %s\n",num_read,debugstr_an(buf, num_read));
2123
  return num_read;
2124 2125
}

2126 2127 2128
/*********************************************************************
 *		_read (MSVCRT.@)
 */
2129
int CDECL MSVCRT__read(int fd, void *buf, unsigned int count)
2130 2131 2132 2133 2134 2135
{
  int num_read;
  num_read = read_i(fd, buf, count);
  return num_read;
}

2136 2137 2138
/*********************************************************************
 *		_setmode (MSVCRT.@)
 */
2139
int CDECL MSVCRT__setmode(int fd,int mode)
2140
{
2141
  int ret = msvcrt_get_ioinfo(fd)->wxflag & WX_TEXT ? MSVCRT__O_TEXT : MSVCRT__O_BINARY;
2142
  if (mode & (~(MSVCRT__O_TEXT|MSVCRT__O_BINARY)))
2143
    FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
2144
  if ((mode & MSVCRT__O_TEXT) == MSVCRT__O_TEXT)
2145
    msvcrt_get_ioinfo(fd)->wxflag |= WX_TEXT;
2146
  else
2147
    msvcrt_get_ioinfo(fd)->wxflag &= ~WX_TEXT;
2148
  return ret;
2149 2150 2151
}

/*********************************************************************
2152
 *		_stat64 (MSVCRT.@)
2153
 */
2154
int CDECL MSVCRT_stat64(const char* path, struct MSVCRT__stat64 * buf)
2155 2156 2157
{
  DWORD dw;
  WIN32_FILE_ATTRIBUTE_DATA hfi;
2158
  unsigned short mode = ALL_S_IREAD;
2159 2160 2161 2162 2163 2164
  int plen;

  TRACE(":file (%s) buf(%p)\n",path,buf);

  if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
  {
2165
      TRACE("failed (%d)\n",GetLastError());
2166
      msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
2167 2168 2169
      return -1;
  }

2170
  memset(buf,0,sizeof(struct MSVCRT__stat64));
2171

2172
  /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
2173
     Bon 011120: This FIXME seems incorrect
2174 2175
                 Also a letter as first char isn't enough to be classified
		 as a drive letter
2176 2177 2178
  */
  if (isalpha(*path)&& (*(path+1)==':'))
    buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
2179
  else
2180
    buf->st_dev = buf->st_rdev = MSVCRT__getdrive() - 1;
2181 2182 2183 2184 2185 2186

  plen = strlen(path);

  /* Dir, or regular file? */
  if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
      (path[plen-1] == '\\'))
2187
    mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
2188 2189
  else
  {
2190
    mode |= MSVCRT__S_IFREG;
2191 2192 2193
    /* executable? */
    if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
    {
2194 2195
      unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
                                 (tolower(path[plen-3]) << 16);
2196
      if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
2197
          mode |= ALL_S_IEXEC;
2198 2199 2200 2201
    }
  }

  if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
2202
    mode |= ALL_S_IWRITE;
2203 2204 2205

  buf->st_mode  = mode;
  buf->st_nlink = 1;
2206
  buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
2207
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
2208
  buf->st_atime = dw;
2209
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
2210
  buf->st_mtime = buf->st_ctime = dw;
2211 2212 2213
  TRACE("%d %d 0x%08x%08x %d %d %d\n", buf->st_mode,buf->st_nlink,
        (int)(buf->st_size >> 32),(int)buf->st_size,
        (int)buf->st_atime,(int)buf->st_mtime,(int)buf->st_ctime);
2214 2215 2216
  return 0;
}

2217 2218 2219
/*********************************************************************
 *		_stati64 (MSVCRT.@)
 */
2220
int CDECL MSVCRT_stati64(const char* path, struct MSVCRT__stati64 * buf)
2221 2222 2223 2224
{
  int ret;
  struct MSVCRT__stat64 buf64;

2225
  ret = MSVCRT_stat64(path, &buf64);
2226 2227 2228 2229 2230
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

2231 2232 2233
/*********************************************************************
 *		_stat (MSVCRT.@)
 */
2234
int CDECL MSVCRT_stat(const char* path, struct MSVCRT__stat * buf)
2235
{ int ret;
2236
  struct MSVCRT__stat64 buf64;
2237

2238
  ret = MSVCRT_stat64( path, &buf64);
2239
  if (!ret)
2240
      msvcrt_stat64_to_stat(&buf64, buf);
2241 2242 2243
  return ret;
}

2244
/*********************************************************************
2245
 *		_wstat64 (MSVCRT.@)
2246
 */
2247
int CDECL MSVCRT__wstat64(const MSVCRT_wchar_t* path, struct MSVCRT__stat64 * buf)
2248 2249 2250
{
  DWORD dw;
  WIN32_FILE_ATTRIBUTE_DATA hfi;
2251
  unsigned short mode = ALL_S_IREAD;
2252 2253 2254 2255 2256 2257
  int plen;

  TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);

  if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
  {
2258
      TRACE("failed (%d)\n",GetLastError());
2259
      msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
2260 2261 2262
      return -1;
  }

2263
  memset(buf,0,sizeof(struct MSVCRT__stat64));
2264

2265 2266
  /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
  if (MSVCRT_iswalpha(*path))
2267
    buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
2268
  else
2269
    buf->st_dev = buf->st_rdev = MSVCRT__getdrive() - 1;
2270

2271
  plen = strlenW(path);
2272 2273 2274

  /* Dir, or regular file? */
  if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
2275
      (path[plen-1] == '\\'))
2276
    mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
2277 2278
  else
  {
2279
    mode |= MSVCRT__S_IFREG;
2280
    /* executable? */
2281
    if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
2282
    {
2283 2284
      ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
                               ((ULONGLONG)tolowerW(path[plen-3]) << 32);
2285
      if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
2286
        mode |= ALL_S_IEXEC;
2287 2288 2289 2290
    }
  }

  if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
2291
    mode |= ALL_S_IWRITE;
2292 2293 2294

  buf->st_mode  = mode;
  buf->st_nlink = 1;
2295
  buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
2296
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
2297
  buf->st_atime = dw;
2298
  RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
2299
  buf->st_mtime = buf->st_ctime = dw;
2300 2301 2302
  TRACE("%d %d 0x%08x%08x %d %d %d\n", buf->st_mode,buf->st_nlink,
        (int)(buf->st_size >> 32),(int)buf->st_size,
        (int)buf->st_atime,(int)buf->st_mtime,(int)buf->st_ctime);
2303 2304 2305
  return 0;
}

2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
/*********************************************************************
 *		_wstati64 (MSVCRT.@)
 */
int CDECL MSVCRT__wstati64(const MSVCRT_wchar_t* path, struct MSVCRT__stati64 * buf)
{
  int ret;
  struct MSVCRT__stat64 buf64;

  ret = MSVCRT__wstat64(path, &buf64);
  if (!ret)
    msvcrt_stat64_to_stati64(&buf64, buf);
  return ret;
}

2320 2321 2322
/*********************************************************************
 *		_wstat (MSVCRT.@)
 */
2323
int CDECL MSVCRT__wstat(const MSVCRT_wchar_t* path, struct MSVCRT__stat * buf)
2324 2325
{
  int ret;
2326
  struct MSVCRT__stat64 buf64;
2327

2328 2329
  ret = MSVCRT__wstat64( path, &buf64 );
  if (!ret) msvcrt_stat64_to_stat(&buf64, buf);
2330 2331 2332
  return ret;
}

2333 2334 2335
/*********************************************************************
 *		_tell (MSVCRT.@)
 */
2336
MSVCRT_long CDECL MSVCRT__tell(int fd)
2337
{
2338
  return MSVCRT__lseek(fd, 0, SEEK_CUR);
2339 2340
}

2341 2342 2343
/*********************************************************************
 *		_telli64 (MSVCRT.@)
 */
2344
__int64 CDECL _telli64(int fd)
2345
{
2346
  return MSVCRT__lseeki64(fd, 0, SEEK_CUR);
2347 2348
}

2349 2350 2351
/*********************************************************************
 *		_tempnam (MSVCRT.@)
 */
2352
char * CDECL MSVCRT__tempnam(const char *dir, const char *prefix)
2353 2354
{
  char tmpbuf[MAX_PATH];
2355 2356 2357
  const char *tmp_dir = MSVCRT_getenv("TMP");

  if (tmp_dir) dir = tmp_dir;
2358 2359 2360 2361 2362

  TRACE("dir (%s) prefix (%s)\n",dir,prefix);
  if (GetTempFileNameA(dir,prefix,0,tmpbuf))
  {
    TRACE("got name (%s)\n",tmpbuf);
2363
    DeleteFileA(tmpbuf);
2364
    return MSVCRT__strdup(tmpbuf);
2365
  }
2366
  TRACE("failed (%d)\n",GetLastError());
2367 2368 2369 2370 2371 2372
  return NULL;
}

/*********************************************************************
 *		_wtempnam (MSVCRT.@)
 */
2373
MSVCRT_wchar_t * CDECL MSVCRT__wtempnam(const MSVCRT_wchar_t *dir, const MSVCRT_wchar_t *prefix)
2374
{
2375
  static const MSVCRT_wchar_t tmpW[] = {'T','M','P',0};
2376
  MSVCRT_wchar_t tmpbuf[MAX_PATH];
2377 2378 2379
  const MSVCRT_wchar_t *tmp_dir = MSVCRT__wgetenv(tmpW);

  if (tmp_dir) dir = tmp_dir;
2380 2381 2382 2383 2384

  TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
  if (GetTempFileNameW(dir,prefix,0,tmpbuf))
  {
    TRACE("got name (%s)\n",debugstr_w(tmpbuf));
2385
    DeleteFileW(tmpbuf);
2386
    return MSVCRT__wcsdup(tmpbuf);
2387
  }
2388
  TRACE("failed (%d)\n",GetLastError());
2389 2390 2391 2392 2393 2394
  return NULL;
}

/*********************************************************************
 *		_umask (MSVCRT.@)
 */
2395
int CDECL MSVCRT__umask(int umask)
2396 2397
{
  int old_umask = MSVCRT_umask;
2398
  TRACE("(%d)\n",umask);
2399 2400 2401 2402 2403
  MSVCRT_umask = umask;
  return old_umask;
}

/*********************************************************************
2404
 *		_utime64 (MSVCRT.@)
2405
 */
2406
int CDECL _utime64(const char* path, struct MSVCRT___utimbuf64 *t)
2407
{
2408
  int fd = MSVCRT__open(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
2409 2410 2411

  if (fd > 0)
  {
2412
    int retVal = _futime64(fd, t);
2413
    MSVCRT__close(fd);
2414 2415 2416 2417 2418
    return retVal;
  }
  return -1;
}

2419
/*********************************************************************
2420 2421 2422 2423
 *		_utime32 (MSVCRT.@)
 */
int CDECL _utime32(const char* path, struct MSVCRT___utimbuf32 *t)
{
2424 2425 2426 2427 2428 2429 2430 2431 2432
    if (t)
    {
        struct MSVCRT___utimbuf64 t64;
        t64.actime = t->actime;
        t64.modtime = t->modtime;
        return _utime64( path, &t64 );
    }
    else
        return _utime64( path, NULL );
2433 2434 2435 2436
}

/*********************************************************************
 *		_utime (MSVCRT.@)
2437
 */
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
#ifdef _WIN64
int CDECL _utime(const char* path, struct MSVCRT___utimbuf64 *t)
{
    return _utime64( path, t );
}
#else
int CDECL _utime(const char* path, struct MSVCRT___utimbuf32 *t)
{
    return _utime32( path, t );
}
#endif

/*********************************************************************
 *		_wutime64 (MSVCRT.@)
 */
int CDECL _wutime64(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf64 *t)
2454
{
2455
  int fd = MSVCRT__wopen(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
2456 2457 2458

  if (fd > 0)
  {
2459
    int retVal = _futime64(fd, t);
2460
    MSVCRT__close(fd);
2461 2462 2463 2464 2465
    return retVal;
  }
  return -1;
}

2466 2467 2468 2469 2470
/*********************************************************************
 *		_wutime32 (MSVCRT.@)
 */
int CDECL _wutime32(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf32 *t)
{
2471 2472 2473 2474 2475 2476 2477 2478 2479
    if (t)
    {
        struct MSVCRT___utimbuf64 t64;
        t64.actime = t->actime;
        t64.modtime = t->modtime;
        return _wutime64( path, &t64 );
    }
    else
        return _wutime64( path, NULL );
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
}

/*********************************************************************
 *		_wutime (MSVCRT.@)
 */
#ifdef _WIN64
int CDECL _wutime(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf64 *t)
{
    return _wutime64( path, t );
}
#else
int CDECL _wutime(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf32 *t)
{
    return _wutime32( path, t );
}
#endif

2497 2498 2499
/*********************************************************************
 *		_write (MSVCRT.@)
 */
2500
int CDECL MSVCRT__write(int fd, const void* buf, unsigned int count)
2501 2502
{
  DWORD num_written;
2503
  HANDLE hand = msvcrt_fdtoh(fd);
2504

2505
  /* Don't trace small writes, it gets *very* annoying */
2506 2507 2508 2509
#if 0
  if (count > 32)
    TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
#endif
2510
  if (hand == INVALID_HANDLE_VALUE)
2511 2512 2513 2514
    {
      *MSVCRT__errno() = MSVCRT_EBADF;
      return -1;
    }
2515 2516

  /* If appending, go to EOF */
2517
  if (msvcrt_get_ioinfo(fd)->wxflag & WX_APPEND)
2518
    MSVCRT__lseek(fd, 0, FILE_END);
2519

2520
  if (!(msvcrt_get_ioinfo(fd)->wxflag & WX_TEXT))
2521 2522 2523 2524
    {
      if (WriteFile(hand, buf, count, &num_written, NULL)
	  &&  (num_written == count))
	return num_written;
2525
      TRACE("WriteFile (fd %d, hand %p) failed-last error (%d)\n", fd,
2526
       hand, GetLastError());
2527
      *MSVCRT__errno() = MSVCRT_ENOSPC;
2528 2529
    }
  else
2530 2531
  {
      unsigned int i, j, nr_lf;
2532 2533
      char *p = NULL;
      const char *q;
2534
      const char *s = buf, *buf_start = buf;
2535
      /* find number of \n ( without preceding \r ) */
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
      for ( nr_lf=0,i = 0; i <count; i++)
      {
          if (s[i]== '\n')
          {
              nr_lf++;
              /*if ((i >1) && (s[i-1] == '\r'))	nr_lf--; */
          }
      }
      if (nr_lf)
      {
2546
          if ((q = p = MSVCRT_malloc(count + nr_lf)))
2547
          {
2548
              for (s = buf, i = 0, j = 0; i < count; i++)
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
              {
                  if (s[i]== '\n')
                  {
                      p[j++] = '\r';
                      /*if ((i >1) && (s[i-1] == '\r'))j--;*/
                  }
                  p[j++] = s[i];
              }
          }
          else
          {
              FIXME("Malloc failed\n");
              nr_lf =0;
2562
              q = buf;
2563 2564 2565
          }
      }
      else
2566
          q = buf;
2567

2568
      if ((WriteFile(hand, q, count+nr_lf, &num_written, NULL) == 0 ) || (num_written != count+nr_lf))
2569
      {
2570
          TRACE("WriteFile (fd %d, hand %p) failed-last error (%d), num_written %d\n",
2571
           fd, hand, GetLastError(), num_written);
2572 2573 2574 2575
          *MSVCRT__errno() = MSVCRT_ENOSPC;
          if(nr_lf)
              MSVCRT_free(p);
          return s - buf_start;
2576 2577 2578 2579 2580 2581 2582 2583
      }
      else
      {
          if(nr_lf)
              MSVCRT_free(p);
          return count;
      }
  }
2584 2585 2586 2587 2588 2589
  return -1;
}

/*********************************************************************
 *		_putw (MSVCRT.@)
 */
2590
int CDECL MSVCRT__putw(int val, MSVCRT_FILE* file)
2591
{
2592
  int len;
2593 2594

  MSVCRT__lock_file(file);
2595
  len = MSVCRT__write(file->_file, &val, sizeof(val));
2596 2597 2598 2599 2600
  if (len == sizeof(val)) {
    MSVCRT__unlock_file(file);
    return val;
  }

2601
  file->_flag |= MSVCRT__IOERR;
2602
  MSVCRT__unlock_file(file);
2603
  return MSVCRT_EOF;
2604 2605 2606 2607 2608
}

/*********************************************************************
 *		fclose (MSVCRT.@)
 */
2609
int CDECL MSVCRT_fclose(MSVCRT_FILE* file)
2610
{
2611 2612
  int r, flag;

2613
  MSVCRT__lock_file(file);
2614
  flag = file->_flag;
2615 2616
  MSVCRT_free(file->_tmpfname);
  file->_tmpfname = NULL;
2617 2618 2619 2620 2621 2622
  /* flush stdio buffers */
  if(file->_flag & MSVCRT__IOWRT)
      MSVCRT_fflush(file);
  if(file->_flag & MSVCRT__IOMYBUF)
      MSVCRT_free(file->_base);

2623
  r=MSVCRT__close(file->_file);
2624 2625

  file->_flag = 0;
2626
  MSVCRT__unlock_file(file);
2627

2628
  return ((r == -1) || (flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
2629 2630 2631 2632 2633
}

/*********************************************************************
 *		feof (MSVCRT.@)
 */
2634
int CDECL MSVCRT_feof(MSVCRT_FILE* file)
2635
{
2636
    return file->_flag & MSVCRT__IOEOF;
2637 2638 2639 2640 2641
}

/*********************************************************************
 *		ferror (MSVCRT.@)
 */
2642
int CDECL MSVCRT_ferror(MSVCRT_FILE* file)
2643
{
2644
    return file->_flag & MSVCRT__IOERR;
2645 2646 2647 2648 2649
}

/*********************************************************************
 *		_filbuf (MSVCRT.@)
 */
2650
int CDECL MSVCRT__filbuf(MSVCRT_FILE* file)
2651
{
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
    unsigned char c;
    MSVCRT__lock_file(file);

    /* Allocate buffer if needed */
    if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF))
        msvcrt_alloc_buffer(file);

    if(!(file->_flag & MSVCRT__IOREAD)) {
        if(file->_flag & MSVCRT__IORW)
            file->_flag |= MSVCRT__IOREAD;
        else {
            MSVCRT__unlock_file(file);
            return MSVCRT_EOF;
        }
    }

    if(file->_flag & MSVCRT__IONBF) {
2669
        int r;
2670
        if ((r = read_i(file->_file,&c,1)) != 1) {
2671
            file->_flag |= (r == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
2672
            MSVCRT__unlock_file(file);
2673
            return MSVCRT_EOF;
2674 2675 2676 2677 2678 2679 2680
        }

        MSVCRT__unlock_file(file);
        return c;
    } else {
        file->_cnt = read_i(file->_file, file->_base, file->_bufsiz);
        if(file->_cnt<=0) {
2681 2682
            file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
            file->_cnt = 0;
2683
            MSVCRT__unlock_file(file);
2684
            return MSVCRT_EOF;
2685 2686 2687 2688 2689 2690 2691 2692
        }

        file->_cnt--;
        file->_ptr = file->_base+1;
        c = *(unsigned char *)file->_base;
        MSVCRT__unlock_file(file);
        return c;
    }
2693 2694 2695
}

/*********************************************************************
2696
 *		fgetc (MSVCRT.@)
2697
 */
2698
int CDECL MSVCRT_fgetc(MSVCRT_FILE* file)
2699
{
2700 2701
  unsigned char *i;
  unsigned int j;
2702 2703

  MSVCRT__lock_file(file);
2704 2705 2706 2707 2708 2709
  if (file->_cnt>0) {
    file->_cnt--;
    i = (unsigned char *)file->_ptr++;
    j = *i;
  } else
    j = MSVCRT__filbuf(file);
2710 2711

  MSVCRT__unlock_file(file);
2712
  return j;
2713 2714 2715 2716 2717
}

/*********************************************************************
 *		_fgetchar (MSVCRT.@)
 */
2718
int CDECL MSVCRT__fgetchar(void)
2719 2720
{
  return MSVCRT_fgetc(MSVCRT_stdin);
2721 2722 2723 2724 2725
}

/*********************************************************************
 *		fgets (MSVCRT.@)
 */
2726
char * CDECL MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
2727
{
2728
  int    cc = MSVCRT_EOF;
2729 2730 2731 2732 2733
  char * buf_start = s;

  TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
	file,file->_file,s,size);

2734 2735
  MSVCRT__lock_file(file);

2736
  while ((size >1) && (cc = MSVCRT_fgetc(file)) != MSVCRT_EOF && cc != '\n')
2737 2738
    {
      *s++ = (char)cc;
2739
      size --;
2740 2741 2742 2743
    }
  if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
  {
    TRACE(":nothing read\n");
2744
    MSVCRT__unlock_file(file);
2745
    return NULL;
2746
  }
2747 2748
  if ((cc != MSVCRT_EOF) && (size > 1))
    *s++ = cc;
2749
  *s = '\0';
Paul Rupe's avatar
Paul Rupe committed
2750
  TRACE(":got %s\n", debugstr_a(buf_start));
2751
  MSVCRT__unlock_file(file);
2752 2753 2754 2755 2756
  return buf_start;
}

/*********************************************************************
 *		fgetwc (MSVCRT.@)
2757
 *
2758
 * In MSVCRT__O_TEXT mode, multibyte characters are read from the file, dropping
2759
 * the CR from CR/LF combinations
2760
 */
2761
MSVCRT_wint_t CDECL MSVCRT_fgetwc(MSVCRT_FILE* file)
2762
{
2763
  int c;
2764

2765
  MSVCRT__lock_file(file);
2766
  if (!(msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT))
2767 2768
    {
      MSVCRT_wchar_t wc;
2769 2770
      unsigned int i;
      int j;
2771 2772 2773
      char *chp, *wcp;
      wcp = (char *)&wc;
      for(i=0; i<sizeof(wc); i++)
2774
      {
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
        if (file->_cnt>0) 
        {
          file->_cnt--;
          chp = file->_ptr++;
          wcp[i] = *chp;
        } 
        else
        {
          j = MSVCRT__filbuf(file);
          if(file->_cnt<=0)
          {
            file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
            file->_cnt = 0;
2788 2789

            MSVCRT__unlock_file(file);
2790 2791 2792 2793
            return MSVCRT_WEOF;
          }
          wcp[i] = j;
        }
2794
      }
2795 2796

      MSVCRT__unlock_file(file);
2797 2798
      return wc;
    }
2799
    
2800
  c = MSVCRT_fgetc(file);
2801
  if ((get_locinfo()->mb_cur_max > 1) && MSVCRT_isleadbyte(c))
2802 2803 2804
    {
      FIXME("Treat Multibyte characters\n");
    }
2805 2806

  MSVCRT__unlock_file(file);
2807
  if (c == MSVCRT_EOF)
2808
    return MSVCRT_WEOF;
2809 2810
  else
    return (MSVCRT_wint_t)c;
2811 2812
}

Duane Clark's avatar
Duane Clark committed
2813 2814 2815 2816 2817 2818
/*********************************************************************
 *		_getw (MSVCRT.@)
 */
int CDECL MSVCRT__getw(MSVCRT_FILE* file)
{
  char *ch;
2819 2820
  int i, k;
  unsigned int j;
Duane Clark's avatar
Duane Clark committed
2821
  ch = (char *)&i;
2822 2823

  MSVCRT__lock_file(file);
Duane Clark's avatar
Duane Clark committed
2824 2825 2826 2827
  for (j=0; j<sizeof(int); j++) {
    k = MSVCRT_fgetc(file);
    if (k == MSVCRT_EOF) {
      file->_flag |= MSVCRT__IOEOF;
2828
      MSVCRT__unlock_file(file);
Duane Clark's avatar
Duane Clark committed
2829 2830 2831 2832
      return EOF;
    }
    ch[j] = k;
  }
2833 2834

  MSVCRT__unlock_file(file);
Duane Clark's avatar
Duane Clark committed
2835 2836 2837
  return i;
}

2838 2839 2840
/*********************************************************************
 *		getwc (MSVCRT.@)
 */
2841
MSVCRT_wint_t CDECL MSVCRT_getwc(MSVCRT_FILE* file)
2842 2843 2844 2845 2846 2847 2848
{
  return MSVCRT_fgetwc(file);
}

/*********************************************************************
 *		_fgetwchar (MSVCRT.@)
 */
2849
MSVCRT_wint_t CDECL MSVCRT__fgetwchar(void)
2850 2851 2852 2853 2854 2855 2856
{
  return MSVCRT_fgetwc(MSVCRT_stdin);
}

/*********************************************************************
 *		getwchar (MSVCRT.@)
 */
2857
MSVCRT_wint_t CDECL MSVCRT_getwchar(void)
2858
{
2859
  return MSVCRT__fgetwchar();
2860 2861
}

2862 2863 2864
/*********************************************************************
 *              fgetws (MSVCRT.@)
 */
2865
MSVCRT_wchar_t * CDECL MSVCRT_fgetws(MSVCRT_wchar_t *s, int size, MSVCRT_FILE* file)
2866
{
2867
  int    cc = MSVCRT_WEOF;
2868
  MSVCRT_wchar_t * buf_start = s;
2869 2870 2871 2872

  TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
        file,file->_file,s,size);

2873 2874
  MSVCRT__lock_file(file);

2875
  while ((size >1) && (cc = MSVCRT_fgetwc(file)) != MSVCRT_WEOF && cc != '\n')
2876
    {
2877 2878
      *s++ = (char)cc;
      size --;
2879
    }
2880
  if ((cc == MSVCRT_WEOF) && (s == buf_start)) /* If nothing read, return 0*/
2881 2882
  {
    TRACE(":nothing read\n");
2883
    MSVCRT__unlock_file(file);
2884
    return NULL;
2885
  }
2886 2887 2888 2889
  if ((cc != MSVCRT_WEOF) && (size > 1))
    *s++ = cc;
  *s = 0;
  TRACE(":got %s\n", debugstr_w(buf_start));
2890
  MSVCRT__unlock_file(file);
2891 2892 2893
  return buf_start;
}

2894 2895 2896
/*********************************************************************
 *		fwrite (MSVCRT.@)
 */
2897
MSVCRT_size_t CDECL MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2898
{
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
    MSVCRT_size_t wrcnt=size * nmemb;
    int written = 0;
    if (size == 0)
        return 0;

    MSVCRT__lock_file(file);
    if(file->_cnt) {
        int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
        memcpy(file->_ptr, ptr, pcnt);
        file->_cnt -= pcnt;
        file->_ptr += pcnt;
        written = pcnt;
        wrcnt -= pcnt;
2912
        ptr = (const char*)ptr + pcnt;
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
    } else if(!(file->_flag & MSVCRT__IOWRT)) {
        if(file->_flag & MSVCRT__IORW) {
            file->_flag |= MSVCRT__IOWRT;
        } else {
            MSVCRT__unlock_file(file);
            return 0;
        }
    }
    if(wrcnt) {
        /* Flush buffer */
        int res=msvcrt_flush_buffer(file);
        if(!res) {
            int pwritten = MSVCRT__write(file->_file, ptr, wrcnt);
            if (pwritten <= 0)
            {
                file->_flag |= MSVCRT__IOERR;
                pwritten=0;
            }
            written += pwritten;
        }
    }

    MSVCRT__unlock_file(file);
    return written / size;
2937
}
2938

2939 2940 2941
/*********************************************************************
 *		fputwc (MSVCRT.@)
 */
2942
MSVCRT_wint_t CDECL MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
2943
{
2944
  MSVCRT_wchar_t mwc=wc;
2945
  if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
2946 2947 2948 2949 2950 2951 2952
    return MSVCRT_WEOF;
  return wc;
}

/*********************************************************************
 *		_fputwchar (MSVCRT.@)
 */
2953
MSVCRT_wint_t CDECL MSVCRT__fputwchar(MSVCRT_wint_t wc)
2954 2955 2956 2957 2958
{
  return MSVCRT_fputwc(wc, MSVCRT_stdout);
}

/*********************************************************************
2959
 *		_wfsopen (MSVCRT.@)
2960
 */
2961
MSVCRT_FILE * CDECL MSVCRT__wfsopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, int share)
2962 2963
{
  MSVCRT_FILE* file;
2964
  int open_flags, stream_flags, fd;
2965

2966
  TRACE("(%s,%s)\n", debugstr_w(path), debugstr_w(mode));
2967 2968

  /* map mode string to open() flags. "man fopen" for possibilities. */
2969 2970
  if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
      return NULL;
2971

2972
  LOCK_FILES();
2973
  fd = MSVCRT__wsopen(path, open_flags, share, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
2974
  if (fd < 0)
2975 2976 2977
    file = NULL;
  else if ((file = msvcrt_alloc_fp()) && msvcrt_init_fp(file, fd, stream_flags)
   != -1)
2978
    TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
2979 2980 2981 2982 2983 2984
  else if (file)
  {
    file->_flag = 0;
    file = NULL;
  }

2985
  TRACE(":got (%p)\n",file);
2986
  if (fd >= 0 && !file)
2987
    MSVCRT__close(fd);
2988
  UNLOCK_FILES();
2989 2990 2991
  return file;
}

2992
/*********************************************************************
2993
 *		_fsopen (MSVCRT.@)
2994
 */
2995
MSVCRT_FILE * CDECL MSVCRT__fsopen(const char *path, const char *mode, int share)
2996
{
2997 2998
    MSVCRT_FILE *ret;
    MSVCRT_wchar_t *pathW = NULL, *modeW = NULL;
2999

3000 3001 3002 3003 3004
    if (path && !(pathW = msvcrt_wstrdupa(path))) {
        MSVCRT__invalid_parameter(NULL, NULL, NULL, 0, 0);
        *MSVCRT__errno() = MSVCRT_EINVAL;
        return NULL;
    }
3005 3006 3007
    if (mode && !(modeW = msvcrt_wstrdupa(mode)))
    {
        MSVCRT_free(pathW);
3008 3009
        MSVCRT__invalid_parameter(NULL, NULL, NULL, 0, 0);
        *MSVCRT__errno() = MSVCRT_EINVAL;
3010 3011
        return NULL;
    }
3012

3013
    ret = MSVCRT__wfsopen(pathW, modeW, share);
3014

3015 3016 3017
    MSVCRT_free(pathW);
    MSVCRT_free(modeW);
    return ret;
3018 3019
}

3020
/*********************************************************************
3021
 *		fopen (MSVCRT.@)
3022
 */
3023
MSVCRT_FILE * CDECL MSVCRT_fopen(const char *path, const char *mode)
3024
{
3025
    return MSVCRT__fsopen( path, mode, MSVCRT__SH_DENYNO );
3026 3027
}

3028 3029 3030 3031 3032 3033
/*********************************************************************
 *              fopen_s (MSVCRT.@)
 */
int CDECL MSVCRT_fopen_s(MSVCRT_FILE** pFile,
        const char *filename, const char *mode)
{
3034 3035 3036
    if (!MSVCRT_CHECK_PMT(pFile != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(filename != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(mode != NULL)) return MSVCRT_EINVAL;
3037 3038 3039 3040 3041 3042 3043 3044

    *pFile = MSVCRT_fopen(filename, mode);

    if(!*pFile)
        return *MSVCRT__errno();
    return 0;
}

3045
/*********************************************************************
3046
 *		_wfopen (MSVCRT.@)
3047
 */
3048
MSVCRT_FILE * CDECL MSVCRT__wfopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode)
3049
{
3050
    return MSVCRT__wfsopen( path, mode, MSVCRT__SH_DENYNO );
3051 3052
}

3053 3054 3055 3056 3057 3058
/*********************************************************************
 *		_wfopen_s (MSVCRT.@)
 */
int CDECL MSVCRT__wfopen_s(MSVCRT_FILE** pFile, const MSVCRT_wchar_t *filename,
        const MSVCRT_wchar_t *mode)
{
3059 3060 3061
    if (!MSVCRT_CHECK_PMT(pFile != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(filename != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(mode != NULL)) return MSVCRT_EINVAL;
3062 3063 3064 3065 3066 3067 3068 3069

    *pFile = MSVCRT__wfopen(filename, mode);

    if(!*pFile)
        return *MSVCRT__errno();
    return 0;
}

3070 3071 3072
/*********************************************************************
 *		_flsbuf (MSVCRT.@)
 */
3073
int CDECL MSVCRT__flsbuf(int c, MSVCRT_FILE* file)
3074
{
3075 3076 3077 3078 3079
    /* Flush output buffer */
    if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
        msvcrt_alloc_buffer(file);
    }
    if(!(file->_flag & MSVCRT__IOWRT)) {
3080
        if(file->_flag & MSVCRT__IORW)
3081
            file->_flag |= MSVCRT__IOWRT;
3082
        else
3083 3084 3085
            return MSVCRT_EOF;
    }
    if(file->_bufsiz) {
3086 3087
        int res = 0;

3088
        if(file->_cnt <= 0)
3089 3090 3091 3092 3093 3094 3095 3096
            res = msvcrt_flush_buffer(file);
        if(!res) {
            *file->_ptr++ = c;
            file->_cnt--;
            res = msvcrt_flush_buffer(file);
        }

        return res ? res : c&0xff;
3097 3098
    } else {
        unsigned char cc=c;
3099
        int len;
Dan Kegel's avatar
Dan Kegel committed
3100 3101
        /* set _cnt to 0 for unbuffered FILEs */
        file->_cnt = 0;
3102
        len = MSVCRT__write(file->_file, &cc, 1);
3103
        if (len == 1)
3104
            return c & 0xff;
3105 3106
        file->_flag |= MSVCRT__IOERR;
        return MSVCRT_EOF;
3107
    }
3108 3109
}

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137
/*********************************************************************
 *		fputc (MSVCRT.@)
 */
int CDECL MSVCRT_fputc(int c, MSVCRT_FILE* file)
{
  int res;

  MSVCRT__lock_file(file);
  if(file->_cnt>0) {
    *file->_ptr++=c;
    file->_cnt--;
    if (c == '\n')
    {
      res = msvcrt_flush_buffer(file);
      MSVCRT__unlock_file(file);
      return res ? res : c;
    }
    else {
      MSVCRT__unlock_file(file);
      return c & 0xff;
    }
  } else {
    res = MSVCRT__flsbuf(c, file);
    MSVCRT__unlock_file(file);
    return res;
  }
}

3138 3139 3140
/*********************************************************************
 *		_fputchar (MSVCRT.@)
 */
3141
int CDECL MSVCRT__fputchar(int c)
3142 3143 3144 3145 3146 3147 3148
{
  return MSVCRT_fputc(c, MSVCRT_stdout);
}

/*********************************************************************
 *		fread (MSVCRT.@)
 */
3149
MSVCRT_size_t CDECL MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
3150 3151
{
  MSVCRT_size_t rcnt=size * nmemb;
3152 3153
  MSVCRT_size_t read=0;
  int pread=0;
3154

3155 3156 3157
  if(!rcnt)
	return 0;

3158 3159
  MSVCRT__lock_file(file);

3160
  /* first buffered data */
3161
  if(file->_cnt>0) {
3162 3163 3164 3165 3166 3167
	int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
	memcpy(ptr, file->_ptr, pcnt);
	file->_cnt -= pcnt;
	file->_ptr += pcnt;
	read += pcnt ;
	rcnt -= pcnt ;
3168
        ptr = (char*)ptr + pcnt;
3169 3170
  } else if(!(file->_flag & MSVCRT__IOREAD )) {
	if(file->_flag & MSVCRT__IORW) {
3171
		file->_flag |= MSVCRT__IOREAD;
3172 3173 3174 3175
	} else {
        MSVCRT__unlock_file(file);
        return 0;
    }
3176
  }
Duane Clark's avatar
Duane Clark committed
3177
  while(rcnt>0)
3178
  {
3179 3180 3181 3182 3183 3184 3185 3186
    int i;
    /* Fill the buffer on small reads.
     * TODO: Use a better buffering strategy.
     */
    if (!file->_cnt && size*nmemb <= MSVCRT_BUFSIZ/2 && !(file->_flag & MSVCRT__IONBF)) {
      if (file->_bufsiz == 0) {
        msvcrt_alloc_buffer(file);
      }
3187
      file->_cnt = MSVCRT__read(file->_file, file->_base, file->_bufsiz);
3188 3189 3190 3191
      file->_ptr = file->_base;
      i = (file->_cnt<rcnt) ? file->_cnt : rcnt;
      /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
      if (i > 0 && i < file->_cnt) {
3192
        msvcrt_get_ioinfo(file->_file)->wxflag &= ~WX_ATEOF;
3193
        file->_flag &= ~MSVCRT__IOEOF;
3194 3195 3196 3197 3198 3199 3200
      }
      if (i > 0) {
        memcpy(ptr, file->_ptr, i);
        file->_cnt -= i;
        file->_ptr += i;
      }
    } else {
3201
      i = MSVCRT__read(file->_file,ptr, rcnt);
3202
    }
Duane Clark's avatar
Duane Clark committed
3203 3204
    pread += i;
    rcnt -= i;
3205
    ptr = (char *)ptr+i;
3206
    /* expose feof condition in the flags
3207
     * MFC tests file->_flag for feof, and doesn't call feof())
3208
     */
3209
    if (msvcrt_get_ioinfo(file->_file)->wxflag & WX_ATEOF)
3210
        file->_flag |= MSVCRT__IOEOF;
Duane Clark's avatar
Duane Clark committed
3211
    else if (i == -1)
3212 3213 3214
    {
        file->_flag |= MSVCRT__IOERR;
        pread = 0;
Duane Clark's avatar
Duane Clark committed
3215
        rcnt = 0;
3216
    }
3217
    if (i < 1) break;
3218 3219
  }
  read+=pread;
3220
  MSVCRT__unlock_file(file);
3221 3222 3223 3224
  return read / size;
}

/*********************************************************************
3225
 *		_wfreopen (MSVCRT.@)
3226 3227
 *
 */
3228
MSVCRT_FILE* CDECL MSVCRT__wfreopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, MSVCRT_FILE* file)
3229
{
3230
  int open_flags, stream_flags, fd;
3231

3232
  TRACE(":path (%s) mode (%s) file (%p) fd (%d)\n", debugstr_w(path), debugstr_w(mode), file, file->_file);
3233

3234 3235 3236 3237
  LOCK_FILES();
  if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
    file = NULL;
  else
3238
  {
3239 3240 3241 3242 3243 3244
    MSVCRT_fclose(file);
    /* map mode string to open() flags. "man fopen" for possibilities. */
    if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
      file = NULL;
    else
    {
3245
      fd = MSVCRT__wopen(path, open_flags, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
3246 3247 3248 3249 3250
      if (fd < 0)
        file = NULL;
      else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
      {
          file->_flag = 0;
3251
          WARN(":failed-last error (%d)\n",GetLastError());
3252 3253 3254 3255
          msvcrt_set_errno(GetLastError());
          file = NULL;
      }
    }
3256
  }
3257
  UNLOCK_FILES();
3258
  return file;
3259 3260
}

3261 3262 3263 3264 3265 3266
/*********************************************************************
 *      _wfreopen_s (MSVCRT.@)
 */
int CDECL MSVCRT__wfreopen_s(MSVCRT_FILE** pFile,
        const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, MSVCRT_FILE* file)
{
3267 3268 3269 3270
    if (!MSVCRT_CHECK_PMT(pFile != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(path != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(mode != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(file != NULL)) return MSVCRT_EINVAL;
3271 3272 3273 3274 3275 3276 3277 3278

    *pFile = MSVCRT__wfreopen(path, mode, file);

    if(!*pFile)
        return *MSVCRT__errno();
    return 0;
}

3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
/*********************************************************************
 *      freopen (MSVCRT.@)
 *
 */
MSVCRT_FILE* CDECL MSVCRT_freopen(const char *path, const char *mode, MSVCRT_FILE* file)
{
    MSVCRT_FILE *ret;
    MSVCRT_wchar_t *pathW = NULL, *modeW = NULL;

    if (path && !(pathW = msvcrt_wstrdupa(path))) return NULL;
    if (mode && !(modeW = msvcrt_wstrdupa(mode)))
    {
        MSVCRT_free(pathW);
        return NULL;
    }

3295
    ret = MSVCRT__wfreopen(pathW, modeW, file);
3296 3297 3298 3299 3300 3301

    MSVCRT_free(pathW);
    MSVCRT_free(modeW);
    return ret;
}

3302 3303 3304 3305 3306 3307
/*********************************************************************
 *      freopen_s (MSVCRT.@)
 */
int CDECL MSVCRT_freopen_s(MSVCRT_FILE** pFile,
        const char *path, const char *mode, MSVCRT_FILE* file)
{
3308 3309 3310 3311
    if (!MSVCRT_CHECK_PMT(pFile != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(path != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(mode != NULL)) return MSVCRT_EINVAL;
    if (!MSVCRT_CHECK_PMT(file != NULL)) return MSVCRT_EINVAL;
3312 3313 3314 3315 3316 3317 3318 3319

    *pFile = MSVCRT_freopen(path, mode, file);

    if(!*pFile)
        return *MSVCRT__errno();
    return 0;
}

3320 3321 3322
/*********************************************************************
 *		fsetpos (MSVCRT.@)
 */
3323
int CDECL MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
3324
{
3325 3326 3327
  int ret;

  MSVCRT__lock_file(file);
3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
  /* Note that all this has been lifted 'as is' from fseek */
  if(file->_flag & MSVCRT__IOWRT)
	msvcrt_flush_buffer(file);

  /* Discard buffered input */
  file->_cnt = 0;
  file->_ptr = file->_base;
  
  /* Reset direction of i/o */
  if(file->_flag & MSVCRT__IORW) {
        file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
  }

3341 3342 3343
  ret = (MSVCRT__lseeki64(file->_file,*pos,SEEK_SET) == -1) ? -1 : 0;
  MSVCRT__unlock_file(file);
  return ret;
3344 3345 3346
}

/*********************************************************************
3347
 *		_ftelli64 (MSVCRT.@)
3348
 */
3349
__int64 CDECL MSVCRT__ftelli64(MSVCRT_FILE* file)
3350
{
3351 3352 3353
    /* TODO: just call fgetpos and return lower half of result */
    int off=0;
    __int64 pos;
3354 3355

    MSVCRT__lock_file(file);
3356
    pos = _telli64(file->_file);
3357 3358 3359 3360
    if(pos == -1) {
        MSVCRT__unlock_file(file);
        return -1;
    }
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378
    if(file->_bufsiz)  {
        if( file->_flag & MSVCRT__IOWRT ) {
            off = file->_ptr - file->_base;
        } else {
            off = -file->_cnt;
            if (msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT) {
                /* Black magic correction for CR removal */
                int i;
                for (i=0; i<file->_cnt; i++) {
                    if (file->_ptr[i] == '\n')
                        off--;
                }
                /* Black magic when reading CR at buffer boundary*/
                if(msvcrt_get_ioinfo(file->_file)->wxflag & WX_READCR)
                    off--;
            }
        }
    }
3379 3380

    MSVCRT__unlock_file(file);
3381
    return off + pos;
3382 3383
}

3384 3385 3386 3387 3388 3389 3390 3391
/*********************************************************************
 *		ftell (MSVCRT.@)
 */
LONG CDECL MSVCRT_ftell(MSVCRT_FILE* file)
{
  return MSVCRT__ftelli64(file);
}

3392
/*********************************************************************
3393
 *		fgetpos (MSVCRT.@)
3394
 */
3395
int CDECL MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
3396
{
3397
    int off=0;
3398 3399

    MSVCRT__lock_file(file);
3400
    *pos = MSVCRT__lseeki64(file->_file,0,SEEK_CUR);
3401 3402 3403 3404
    if(*pos == -1) {
        MSVCRT__unlock_file(file);
        return -1;
    }
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
    if(file->_bufsiz)  {
        if( file->_flag & MSVCRT__IOWRT ) {
            off = file->_ptr - file->_base;
        } else {
            off = -file->_cnt;
            if (msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT) {
                /* Black magic correction for CR removal */
                int i;
                for (i=0; i<file->_cnt; i++) {
                    if (file->_ptr[i] == '\n')
                        off--;
                }
                /* Black magic when reading CR at buffer boundary*/
                if(msvcrt_get_ioinfo(file->_file)->wxflag & WX_READCR)
                    off--;
            }
        }
    }
    *pos += off;
3424
    MSVCRT__unlock_file(file);
3425
    return 0;
3426 3427 3428 3429 3430
}

/*********************************************************************
 *		fputs (MSVCRT.@)
 */
3431
int CDECL MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
3432
{
3433
    MSVCRT_size_t i, len = strlen(s);
3434 3435 3436 3437 3438 3439 3440 3441
    int ret;

    MSVCRT__lock_file(file);
    if (!(msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT)) {
      ret = MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
      MSVCRT__unlock_file(file);
      return ret;
    }
3442
    for (i=0; i<len; i++)
3443 3444 3445 3446 3447 3448
      if (MSVCRT_fputc(s[i], file) == MSVCRT_EOF)  {
        MSVCRT__unlock_file(file);
        return MSVCRT_EOF;
      }

    MSVCRT__unlock_file(file);
3449
    return 0;
3450 3451
}

3452 3453 3454
/*********************************************************************
 *		fputws (MSVCRT.@)
 */
3455
int CDECL MSVCRT_fputws(const MSVCRT_wchar_t *s, MSVCRT_FILE* file)
3456
{
3457
    MSVCRT_size_t i, len = strlenW(s);
3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
    int ret;

    MSVCRT__lock_file(file);
    if (!(msvcrt_get_ioinfo(file->_file)->wxflag & WX_TEXT)) {
        ret = MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
        MSVCRT__unlock_file(file);
        return ret;
    }
    for (i=0; i<len; i++) {
        if (((s[i] == '\n') && (MSVCRT_fputc('\r', file) == MSVCRT_EOF))
                || MSVCRT_fputwc(s[i], file) == MSVCRT_WEOF) {
            MSVCRT__unlock_file(file);
            return MSVCRT_WEOF;
        }
    }

    MSVCRT__unlock_file(file);
3475
    return 0;
3476 3477
}

3478 3479 3480
/*********************************************************************
 *		getchar (MSVCRT.@)
 */
3481
int CDECL MSVCRT_getchar(void)
3482 3483 3484 3485 3486 3487 3488
{
  return MSVCRT_fgetc(MSVCRT_stdin);
}

/*********************************************************************
 *		getc (MSVCRT.@)
 */
3489
int CDECL MSVCRT_getc(MSVCRT_FILE* file)
3490 3491 3492 3493 3494 3495 3496
{
  return MSVCRT_fgetc(file);
}

/*********************************************************************
 *		gets (MSVCRT.@)
 */
3497
char * CDECL MSVCRT_gets(char *buf)
3498 3499 3500 3501
{
  int    cc;
  char * buf_start = buf;

3502
  MSVCRT__lock_file(MSVCRT_stdin);
3503 3504 3505 3506 3507 3508 3509
  for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
      cc = MSVCRT_fgetc(MSVCRT_stdin))
  if(cc != '\r') *buf++ = (char)cc;

  *buf = '\0';

  TRACE("got '%s'\n", buf_start);
3510
  MSVCRT__unlock_file(MSVCRT_stdin);
3511 3512 3513
  return buf_start;
}

Francois Gouget's avatar
Francois Gouget committed
3514 3515 3516
/*********************************************************************
 *		_getws (MSVCRT.@)
 */
3517
MSVCRT_wchar_t* CDECL MSVCRT__getws(MSVCRT_wchar_t* buf)
Francois Gouget's avatar
Francois Gouget committed
3518 3519
{
    MSVCRT_wint_t cc;
3520
    MSVCRT_wchar_t* ws = buf;
Francois Gouget's avatar
Francois Gouget committed
3521

3522
    MSVCRT__lock_file(MSVCRT_stdin);
Francois Gouget's avatar
Francois Gouget committed
3523 3524 3525 3526
    for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
         cc = MSVCRT_fgetwc(MSVCRT_stdin))
    {
        if (cc != '\r')
3527
            *buf++ = (MSVCRT_wchar_t)cc;
Francois Gouget's avatar
Francois Gouget committed
3528 3529 3530
    }
    *buf = '\0';

3531
    TRACE("got %s\n", debugstr_w(ws));
3532
    MSVCRT__unlock_file(MSVCRT_stdin);
Francois Gouget's avatar
Francois Gouget committed
3533 3534 3535
    return ws;
}

3536 3537 3538
/*********************************************************************
 *		putc (MSVCRT.@)
 */
3539
int CDECL MSVCRT_putc(int c, MSVCRT_FILE* file)
3540 3541 3542 3543 3544 3545 3546
{
  return MSVCRT_fputc(c, file);
}

/*********************************************************************
 *		putchar (MSVCRT.@)
 */
3547
int CDECL MSVCRT_putchar(int c)
3548
{
3549
  return MSVCRT_fputc(c, MSVCRT_stdout);
3550 3551
}

3552 3553 3554 3555 3556 3557 3558 3559
/*********************************************************************
 *		_putwch (MSVCRT.@)
 */
int CDECL MSVCRT__putwch(int c)
{
  return MSVCRT_fputwc(c, MSVCRT_stdout);
}

3560 3561 3562
/*********************************************************************
 *		puts (MSVCRT.@)
 */
3563
int CDECL MSVCRT_puts(const char *s)
3564
{
3565
    MSVCRT_size_t len = strlen(s);
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
    int ret;

    MSVCRT__lock_file(MSVCRT_stdout);
    if(MSVCRT_fwrite(s, sizeof(*s), len, MSVCRT_stdout) != len) {
        MSVCRT__unlock_file(MSVCRT_stdout);
        return MSVCRT_EOF;
    }

    ret = MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
    MSVCRT__unlock_file(MSVCRT_stdout);
    return ret;
3577 3578
}

3579 3580 3581
/*********************************************************************
 *		_putws (MSVCRT.@)
 */
3582
int CDECL MSVCRT__putws(const MSVCRT_wchar_t *s)
3583
{
3584
    static const MSVCRT_wchar_t nl = '\n';
3585
    MSVCRT_size_t len = strlenW(s);
3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
    int ret;

    MSVCRT__lock_file(MSVCRT_stdout);
    if(MSVCRT_fwrite(s, sizeof(*s), len, MSVCRT_stdout) != len) {
        MSVCRT__unlock_file(MSVCRT_stdout);
        return MSVCRT_EOF;
    }

    ret = MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
    MSVCRT__unlock_file(MSVCRT_stdout);
    return ret;
3597 3598
}

3599 3600 3601
/*********************************************************************
 *		remove (MSVCRT.@)
 */
3602
int CDECL MSVCRT_remove(const char *path)
3603
{
3604
  TRACE("(%s)\n",path);
3605 3606
  if (DeleteFileA(path))
    return 0;
3607
  TRACE(":failed (%d)\n",GetLastError());
3608
  msvcrt_set_errno(GetLastError());
3609 3610 3611 3612 3613 3614
  return -1;
}

/*********************************************************************
 *		_wremove (MSVCRT.@)
 */
3615
int CDECL MSVCRT__wremove(const MSVCRT_wchar_t *path)
3616 3617 3618 3619
{
  TRACE("(%s)\n",debugstr_w(path));
  if (DeleteFileW(path))
    return 0;
3620
  TRACE(":failed (%d)\n",GetLastError());
3621
  msvcrt_set_errno(GetLastError());
3622 3623 3624 3625 3626 3627
  return -1;
}

/*********************************************************************
 *		rename (MSVCRT.@)
 */
3628
int CDECL MSVCRT_rename(const char *oldpath,const char *newpath)
3629 3630
{
  TRACE(":from %s to %s\n",oldpath,newpath);
3631
  if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
3632
    return 0;
3633
  TRACE(":failed (%d)\n",GetLastError());
3634
  msvcrt_set_errno(GetLastError());
3635 3636 3637
  return -1;
}

3638 3639 3640
/*********************************************************************
 *		_wrename (MSVCRT.@)
 */
3641
int CDECL MSVCRT__wrename(const MSVCRT_wchar_t *oldpath,const MSVCRT_wchar_t *newpath)
3642 3643
{
  TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
3644
  if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
3645
    return 0;
3646
  TRACE(":failed (%d)\n",GetLastError());
3647
  msvcrt_set_errno(GetLastError());
3648 3649 3650 3651 3652 3653
  return -1;
}

/*********************************************************************
 *		setvbuf (MSVCRT.@)
 */
3654
int CDECL MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
3655
{
3656
  MSVCRT__lock_file(file);
3657
  if(file->_bufsiz) {
3658 3659 3660 3661
	MSVCRT_free(file->_base);
	file->_bufsiz = 0;
	file->_cnt = 0;
  }
3662
  if(mode == MSVCRT__IOFBF) {
3663 3664
	file->_flag &= ~MSVCRT__IONBF;
  	file->_base = file->_ptr = buf;
3665
  	if(buf) {
3666
		file->_bufsiz = size;
3667
	}
3668 3669 3670
  } else {
	file->_flag |= MSVCRT__IONBF;
  }
3671
  MSVCRT__unlock_file(file);
3672
  return 0;
3673 3674
}

3675 3676 3677
/*********************************************************************
 *		setbuf (MSVCRT.@)
 */
3678
void CDECL MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
3679
{
3680
  MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
3681 3682 3683 3684 3685
}

/*********************************************************************
 *		tmpnam (MSVCRT.@)
 */
3686
char * CDECL MSVCRT_tmpnam(char *s)
3687
{
3688 3689
  char tmpstr[16];
  char *p;
3690
  int count, size;
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700

  if (!s) {
    thread_data_t *data = msvcrt_get_thread_data();

    if(!data->tmpnam_buffer)
      data->tmpnam_buffer = MSVCRT_malloc(MAX_PATH);

    s = data->tmpnam_buffer;
  }

3701 3702 3703
  msvcrt_int_to_base32(GetCurrentProcessId(), tmpstr);
  p = s + sprintf(s, "\\s%s.", tmpstr);
  for (count = 0; count < MSVCRT_TMP_MAX; count++)
3704
  {
3705 3706
    size = msvcrt_int_to_base32(tmpnam_unique++, tmpstr);
    memcpy(p, tmpstr, size);
3707
    p[size] = '\0';
3708 3709 3710
    if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
        GetLastError() == ERROR_FILE_NOT_FOUND)
      break;
3711 3712 3713 3714
  }
  return s;
}

3715 3716 3717
/*********************************************************************
 *              _wtmpnam (MSVCRT.@)
 */
3718
MSVCRT_wchar_t * CDECL MSVCRT_wtmpnam(MSVCRT_wchar_t *s)
3719 3720 3721 3722 3723
{
    static const MSVCRT_wchar_t format[] = {'\\','s','%','s','.',0};
    MSVCRT_wchar_t tmpstr[16];
    MSVCRT_wchar_t *p;
    int count, size;
3724 3725 3726 3727 3728 3729 3730 3731 3732
    if (!s) {
        thread_data_t *data = msvcrt_get_thread_data();

        if(!data->wtmpnam_buffer)
            data->wtmpnam_buffer = MSVCRT_malloc(sizeof(MSVCRT_wchar_t[MAX_PATH]));

        s = data->wtmpnam_buffer;
    }

3733 3734 3735 3736 3737 3738
    msvcrt_int_to_base32_w(GetCurrentProcessId(), tmpstr);
    p = s + MSVCRT__snwprintf(s, MAX_PATH, format, tmpstr);
    for (count = 0; count < MSVCRT_TMP_MAX; count++)
    {
        size = msvcrt_int_to_base32_w(tmpnam_unique++, tmpstr);
        memcpy(p, tmpstr, size*sizeof(MSVCRT_wchar_t));
3739
        p[size] = '\0';
3740 3741 3742 3743 3744 3745 3746
        if (GetFileAttributesW(s) == INVALID_FILE_ATTRIBUTES &&
                GetLastError() == ERROR_FILE_NOT_FOUND)
            break;
    }
    return s;
}

3747 3748 3749
/*********************************************************************
 *		tmpfile (MSVCRT.@)
 */
3750
MSVCRT_FILE* CDECL MSVCRT_tmpfile(void)
3751 3752 3753
{
  char *filename = MSVCRT_tmpnam(NULL);
  int fd;
3754 3755
  MSVCRT_FILE* file = NULL;

3756
  LOCK_FILES();
3757
  fd = MSVCRT__open(filename, MSVCRT__O_CREAT | MSVCRT__O_BINARY | MSVCRT__O_RDWR | MSVCRT__O_TEMPORARY);
3758 3759
  if (fd != -1 && (file = msvcrt_alloc_fp()))
  {
3760
    if (msvcrt_init_fp(file, fd, MSVCRT__O_RDWR) == -1)
3761 3762 3763 3764
    {
        file->_flag = 0;
        file = NULL;
    }
3765
    else file->_tmpfname = MSVCRT__strdup(filename);
3766
  }
3767
  UNLOCK_FILES();
3768
  return file;
3769 3770
}

3771 3772 3773 3774 3775
/*********************************************************************
 *      tmpfile_s (MSVCRT.@)
 */
int CDECL MSVCRT_tmpfile_s(MSVCRT_FILE** file)
{
3776
    if (!MSVCRT_CHECK_PMT(file != NULL)) return MSVCRT_EINVAL;
3777 3778 3779 3780 3781

    *file = MSVCRT_tmpfile();
    return 0;
}

3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
static int puts_clbk_file_a(void *file, int len, const char *str)
{
    return MSVCRT_fwrite(str, sizeof(char), len, file);
}

static int puts_clbk_file_w(void *file, int len, const MSVCRT_wchar_t *str)
{
    return MSVCRT_fwrite(str, sizeof(MSVCRT_wchar_t), len, file);
}

3792 3793 3794
/*********************************************************************
 *		vfprintf (MSVCRT.@)
 */
3795
int CDECL MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, __ms_va_list valist)
3796
{
3797 3798 3799 3800 3801 3802 3803
    int ret;

    MSVCRT__lock_file(file);
    ret = pf_printf_a(puts_clbk_file_a, file, format, NULL, FALSE, FALSE, arg_clbk_valist, NULL, &valist);
    MSVCRT__unlock_file(file);

    return ret;
3804 3805
}

3806 3807 3808 3809 3810
/*********************************************************************
 *		vfprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_vfprintf_s(MSVCRT_FILE* file, const char *format, __ms_va_list valist)
{
3811 3812
    int ret;

3813
    if(!MSVCRT_CHECK_PMT(file != NULL)) return -1;
3814

3815 3816 3817 3818 3819
    MSVCRT__lock_file(file);
    ret = pf_printf_a(puts_clbk_file_a, file, format, NULL, FALSE, TRUE, arg_clbk_valist, NULL, &valist);
    MSVCRT__unlock_file(file);

    return ret;
3820 3821
}

3822 3823 3824
/*********************************************************************
 *		vfwprintf (MSVCRT.@)
 */
3825
int CDECL MSVCRT_vfwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, __ms_va_list valist)
3826
{
3827 3828 3829 3830 3831 3832 3833
    int ret;

    MSVCRT__lock_file(file);
    ret = pf_printf_w(puts_clbk_file_w, file, format, NULL, FALSE, FALSE, arg_clbk_valist, NULL, &valist);
    MSVCRT__unlock_file(file);

    return ret;
3834 3835
}

3836 3837 3838 3839 3840
/*********************************************************************
 *		vfwprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_vfwprintf_s(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, __ms_va_list valist)
{
3841 3842
    int ret;

3843
    if (!MSVCRT_CHECK_PMT( file != NULL )) return -1;
3844

3845 3846 3847 3848 3849
    MSVCRT__lock_file(file);
    ret = pf_printf_w(puts_clbk_file_w, file, format, NULL, FALSE, TRUE, arg_clbk_valist, NULL, &valist);
    MSVCRT__unlock_file(file);

    return ret;
3850 3851
}

3852 3853 3854
/*********************************************************************
 *		vprintf (MSVCRT.@)
 */
3855
int CDECL MSVCRT_vprintf(const char *format, __ms_va_list valist)
3856 3857 3858 3859
{
  return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
}

3860 3861 3862 3863 3864 3865 3866 3867
/*********************************************************************
 *		vprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_vprintf_s(const char *format, __ms_va_list valist)
{
  return MSVCRT_vfprintf_s(MSVCRT_stdout,format,valist);
}

3868 3869 3870
/*********************************************************************
 *		vwprintf (MSVCRT.@)
 */
3871
int CDECL MSVCRT_vwprintf(const MSVCRT_wchar_t *format, __ms_va_list valist)
3872 3873
{
  return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
3874 3875
}

3876 3877 3878 3879 3880 3881 3882 3883
/*********************************************************************
 *		vwprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_vwprintf_s(const MSVCRT_wchar_t *format, __ms_va_list valist)
{
  return MSVCRT_vfwprintf_s(MSVCRT_stdout,format,valist);
}

3884 3885 3886
/*********************************************************************
 *		fprintf (MSVCRT.@)
 */
3887
int CDECL MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
3888
{
3889
    __ms_va_list valist;
3890
    int res;
3891
    __ms_va_start(valist, format);
3892
    res = MSVCRT_vfprintf(file, format, valist);
3893
    __ms_va_end(valist);
3894 3895 3896
    return res;
}

3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909
/*********************************************************************
 *		fprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_fprintf_s(MSVCRT_FILE* file, const char *format, ...)
{
    __ms_va_list valist;
    int res;
    __ms_va_start(valist, format);
    res = MSVCRT_vfprintf_s(file, format, valist);
    __ms_va_end(valist);
    return res;
}

3910 3911 3912
/*********************************************************************
 *		fwprintf (MSVCRT.@)
 */
3913
int CDECL MSVCRT_fwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, ...)
3914
{
3915
    __ms_va_list valist;
3916
    int res;
3917
    __ms_va_start(valist, format);
3918
    res = MSVCRT_vfwprintf(file, format, valist);
3919
    __ms_va_end(valist);
3920 3921 3922
    return res;
}

3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
/*********************************************************************
 *		fwprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_fwprintf_s(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, ...)
{
    __ms_va_list valist;
    int res;
    __ms_va_start(valist, format);
    res = MSVCRT_vfwprintf_s(file, format, valist);
    __ms_va_end(valist);
    return res;
}

3936 3937 3938
/*********************************************************************
 *		printf (MSVCRT.@)
 */
3939
int CDECL MSVCRT_printf(const char *format, ...)
3940
{
3941
    __ms_va_list valist;
3942
    int res;
3943
    __ms_va_start(valist, format);
3944
    res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
3945
    __ms_va_end(valist);
3946 3947 3948
    return res;
}

3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961
/*********************************************************************
 *		printf_s (MSVCRT.@)
 */
int CDECL MSVCRT_printf_s(const char *format, ...)
{
    __ms_va_list valist;
    int res;
    __ms_va_start(valist, format);
    res = MSVCRT_vprintf_s(format, valist);
    __ms_va_end(valist);
    return res;
}

3962 3963 3964
/*********************************************************************
 *		ungetc (MSVCRT.@)
 */
3965
int CDECL MSVCRT_ungetc(int c, MSVCRT_FILE * file)
3966
{
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
    if (c == MSVCRT_EOF)
        return MSVCRT_EOF;

    MSVCRT__lock_file(file);
    if(file->_bufsiz == 0) {
        msvcrt_alloc_buffer(file);
        file->_ptr++;
    }
    if(file->_ptr>file->_base) {
        file->_ptr--;
        *file->_ptr=c;
        file->_cnt++;
        MSVCRT_clearerr(file);
        MSVCRT__unlock_file(file);
        return c;
    }

    MSVCRT__unlock_file(file);
    return MSVCRT_EOF;
3986 3987 3988 3989 3990
}

/*********************************************************************
 *              ungetwc (MSVCRT.@)
 */
3991
MSVCRT_wint_t CDECL MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
3992
{
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
    MSVCRT_wchar_t mwc = wc;
    char * pp = (char *)&mwc;
    int i;

    MSVCRT__lock_file(file);
    for(i=sizeof(MSVCRT_wchar_t)-1;i>=0;i--) {
        if(pp[i] != MSVCRT_ungetc(pp[i],file)) {
            MSVCRT__unlock_file(file);
            return MSVCRT_WEOF;
        }
    }

    MSVCRT__unlock_file(file);
    return mwc;
4007 4008
}

4009 4010 4011
/*********************************************************************
 *		wprintf (MSVCRT.@)
 */
4012
int CDECL MSVCRT_wprintf(const MSVCRT_wchar_t *format, ...)
4013
{
4014
    __ms_va_list valist;
4015
    int res;
4016
    __ms_va_start(valist, format);
4017
    res = MSVCRT_vwprintf(format, valist);
4018
    __ms_va_end(valist);
4019 4020
    return res;
}
4021

4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034
/*********************************************************************
 *		wprintf_s (MSVCRT.@)
 */
int CDECL MSVCRT_wprintf_s(const MSVCRT_wchar_t *format, ...)
{
    __ms_va_list valist;
    int res;
    __ms_va_start(valist, format);
    res = MSVCRT_vwprintf_s(format, valist);
    __ms_va_end(valist);
    return res;
}

4035 4036 4037
/*********************************************************************
 *		_getmaxstdio (MSVCRT.@)
 */
4038
int CDECL MSVCRT__getmaxstdio(void)
4039
{
4040
    return MSVCRT_max_streams;
4041 4042
}

4043
/*********************************************************************
4044
 *		_setmaxstdio (MSVCRT.@)
4045
 */
4046
int CDECL MSVCRT__setmaxstdio(int newmax)
4047
{
4048 4049 4050 4051 4052 4053 4054
    TRACE("%d\n", newmax);

    if(newmax<_IOB_ENTRIES || newmax>MSVCRT_MAX_FILES || newmax<MSVCRT_stream_idx)
        return -1;

    MSVCRT_max_streams = newmax;
    return MSVCRT_max_streams;
4055
}