]> Dogcows Code - chaz/tar/blob - src/misc.c
tar: add utimens.h includes
[chaz/tar] / src / misc.c
1 /* Miscellaneous functions, not really specific to GNU tar.
2
3 Copyright (C) 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001,
4 2003, 2004, 2005, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 This program is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 Public License for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19
20 #include <system.h>
21 #include <rmt.h>
22 #include "common.h"
23 #include <quotearg.h>
24 #include <save-cwd.h>
25 #include <xgetcwd.h>
26 #include <unlinkdir.h>
27 #include <utimens.h>
28
29 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
30 # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
31 #endif
32
33 \f
34 /* Handling strings. */
35
36 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
37 STRING was nonzero, it is freed first. */
38 void
39 assign_string (char **string, const char *value)
40 {
41 if (*string)
42 free (*string);
43 *string = value ? xstrdup (value) : 0;
44 }
45
46 #if 0
47 /* This function is currently unused; perhaps it should be removed? */
48
49 /* Allocate a copy of the string quoted as in C, and returns that. If
50 the string does not have to be quoted, it returns a null pointer.
51 The allocated copy should normally be freed with free() after the
52 caller is done with it.
53
54 This is used in one context only: generating the directory file in
55 incremental dumps. The quoted string is not intended for human
56 consumption; it is intended only for unquote_string. The quoting
57 is locale-independent, so that users needn't worry about locale
58 when reading directory files. This means that we can't use
59 quotearg, as quotearg is locale-dependent and is meant for human
60 consumption. */
61 static char *
62 quote_copy_string (const char *string)
63 {
64 const char *source = string;
65 char *destination = 0;
66 char *buffer = 0;
67 int copying = 0;
68
69 while (*source)
70 {
71 int character = *source++;
72
73 switch (character)
74 {
75 case '\n': case '\\':
76 if (!copying)
77 {
78 size_t length = (source - string) - 1;
79
80 copying = 1;
81 buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
82 memcpy (buffer, string, length);
83 destination = buffer + length;
84 }
85 *destination++ = '\\';
86 *destination++ = character == '\\' ? '\\' : 'n';
87 break;
88
89 default:
90 if (copying)
91 *destination++ = character;
92 break;
93 }
94 }
95 if (copying)
96 {
97 *destination = '\0';
98 return buffer;
99 }
100 return 0;
101 }
102 #endif
103
104 /* Takes a quoted C string (like those produced by quote_copy_string)
105 and turns it back into the un-quoted original. This is done in
106 place. Returns 0 only if the string was not properly quoted, but
107 completes the unquoting anyway.
108
109 This is used for reading the saved directory file in incremental
110 dumps. It is used for decoding old `N' records (demangling names).
111 But also, it is used for decoding file arguments, would they come
112 from the shell or a -T file, and for decoding the --exclude
113 argument. */
114 int
115 unquote_string (char *string)
116 {
117 int result = 1;
118 char *source = string;
119 char *destination = string;
120
121 /* Escape sequences other than \\ and \n are no longer generated by
122 quote_copy_string, but accept them for backwards compatibility,
123 and also because unquote_string is used for purposes other than
124 parsing the output of quote_copy_string. */
125
126 while (*source)
127 if (*source == '\\')
128 switch (*++source)
129 {
130 case '\\':
131 *destination++ = '\\';
132 source++;
133 break;
134
135 case 'a':
136 *destination++ = '\a';
137 source++;
138 break;
139
140 case 'b':
141 *destination++ = '\b';
142 source++;
143 break;
144
145 case 'f':
146 *destination++ = '\f';
147 source++;
148 break;
149
150 case 'n':
151 *destination++ = '\n';
152 source++;
153 break;
154
155 case 'r':
156 *destination++ = '\r';
157 source++;
158 break;
159
160 case 't':
161 *destination++ = '\t';
162 source++;
163 break;
164
165 case 'v':
166 *destination++ = '\v';
167 source++;
168 break;
169
170 case '?':
171 *destination++ = 0177;
172 source++;
173 break;
174
175 case '0':
176 case '1':
177 case '2':
178 case '3':
179 case '4':
180 case '5':
181 case '6':
182 case '7':
183 {
184 int value = *source++ - '0';
185
186 if (*source < '0' || *source > '7')
187 {
188 *destination++ = value;
189 break;
190 }
191 value = value * 8 + *source++ - '0';
192 if (*source < '0' || *source > '7')
193 {
194 *destination++ = value;
195 break;
196 }
197 value = value * 8 + *source++ - '0';
198 *destination++ = value;
199 break;
200 }
201
202 default:
203 result = 0;
204 *destination++ = '\\';
205 if (*source)
206 *destination++ = *source++;
207 break;
208 }
209 else if (source != destination)
210 *destination++ = *source++;
211 else
212 source++, destination++;
213
214 if (source != destination)
215 *destination = '\0';
216 return result;
217 }
218
219 /* Zap trailing slashes. */
220 char *
221 zap_slashes (char *name)
222 {
223 char *q;
224
225 if (!name || *name == 0)
226 return name;
227 q = name + strlen (name) - 1;
228 while (q > name && ISSLASH (*q))
229 *q-- = '\0';
230 return name;
231 }
232
233 /* Normalize FILE_NAME by removing redundant slashes and "."
234 components, including redundant trailing slashes. Leave ".."
235 alone, as it may be significant in the presence of symlinks and on
236 platforms where "/.." != "/". Destructive version: modifies its
237 argument. */
238 static void
239 normalize_filename_x (char *file_name)
240 {
241 char *name = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
242 char *p;
243 char const *q;
244 char c;
245
246 /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
247 name += (DOUBLE_SLASH_IS_DISTINCT_ROOT
248 && ISSLASH (*name) && ISSLASH (name[1]) && ! ISSLASH (name[2]));
249
250 /* Omit redundant leading "." components. */
251 for (q = p = name; (*p = *q) == '.' && ISSLASH (q[1]); p += !*q)
252 for (q += 2; ISSLASH (*q); q++)
253 continue;
254
255 /* Copy components from Q to P, omitting redundant slashes and
256 internal "." components. */
257 while ((*p++ = c = *q++) != '\0')
258 if (ISSLASH (c))
259 while (ISSLASH (q[*q == '.']))
260 q += (*q == '.') + 1;
261
262 /* Omit redundant trailing "." component and slash. */
263 if (2 < p - name)
264 {
265 p -= p[-2] == '.' && ISSLASH (p[-3]);
266 p -= 2 < p - name && ISSLASH (p[-2]);
267 p[-1] = '\0';
268 }
269 }
270
271 /* Normalize NAME by removing redundant slashes and "." components,
272 including redundant trailing slashes. Return a normalized
273 newly-allocated copy. */
274
275 char *
276 normalize_filename (const char *name)
277 {
278 char *copy = NULL;
279
280 if (IS_RELATIVE_FILE_NAME (name))
281 {
282 /* Set COPY to the absolute file name if possible.
283
284 FIXME: There should be no need to get the absolute file name.
285 getcwd is slow, it might fail, and it does not necessarily
286 return a canonical name even when it succeeds. Perhaps we
287 can use dev+ino pairs instead of names? */
288 copy = xgetcwd ();
289 if (copy)
290 {
291 size_t copylen = strlen (copy);
292 bool need_separator = ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
293 && copylen == 2 && ISSLASH (copy[1]));
294 copy = xrealloc (copy, copylen + need_separator + strlen (name) + 1);
295 copy[copylen] = DIRECTORY_SEPARATOR;
296 strcpy (copy + copylen + need_separator, name);
297 }
298 else
299 WARN ((0, errno, _("Cannot get working directory")));
300 }
301
302 if (! copy)
303 copy = xstrdup (name);
304 normalize_filename_x (copy);
305 return copy;
306 }
307
308 \f
309 void
310 replace_prefix (char **pname, const char *samp, size_t slen,
311 const char *repl, size_t rlen)
312 {
313 char *name = *pname;
314 size_t nlen = strlen (name);
315 if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
316 {
317 if (rlen > slen)
318 {
319 name = xrealloc (name, nlen - slen + rlen + 1);
320 *pname = name;
321 }
322 memmove (name + rlen, name + slen, nlen - slen + 1);
323 memcpy (name, repl, rlen);
324 }
325 }
326
327 \f
328 /* Handling numbers. */
329
330 /* Output fraction and trailing digits appropriate for a nanoseconds
331 count equal to NS, but don't output unnecessary '.' or trailing
332 zeros. */
333
334 void
335 code_ns_fraction (int ns, char *p)
336 {
337 if (ns == 0)
338 *p = '\0';
339 else
340 {
341 int i = 9;
342 *p++ = '.';
343
344 while (ns % 10 == 0)
345 {
346 ns /= 10;
347 i--;
348 }
349
350 p[i] = '\0';
351
352 for (;;)
353 {
354 p[--i] = '0' + ns % 10;
355 if (i == 0)
356 break;
357 ns /= 10;
358 }
359 }
360 }
361
362 char const *
363 code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
364 {
365 time_t s = t.tv_sec;
366 int ns = t.tv_nsec;
367 char *np;
368 bool negative = s < 0;
369
370 /* ignore invalid values of ns */
371 if (BILLION <= ns || ns < 0)
372 ns = 0;
373
374 if (negative && ns != 0)
375 {
376 s++;
377 ns = BILLION - ns;
378 }
379
380 np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
381 if (negative)
382 *--np = '-';
383 code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
384 return np;
385 }
386 \f
387 /* File handling. */
388
389 /* Saved names in case backup needs to be undone. */
390 static char *before_backup_name;
391 static char *after_backup_name;
392
393 /* Return 1 if FILE_NAME is obviously "." or "/". */
394 bool
395 must_be_dot_or_slash (char const *file_name)
396 {
397 file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
398
399 if (ISSLASH (file_name[0]))
400 {
401 for (;;)
402 if (ISSLASH (file_name[1]))
403 file_name++;
404 else if (file_name[1] == '.'
405 && ISSLASH (file_name[2 + (file_name[2] == '.')]))
406 file_name += 2 + (file_name[2] == '.');
407 else
408 return ! file_name[1];
409 }
410 else
411 {
412 while (file_name[0] == '.' && ISSLASH (file_name[1]))
413 {
414 file_name += 2;
415 while (ISSLASH (*file_name))
416 file_name++;
417 }
418
419 return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
420 }
421 }
422
423 /* Some implementations of rmdir let you remove '.' or '/'.
424 Report an error with errno set to zero for obvious cases of this;
425 otherwise call rmdir. */
426 static int
427 safer_rmdir (const char *file_name)
428 {
429 if (must_be_dot_or_slash (file_name))
430 {
431 errno = 0;
432 return -1;
433 }
434
435 return rmdir (file_name);
436 }
437
438 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
439 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
440 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
441 a directory that cannot be removed (e.g., because it is nonempty)
442 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
443 Return 0 on error, with errno set; if FILE_NAME is obviously the working
444 directory return zero with errno set to zero. */
445 int
446 remove_any_file (const char *file_name, enum remove_option option)
447 {
448 /* Try unlink first if we cannot unlink directories, as this saves
449 us a system call in the common case where we're removing a
450 non-directory. */
451 bool try_unlink_first = cannot_unlink_dir ();
452
453 if (try_unlink_first)
454 {
455 if (unlink (file_name) == 0)
456 return 1;
457
458 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
459 directory without appropriate privileges, but many Linux
460 kernels return the more-sensible EISDIR. */
461 if (errno != EPERM && errno != EISDIR)
462 return 0;
463 }
464
465 if (safer_rmdir (file_name) == 0)
466 return 1;
467
468 switch (errno)
469 {
470 case ENOTDIR:
471 return !try_unlink_first && unlink (file_name) == 0;
472
473 case 0:
474 case EEXIST:
475 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
476 case ENOTEMPTY:
477 #endif
478 switch (option)
479 {
480 case ORDINARY_REMOVE_OPTION:
481 break;
482
483 case WANT_DIRECTORY_REMOVE_OPTION:
484 return -1;
485
486 case RECURSIVE_REMOVE_OPTION:
487 {
488 char *directory = savedir (file_name);
489 char const *entry;
490 size_t entrylen;
491
492 if (! directory)
493 return 0;
494
495 for (entry = directory;
496 (entrylen = strlen (entry)) != 0;
497 entry += entrylen + 1)
498 {
499 char *file_name_buffer = new_name (file_name, entry);
500 int r = remove_any_file (file_name_buffer,
501 RECURSIVE_REMOVE_OPTION);
502 int e = errno;
503 free (file_name_buffer);
504
505 if (! r)
506 {
507 free (directory);
508 errno = e;
509 return 0;
510 }
511 }
512
513 free (directory);
514 return safer_rmdir (file_name) == 0;
515 }
516 }
517 break;
518 }
519
520 return 0;
521 }
522
523 /* Check if FILE_NAME already exists and make a backup of it right now.
524 Return success (nonzero) only if the backup is either unneeded, or
525 successful. For now, directories are considered to never need
526 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
527 so, we do not have to backup block or character devices, nor remote
528 entities. */
529 bool
530 maybe_backup_file (const char *file_name, bool this_is_the_archive)
531 {
532 struct stat file_stat;
533
534 assign_string (&before_backup_name, file_name);
535
536 /* A run situation may exist between Emacs or other GNU programs trying to
537 make a backup for the same file simultaneously. If theoretically
538 possible, real problems are unlikely. Doing any better would require a
539 convention, GNU-wide, for all programs doing backups. */
540
541 assign_string (&after_backup_name, 0);
542
543 /* Check if we really need to backup the file. */
544
545 if (this_is_the_archive && _remdev (file_name))
546 return true;
547
548 if (stat (file_name, &file_stat))
549 {
550 if (errno == ENOENT)
551 return true;
552
553 stat_error (file_name);
554 return false;
555 }
556
557 if (S_ISDIR (file_stat.st_mode))
558 return true;
559
560 if (this_is_the_archive
561 && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
562 return true;
563
564 after_backup_name = find_backup_file_name (file_name, backup_type);
565 if (! after_backup_name)
566 xalloc_die ();
567
568 if (rename (before_backup_name, after_backup_name) == 0)
569 {
570 if (verbose_option)
571 fprintf (stdlis, _("Renaming %s to %s\n"),
572 quote_n (0, before_backup_name),
573 quote_n (1, after_backup_name));
574 return true;
575 }
576 else
577 {
578 /* The backup operation failed. */
579 int e = errno;
580 ERROR ((0, e, _("%s: Cannot rename to %s"),
581 quotearg_colon (before_backup_name),
582 quote_n (1, after_backup_name)));
583 assign_string (&after_backup_name, 0);
584 return false;
585 }
586 }
587
588 /* Try to restore the recently backed up file to its original name.
589 This is usually only needed after a failed extraction. */
590 void
591 undo_last_backup (void)
592 {
593 if (after_backup_name)
594 {
595 if (rename (after_backup_name, before_backup_name) != 0)
596 {
597 int e = errno;
598 ERROR ((0, e, _("%s: Cannot rename to %s"),
599 quotearg_colon (after_backup_name),
600 quote_n (1, before_backup_name)));
601 }
602 if (verbose_option)
603 fprintf (stdlis, _("Renaming %s back to %s\n"),
604 quote_n (0, after_backup_name),
605 quote_n (1, before_backup_name));
606 assign_string (&after_backup_name, 0);
607 }
608 }
609
610 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
611 int
612 deref_stat (bool deref, char const *name, struct stat *buf)
613 {
614 return deref ? stat (name, buf) : lstat (name, buf);
615 }
616
617 /* Set FD's (i.e., assuming the working directory is PARENTFD, FILE's)
618 access time to ATIME. ATFLAG controls symbolic-link following, in
619 the style of openat. */
620 int
621 set_file_atime (int fd, int parentfd, char const *file, struct timespec atime,
622 int atflag)
623 {
624 struct timespec ts[2];
625 ts[0] = atime;
626 ts[1].tv_nsec = UTIME_OMIT;
627 return fdutimensat (fd, parentfd, file, ts, atflag);
628 }
629
630 /* A description of a working directory. */
631 struct wd
632 {
633 /* The directory's name. */
634 char const *name;
635
636 /* A negative value if no attempt has been made to save the
637 directory, 0 if it was saved successfully, and a positive errno
638 value if it was not saved successfully. */
639 int err;
640
641 /* The saved version of the directory, if ERR == 0. */
642 struct saved_cwd saved_cwd;
643 };
644
645 /* A vector of chdir targets. wd[0] is the initial working directory. */
646 static struct wd *wd;
647
648 /* The number of working directories in the vector. */
649 static size_t wd_count;
650
651 /* The allocated size of the vector. */
652 static size_t wd_alloc;
653
654 int
655 chdir_count ()
656 {
657 if (wd_count == 0)
658 return wd_count;
659 return wd_count - 1;
660 }
661
662 /* DIR is the operand of a -C option; add it to vector of chdir targets,
663 and return the index of its location. */
664 int
665 chdir_arg (char const *dir)
666 {
667 if (wd_count == wd_alloc)
668 {
669 if (wd_alloc == 0)
670 {
671 wd_alloc = 2;
672 wd = xmalloc (sizeof *wd * wd_alloc);
673 }
674 else
675 wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
676
677 if (! wd_count)
678 {
679 wd[wd_count].name = ".";
680 wd[wd_count].err = -1;
681 wd_count++;
682 }
683 }
684
685 /* Optimize the common special case of the working directory,
686 or the working directory as a prefix. */
687 if (dir[0])
688 {
689 while (dir[0] == '.' && ISSLASH (dir[1]))
690 for (dir += 2; ISSLASH (*dir); dir++)
691 continue;
692 if (! dir[dir[0] == '.'])
693 return wd_count - 1;
694 }
695
696 wd[wd_count].name = dir;
697 wd[wd_count].err = -1;
698 return wd_count++;
699 }
700
701 /* Index of current directory. */
702 int chdir_current;
703
704 /* Change to directory I. If I is 0, change to the initial working
705 directory; otherwise, I must be a value returned by chdir_arg. */
706 void
707 chdir_do (int i)
708 {
709 if (chdir_current != i)
710 {
711 struct wd *prev = &wd[chdir_current];
712 struct wd *curr = &wd[i];
713
714 if (prev->err < 0)
715 {
716 prev->err = 0;
717 if (save_cwd (&prev->saved_cwd) != 0)
718 prev->err = errno;
719 else if (0 <= prev->saved_cwd.desc)
720 {
721 /* Make sure we still have at least one descriptor available. */
722 int fd1 = prev->saved_cwd.desc;
723 int fd2 = dup (fd1);
724 if (0 <= fd2)
725 close (fd2);
726 else if (errno == EMFILE)
727 {
728 /* Force restore_cwd to use chdir_long. */
729 close (fd1);
730 prev->saved_cwd.desc = -1;
731 prev->saved_cwd.name = xgetcwd ();
732 if (! prev->saved_cwd.name)
733 prev->err = errno;
734 }
735 else
736 prev->err = errno;
737 }
738 }
739
740 if (0 <= curr->err)
741 {
742 int err = curr->err;
743 if (err == 0 && restore_cwd (&curr->saved_cwd) != 0)
744 err = errno;
745 if (err)
746 FATAL_ERROR ((0, err, _("Cannot restore working directory")));
747 }
748 else
749 {
750 if (i && ! ISSLASH (curr->name[0]))
751 chdir_do (i - 1);
752 if (chdir (curr->name) != 0)
753 chdir_fatal (curr->name);
754 }
755
756 chdir_current = i;
757 }
758 }
759 \f
760 void
761 close_diag (char const *name)
762 {
763 if (ignore_failed_read_option)
764 close_warn (name);
765 else
766 close_error (name);
767 }
768
769 void
770 open_diag (char const *name)
771 {
772 if (ignore_failed_read_option)
773 open_warn (name);
774 else
775 open_error (name);
776 }
777
778 void
779 read_diag_details (char const *name, off_t offset, size_t size)
780 {
781 if (ignore_failed_read_option)
782 read_warn_details (name, offset, size);
783 else
784 read_error_details (name, offset, size);
785 }
786
787 void
788 readlink_diag (char const *name)
789 {
790 if (ignore_failed_read_option)
791 readlink_warn (name);
792 else
793 readlink_error (name);
794 }
795
796 void
797 savedir_diag (char const *name)
798 {
799 if (ignore_failed_read_option)
800 savedir_warn (name);
801 else
802 savedir_error (name);
803 }
804
805 void
806 seek_diag_details (char const *name, off_t offset)
807 {
808 if (ignore_failed_read_option)
809 seek_warn_details (name, offset);
810 else
811 seek_error_details (name, offset);
812 }
813
814 void
815 stat_diag (char const *name)
816 {
817 if (ignore_failed_read_option)
818 stat_warn (name);
819 else
820 stat_error (name);
821 }
822
823 void
824 file_removed_diag (const char *name, bool top_level,
825 void (*diagfn) (char const *name))
826 {
827 if (!top_level && errno == ENOENT)
828 {
829 WARNOPT (WARN_FILE_REMOVED,
830 (0, 0, _("%s: File removed before we read it"),
831 quotearg_colon (name)));
832 set_exit_status (TAREXIT_DIFFERS);
833 }
834 else
835 diagfn (name);
836 }
837
838 void
839 dir_removed_diag (const char *name, bool top_level,
840 void (*diagfn) (char const *name))
841 {
842 if (!top_level && errno == ENOENT)
843 {
844 WARNOPT (WARN_FILE_REMOVED,
845 (0, 0, _("%s: Directory removed before we read it"),
846 quotearg_colon (name)));
847 set_exit_status (TAREXIT_DIFFERS);
848 }
849 else
850 diagfn (name);
851 }
852
853 void
854 write_fatal_details (char const *name, ssize_t status, size_t size)
855 {
856 write_error_details (name, status, size);
857 fatal_exit ();
858 }
859
860 /* Fork, aborting if unsuccessful. */
861 pid_t
862 xfork (void)
863 {
864 pid_t p = fork ();
865 if (p == (pid_t) -1)
866 call_arg_fatal ("fork", _("child process"));
867 return p;
868 }
869
870 /* Create a pipe, aborting if unsuccessful. */
871 void
872 xpipe (int fd[2])
873 {
874 if (pipe (fd) < 0)
875 call_arg_fatal ("pipe", _("interprocess channel"));
876 }
877
878 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
879 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
880 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
881 locations. */
882
883 static inline void *
884 ptr_align (void *ptr, size_t alignment)
885 {
886 char *p0 = ptr;
887 char *p1 = p0 + alignment - 1;
888 return p1 - (size_t) p1 % alignment;
889 }
890
891 /* Return the address of a page-aligned buffer of at least SIZE bytes.
892 The caller should free *PTR when done with the buffer. */
893
894 void *
895 page_aligned_alloc (void **ptr, size_t size)
896 {
897 size_t alignment = getpagesize ();
898 size_t size1 = size + alignment;
899 if (size1 < size)
900 xalloc_die ();
901 *ptr = xmalloc (size1);
902 return ptr_align (*ptr, alignment);
903 }
904
905 \f
906
907 struct namebuf
908 {
909 char *buffer; /* directory, `/', and directory member */
910 size_t buffer_size; /* allocated size of name_buffer */
911 size_t dir_length; /* length of directory part in buffer */
912 };
913
914 namebuf_t
915 namebuf_create (const char *dir)
916 {
917 namebuf_t buf = xmalloc (sizeof (*buf));
918 buf->buffer_size = strlen (dir) + 2;
919 buf->buffer = xmalloc (buf->buffer_size);
920 strcpy (buf->buffer, dir);
921 buf->dir_length = strlen (buf->buffer);
922 if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
923 buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
924 return buf;
925 }
926
927 void
928 namebuf_free (namebuf_t buf)
929 {
930 free (buf->buffer);
931 free (buf);
932 }
933
934 char *
935 namebuf_name (namebuf_t buf, const char *name)
936 {
937 size_t len = strlen (name);
938 while (buf->dir_length + len + 1 >= buf->buffer_size)
939 buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
940 strcpy (buf->buffer + buf->dir_length, name);
941 return buf->buffer;
942 }
This page took 0.06793 seconds and 5 git commands to generate.