natFilePosix.cc 12.7 KB
Newer Older
1
// natFile.cc - Native part of File class for POSIX.
Tom Tromey committed
2

3 4
/* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2006
   Free Software Foundation
Tom Tromey committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

#include <config.h>

#include <stdio.h>
#include <errno.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stdlib.h>
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#include <string.h>
28
#include <utime.h>
Tom Tromey committed
29

Tom Tromey committed
30
#include <gcj/cni.h>
Tom Tromey committed
31 32 33
#include <jvm.h>
#include <java/io/File.h>
#include <java/io/IOException.h>
34
#include <java/util/ArrayList.h>
Tom Tromey committed
35 36
#include <java/lang/String.h>
#include <java/io/FilenameFilter.h>
37
#include <java/io/FileFilter.h>
Tom Tromey committed
38 39 40
#include <java/lang/System.h>

jboolean
41
java::io::File::_access (jint query)
Tom Tromey committed
42
{
43
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
44
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
Tom Tromey committed
45
  buf[total] = '\0';
46 47
  JvAssert (query == READ || query == WRITE || query == EXISTS
	    || query == EXEC);
Tom Tromey committed
48 49 50 51 52 53
#ifdef HAVE_ACCESS
  int mode;
  if (query == READ)
    mode = R_OK;
  else if (query == WRITE)
    mode = W_OK;
54
  else if (query == EXISTS)
Tom Tromey committed
55
    mode = F_OK;
56 57
  else
    mode = X_OK;
Tom Tromey committed
58 59 60 61 62 63 64
  return ::access (buf, mode) == 0;
#else
  return false;
#endif
}

jboolean
65
java::io::File::_stat (jint query)
Tom Tromey committed
66
{
67 68 69 70
  if (query == ISHIDDEN)
    return getName()->charAt(0) == '.';

#ifdef HAVE_STAT
71
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
72
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
Tom Tromey committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  buf[total] = '\0';

  struct stat sb;
  if (::stat (buf, &sb))
    return false;
  
  JvAssert (query == DIRECTORY || query == ISFILE);
  jboolean r = S_ISDIR (sb.st_mode);
  return query == DIRECTORY ? r : ! r;
#else
  return false;
#endif
}

jlong
88
java::io::File::attr (jint query)
Tom Tromey committed
89
{
90
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
91
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
Tom Tromey committed
92 93 94 95 96 97 98 99 100
  buf[total] = '\0';

#ifdef HAVE_STAT
  struct stat sb;
  // FIXME: not sure about return value here.
  if (::stat (buf, &sb))
    return 0;

  JvAssert (query == MODIFIED || query == LENGTH);
101
  return query == MODIFIED ? (jlong)sb.st_mtime * 1000 : sb.st_size;
Tom Tromey committed
102 103 104 105 106 107
#else
  // There's no good choice here.
  return 23;
#endif
}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
// These two methods are used to maintain dynamically allocated
// buffers for getCanonicalPath without the overhead of calling
// realloc every time a buffer is modified.  Buffers are sized
// at the smallest multiple of CHUNKSIZ that is greater than or
// equal to the desired length.  The default CHUNKSIZ is 256,
// longer than most paths, so in most cases a getCanonicalPath
// will require only one malloc per buffer.

#define CHUNKLOG 8
#define CHUNKSIZ (1 << CHUNKLOG)

static int
nextChunkSize (int size)
{
  return ((size >> CHUNKLOG) + ((size & (CHUNKSIZ - 1)) ? 1 : 0)) << CHUNKLOG;
}

static char *
maybeGrowBuf (char *buf, int *size, int required)
{
  if (required > *size)
    {
      *size = nextChunkSize (required);
      buf = (char *) _Jv_Realloc (buf, *size);
    }
  return buf;
}

// Return a canonical representation of the pathname of this file.  On
// the GNU system this involves the removal of redundant separators,
// references to "." and "..", and symbolic links.
//
// The conversion proceeds on a component-by-component basis: symbolic
// links and references to ".."  are resolved as and when they occur.
// This means that if "/foo/bar" is a symbolic link to "/baz" then the
// canonical form of "/foo/bar/.." is "/" and not "/foo".
//
// In order to mimic the behaviour of proprietary JVMs, non-existant
// path components are allowed (a departure from the normal GNU system
// convention).  This means that if "/foo/bar" is a symbolic link to
// "/baz", the canonical form of "/non-existant-directory/../foo/bar"
// is "/baz".

Tom Tromey committed
151 152 153
jstring
java::io::File::getCanonicalPath (void)
{
154
  jstring path = getAbsolutePath ();
155

156 157 158 159 160 161
  int len = JvGetStringUTFLength (path);
  int srcl = nextChunkSize (len + 1);
  char *src = (char *) _Jv_Malloc (srcl);
  JvGetStringUTFRegion (path, 0, path->length(), src);
  src[len] = '\0';
  int srci = 1;
162

163 164 165 166 167 168
  int dstl = nextChunkSize (2);  
  char *dst = (char *) _Jv_Malloc (dstl);
  dst[0] = '/';
  int dsti = 1;

  bool fschecks = true;
Tom Tromey committed
169

170
  while (src[srci] != '\0')
171
    {
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
      // Skip slashes.
      while (src[srci] == '/')
	srci++;
      int tmpi = srci;
      // Find next slash.
      while (src[srci] != '/' && src[srci] != '\0')
	srci++;
      if (srci == tmpi)
	// We hit the end.
	break;
      len = srci - tmpi;

      // Handle "." and "..".
      if (len == 1 && src[tmpi] == '.')
	continue;
      if (len == 2 && src[tmpi] == '.' && src[tmpi + 1] == '.')
188
	{
189 190 191 192 193 194 195 196 197 198
	  while (dsti > 1 && dst[dsti - 1] != '/')
	    dsti--;
	  if (dsti != 1)
	    dsti--;
	  // Reenable filesystem checking if disabled, as we might
	  // have reversed over whatever caused the problem before.
	  // At least one proprietary JVM has inconsistencies because
	  // it does not do this.
	  fschecks = true;
	  continue;
199
	}
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

      // Handle real path components.
      dst = maybeGrowBuf (dst, &dstl, dsti + (dsti > 1 ? 1 : 0) + len + 1);
      int dsti_save = dsti;
      if (dsti > 1)
	dst[dsti++] = '/';
      strncpy (&dst[dsti], &src[tmpi], len);
      dsti += len;
      if (fschecks == false)
	continue;

#if defined (HAVE_LSTAT) && defined (HAVE_READLINK)
      struct stat sb;
      dst[dsti] = '\0';
      if (::lstat (dst, &sb) == 0)
215
	{
216
	  if (S_ISLNK (sb.st_mode))
217
	    {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
	      int tmpl = CHUNKSIZ;
	      char *tmp = (char *) _Jv_Malloc (tmpl);

	      while (1)
		{
		  tmpi = ::readlink (dst, tmp, tmpl);
		  if (tmpi < 1)
		    {
		      _Jv_Free (src);
		      _Jv_Free (dst);
		      _Jv_Free (tmp);
		      throw new IOException (
			JvNewStringLatin1 ("readlink failed"));
		    }
		  if (tmpi < tmpl)
		    break;
		  tmpl += CHUNKSIZ;
		  tmp = (char *) _Jv_Realloc (tmp, tmpl);
		}

	      // Prepend the link's path to src.
	      tmp = maybeGrowBuf (tmp, &tmpl, tmpi + strlen (&src[srci]) + 1);
	      strcpy(&tmp[tmpi], &src[srci]);
	      _Jv_Free (src);
	      src = tmp;
	      srcl = tmpl;
	      srci = 0;

	      // Either replace or append dst depending on whether the
	      // link is relative or absolute.
	      dsti = src[0] == '/' ? 1 : dsti_save;
249 250
	    }
	}
251 252 253 254 255 256 257 258 259
      else
	{
	  // Something doesn't exist, or we don't have permission to
	  // read it, or a previous path component is a directory, or
	  // a symlink is looped.  Whatever, we can't check the
	  // filesystem any more.
	  fschecks = false;
	}
#endif // HAVE_LSTAT && HAVE_READLINK
260
    }
261
  dst[dsti] = '\0';
Tom Tromey committed
262 263 264

  // FIXME: what encoding to assume for file names?  This affects many
  // calls.
265 266 267 268
  path = JvNewStringUTF (dst);
  _Jv_Free (src);
  _Jv_Free (dst);
  return path;
Tom Tromey committed
269 270 271 272 273
}

jboolean
java::io::File::isAbsolute (void)
{
274
  return path->length() > 0 && path->charAt(0) == '/';
Tom Tromey committed
275 276
}

277 278 279 280
jobjectArray
java::io::File::performList (java::io::FilenameFilter *filter, 
			     java::io::FileFilter *fileFilter, 
			     java::lang::Class *result_type)
Tom Tromey committed
281
{
Anthony Green committed
282 283 284
  /* Some systems have dirent.h, but no directory reading functions like
     opendir.  */
#if defined(HAVE_DIRENT_H) && defined(HAVE_OPENDIR)
285
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
286
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
Tom Tromey committed
287 288 289 290 291 292
  buf[total] = '\0';

  DIR *dir = opendir (buf);
  if (! dir)
    return NULL;

293
  java::util::ArrayList *list = new java::util::ArrayList ();
294
  struct dirent *d;
295
#if defined(HAVE_READDIR_R) && defined(_POSIX_PTHREAD_SEMANTICS)
296 297 298 299 300 301
  int name_max = pathconf (buf, _PC_NAME_MAX);
  char dbuf[sizeof (struct dirent) + name_max + 1];
  while (readdir_r (dir, (struct dirent *) dbuf, &d) == 0 && d != NULL)
#else /* HAVE_READDIR_R */
  while ((d = readdir (dir)) != NULL)
#endif /* HAVE_READDIR_R */
Tom Tromey committed
302
    {
303 304 305 306
      // Omit "." and "..".
      if (d->d_name[0] == '.'
	  && (d->d_name[1] == '\0'
	      || (d->d_name[1] == '.' && d->d_name[2] == '\0')))
Tom Tromey committed
307 308 309 310 311
	continue;

      jstring name = JvNewStringUTF (d->d_name);
      if (filter && ! filter->accept(this, name))
	continue;
312

313 314 315 316 317 318 319 320 321 322
      if (result_type == &java::io::File::class$)
        {
	  java::io::File *file = new java::io::File (this, name);
	  if (fileFilter && ! fileFilter->accept(file))
	    continue;

	  list->add(file);
	}
      else
	list->add(name);
Tom Tromey committed
323 324 325 326
    }

  closedir (dir);

327 328 329
  jobjectArray ret = JvNewObjectArray (list->size(), result_type, NULL);
  list->toArray(ret);
  return ret;
Anthony Green committed
330
#else /* HAVE_DIRENT_H && HAVE_OPENDIR */
Tom Tromey committed
331
  return NULL;
Anthony Green committed
332
#endif /* HAVE_DIRENT_H && HAVE_OPENDIR */
Tom Tromey committed
333 334 335 336 337
}

jboolean
java::io::File::performMkdir (void)
{
338
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
Tom Tromey committed
339 340 341 342 343 344 345 346 347 348 349
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';

#ifdef HAVE_MKDIR
  return ::mkdir (buf, 0755) == 0;
#else
  return false;
#endif
}

jboolean
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
java::io::File::setFilePermissions (jboolean enable,
				    jboolean ownerOnly,
				    jint permissions)
{
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';
  JvAssert (permissions == READ || permissions == WRITE || permissions == EXEC);
#if defined (HAVE_STAT) && defined (HAVE_CHMOD)
  mode_t mode = 0;

  struct stat sb;
  if (::stat (buf, &sb))
    return false;

  if (ownerOnly)
    {
      if (permissions == READ)
        mode |= S_IRUSR;
      else if (permissions == WRITE)
        mode |= S_IWUSR;
      else if (permissions == EXEC)
        mode |= S_IXUSR;
    }
  else
    {
      if (permissions == READ)
        mode |= (S_IRUSR | S_IRGRP | S_IROTH);
      else if (permissions == WRITE)
        mode |= (S_IWUSR | S_IWGRP | S_IWOTH);
      else if (permissions == EXEC)
        mode |= (S_IXUSR | S_IXGRP | S_IXOTH);
    }
  
  if (enable)
    mode = sb.st_mode | mode;
  else
    mode = sb.st_mode & ~mode;
  
  if (::chmod(buf, mode) < 0)
    return false;
  return true;
#else
  return false;
#endif
}

jboolean
398 399
java::io::File::performSetReadOnly (void)
{
400
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
401 402 403
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';

404
#if defined (HAVE_STAT) && defined (HAVE_CHMOD)
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  struct stat sb;
  if (::stat (buf, &sb))
    return false;

  if (::chmod(buf, sb.st_mode & 0555))
    return false;  
  return true;
#else
  return false;
#endif
}

JArray< ::java::io::File *>*
java::io::File::performListRoots ()
{
420 421 422 423 424
  ::java::io::File *f = new ::java::io::File (JvNewStringLatin1 ("/"));
  JArray<java::io::File *> *unixroot
    = reinterpret_cast <JArray<java::io::File *>*> 
          (JvNewObjectArray (1, &java::io::File::class$, f));
  elements (unixroot) [0] = f;
425 426 427 428
  return unixroot;
}

jboolean
Tom Tromey committed
429 430
java::io::File::performRenameTo (File *dest)
{
431
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
Tom Tromey committed
432 433
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';
434 435
  char *buf2
    = (char *) __builtin_alloca (JvGetStringUTFLength (dest->path) + 1);
Tom Tromey committed
436 437 438 439 440 441 442 443 444 445 446
  total = JvGetStringUTFRegion (dest->path, 0, dest->path->length(), buf2);
  buf2[total] = '\0';

#ifdef HAVE_RENAME
  return ::rename (buf, buf2) == 0;
#else
  return false;
#endif
}

jboolean
447 448 449 450 451
java::io::File::performSetLastModified (jlong time)
{
#ifdef HAVE_UTIME
  utimbuf tb;

452
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
453 454 455 456 457
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';
  
  tb.actime = time / 1000;
  tb.modtime = time / 1000;
458
  return (::utime (buf, &tb) == 0);
459 460 461 462 463 464 465 466
#else
  return false;
#endif
}

jboolean
java::io::File::performCreate (void)
{
467
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
  buf[total] = '\0';

  int fd = ::open (buf, O_CREAT | O_EXCL, 0644);

  if (fd < 0)
    {
      if (errno == EEXIST)
        return false;
      throw new IOException (JvNewStringLatin1 (strerror (errno)));
    }
  else
    {
      ::close (fd);
      return true;
    }
}

jboolean
java::io::File::performDelete (void)
Tom Tromey committed
488
{
489
  char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (path) + 1);
490
  jsize total = JvGetStringUTFRegion (path, 0, path->length(), buf);
Tom Tromey committed
491 492 493 494 495 496 497
  buf[total] = '\0';

#ifdef HAVE_UNLINK
#ifdef HAVE_RMDIR
  if (! ::rmdir (buf))
    return true;
  if (errno == ENOTDIR)
498
#endif // HAVE_RMDIR
Tom Tromey committed
499 500 501 502
    return ::unlink (buf) == 0;
#endif // HAVE_UNLINK
  return false;
}
503 504 505 506

void
java::io::File::init_native ()
{
507
#ifdef MAXPATHLEN
508
  maxPathLen = MAXPATHLEN;
509 510 511 512 513
#else
  /* Some systems do not have a limit on the length of a file name,
     the GNU system is one such example.  */
  maxPathLen = 0;
#endif
514 515
  caseSensitive = true;
}