2 * Copyright (C) 1995 Andries E. Brouwer (aeb@cwi.nl)
3 * Copyright (C) 2014 Karel Zak <kzak@redhat.com>
5 * This program is free software. You can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation: either Version 1
8 * or (at your option) any later version.
10 * A.V. Le Blanc (LeBlanc@mcc.ac.uk) wrote Linux fdisk 1992-1994,
11 * patched by various people (faith@cs.unc.edu, martin@cs.unc.edu,
12 * leisner@sdsp.mc.xerox.com, esr@snark.thyrsus.com, aeb@cwi.nl)
13 * 1993-1995, with version numbers (as far as I have seen) 0.93 - 2.0e.
14 * This program had (head,sector,cylinder) as basic unit, and was
15 * (therefore) broken in several ways for the use on larger disks -
16 * for example, my last patch (from 2.0d to 2.0e) was required
17 * to allow a partition to cross cylinder 8064, and to write an
18 * extended partition past the 4GB mark.
20 * Karel Zak wrote new sfdisk based on libfdisk from util-linux
34 #include <libsmartcols.h>
35 #ifdef HAVE_LIBREADLINE
36 # define _FUNCTION_DEF
37 # include <readline/readline.h>
47 #include "closestream.h"
56 #include "fdisk-list.h"
59 * sfdisk debug stuff (see fdisk.h and include/debug.h)
61 static UL_DEBUG_DEFINE_MASK(sfdisk
);
62 UL_DEBUG_DEFINE_MASKNAMES(sfdisk
) = UL_DEBUG_EMPTY_MASKNAMES
;
64 #define SFDISKPROG_DEBUG_INIT (1 << 1)
65 #define SFDISKPROG_DEBUG_PARSE (1 << 2)
66 #define SFDISKPROG_DEBUG_MISC (1 << 3)
67 #define SFDISKPROG_DEBUG_ASK (1 << 4)
68 #define SFDISKPROG_DEBUG_ALL 0xFFFF
70 #define DBG(m, x) __UL_DBG(sfdisk, SFDISKPROG_DEBUG_, m, x)
71 #define ON_DBG(m, x) __UL_DBG_CALL(sfdisk, SFDISKPROG_DEBUG_, m, x)
96 int partno
; /* -N <partno>, default -1 */
97 int wipemode
; /* remove foreign signatures from disk */
98 int pwipemode
; /* remove foreign signatures from partitions */
99 const char *label
; /* --label <label> */
100 const char *label_nested
; /* --label-nested <label> */
101 const char *backup_file
; /* -O <path> */
102 const char *move_typescript
; /* --movedata <typescript> */
105 struct fdisk_context
*cxt
; /* libfdisk context */
106 struct fdisk_partition
*orig_pa
; /* -N <partno> before the change */
108 unsigned int verify
: 1, /* call fdisk_verify_disklabel() */
109 quiet
: 1, /* suppress extra messages */
110 interactive
: 1, /* running on tty */
111 noreread
: 1, /* don't check device is in use */
112 force
: 1, /* do also stupid things */
113 backup
: 1, /* backup sectors before write PT */
114 container
: 1, /* PT contains container (MBR extended) partitions */
115 append
: 1, /* don't create new PT, append partitions only */
116 json
: 1, /* JSON dump */
117 movedata
: 1, /* move data after resize */
118 movefsync
: 1, /* use fsync() after each write() */
119 notell
: 1, /* don't tell kernel aout new PT */
120 noact
: 1; /* do not write to device */
123 #define SFDISK_PROMPT ">>> "
125 static void sfdiskprog_init_debug(void)
127 __UL_INIT_DEBUG_FROM_ENV(sfdisk
, SFDISKPROG_DEBUG_
, 0, SFDISK_DEBUG
);
131 static int get_user_reply(const char *prompt
, char *buf
, size_t bufsz
)
136 #ifdef HAVE_LIBREADLINE
137 if (isatty(STDIN_FILENO
)) {
138 p
= readline(prompt
);
141 xstrncpy(buf
, p
, bufsz
);
146 fputs(prompt
, stdout
);
149 if (!fgets(buf
, bufsz
, stdin
))
153 for (p
= buf
; *p
&& !isgraph(*p
); p
++); /* get first non-blank */
156 memmove(buf
, p
, p
- buf
); /* remove blank space */
158 if (sz
&& *(buf
+ sz
- 1) == '\n')
159 *(buf
+ sz
- 1) = '\0';
161 DBG(ASK
, ul_debug("user's reply: >>>%s<<<", buf
));
165 static int ask_callback(struct fdisk_context
*cxt
__attribute__((__unused__
)),
166 struct fdisk_ask
*ask
,
169 struct sfdisk
*sf
= (struct sfdisk
*) data
;
174 switch(fdisk_ask_get_type(ask
)) {
175 case FDISK_ASKTYPE_INFO
:
178 fputs(fdisk_ask_print_get_mesg(ask
), stdout
);
181 case FDISK_ASKTYPE_WARNX
:
183 color_scheme_fenable("warn", UL_COLOR_RED
, stderr
);
184 fputs(fdisk_ask_print_get_mesg(ask
), stderr
);
185 color_fdisable(stderr
);
188 case FDISK_ASKTYPE_WARN
:
190 color_scheme_fenable("warn", UL_COLOR_RED
, stderr
);
191 fputs(fdisk_ask_print_get_mesg(ask
), stderr
);
192 errno
= fdisk_ask_print_get_errno(ask
);
193 fprintf(stderr
, ": %m\n");
194 color_fdisable(stderr
);
196 case FDISK_ASKTYPE_YESNO
:
198 char buf
[BUFSIZ
] = { '\0' };
202 fputs(fdisk_ask_get_query(ask
), stdout
);
203 rc
= get_user_reply(_(" [Y]es/[N]o: "), buf
, sizeof(buf
));
207 if (x
== RPMATCH_YES
|| x
== RPMATCH_NO
) {
208 fdisk_ask_yesno_set_result(ask
, x
);
212 DBG(ASK
, ul_debug("yes-no ask: reply '%s' [rc=%d]", buf
, rc
));
221 static void sfdisk_init(struct sfdisk
*sf
)
225 sfdiskprog_init_debug();
227 sf
->cxt
= fdisk_new_context();
229 err(EXIT_FAILURE
, _("failed to allocate libfdisk context"));
230 fdisk_set_ask(sf
->cxt
, ask_callback
, (void *) sf
);
231 fdisk_enable_bootbits_protection(sf
->cxt
, 1);
233 if (sf
->label_nested
) {
234 struct fdisk_context
*x
= fdisk_new_nested_context(sf
->cxt
,
237 err(EXIT_FAILURE
, _("failed to allocate nested libfdisk context"));
238 /* the original context is available by fdisk_get_parent() */
243 static int sfdisk_deinit(struct sfdisk
*sf
)
245 struct fdisk_context
*parent
;
250 parent
= fdisk_get_parent(sf
->cxt
);
252 fdisk_unref_context(sf
->cxt
);
256 fdisk_unref_context(sf
->cxt
);
259 memset(sf
, 0, sizeof(*sf
));
263 static struct fdisk_partition
*get_partition(struct fdisk_context
*cxt
, size_t partno
)
265 struct fdisk_table
*tb
= NULL
;
266 struct fdisk_partition
*pa
;
268 if (fdisk_get_partitions(cxt
, &tb
) != 0)
271 pa
= fdisk_table_get_partition_by_partno(tb
, partno
);
273 fdisk_ref_partition(pa
);
274 fdisk_unref_table(tb
);
278 static void backup_sectors(struct sfdisk
*sf
,
282 uint64_t offset
, size_t size
)
287 devfd
= fdisk_get_devfd(sf
->cxt
);
290 xasprintf(&fname
, "%s0x%08"PRIx64
".bak", tpl
, offset
);
292 fd
= open(fname
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
);
296 if (lseek(devfd
, (off_t
) offset
, SEEK_SET
) == (off_t
) -1) {
297 fdisk_warn(sf
->cxt
, _("cannot seek %s"), devname
);
300 unsigned char *buf
= xmalloc(size
);
302 if (read_all(devfd
, (char *) buf
, size
) != (ssize_t
) size
) {
303 fdisk_warn(sf
->cxt
, _("cannot read %s"), devname
);
307 if (write_all(fd
, buf
, size
) != 0) {
308 fdisk_warn(sf
->cxt
, _("cannot write %s"), fname
);
315 fdisk_info(sf
->cxt
, _("%12s (offset %5ju, size %5ju): %s"),
316 name
, (uintmax_t) offset
, (uintmax_t) size
, fname
);
321 errx(EXIT_FAILURE
, _("%s: failed to create a backup"), devname
);
324 static char *mk_backup_filename_tpl(const char *filename
, const char *devname
, const char *suffix
)
327 char *name
, *buf
= xstrdup(devname
);
329 name
= basename(buf
);
331 if (!filename
|| strcmp(filename
, "@default") == 0) {
332 const char *home
= getenv ("HOME");
334 errx(EXIT_FAILURE
, _("failed to create a backup file, $HOME undefined"));
335 xasprintf(&tpl
, "%s/sfdisk-%s%s", home
, name
, suffix
);
337 xasprintf(&tpl
, "%s-%s%s", filename
, name
, suffix
);
344 static void backup_partition_table(struct sfdisk
*sf
, const char *devname
)
354 if (!fdisk_has_label(sf
->cxt
))
357 tpl
= mk_backup_filename_tpl(sf
->backup_file
, devname
, "-");
359 color_scheme_enable("header", UL_COLOR_BOLD
);
360 fdisk_info(sf
->cxt
, _("Backup files:"));
363 while (fdisk_locate_disklabel(sf
->cxt
, i
++, &name
, &offset
, &size
) == 0 && size
)
364 backup_sectors(sf
, tpl
, name
, devname
, offset
, size
);
371 static int move_partition_data(struct sfdisk
*sf
, size_t partno
, struct fdisk_partition
*orig_pa
)
373 struct fdisk_partition
*pa
= get_partition(sf
->cxt
, partno
);
374 char *devname
= NULL
, *typescript
= NULL
, *buf
= NULL
;
376 int ok
= 0, fd
, backward
= 0;
377 fdisk_sector_t nsectors
, from
, to
, step
, i
, prev
;
378 size_t io
, ss
, step_bytes
, cc
;
379 uintmax_t src
, dst
, nbytes
;
380 int errsv
, progress
= 0;
381 struct timeval prev_time
;
382 uint64_t bytes_per_sec
= 0;
384 assert(sf
->movedata
);
387 warnx(_("failed to read new partition from device; ignoring --move-data"));
388 else if (!fdisk_partition_has_size(pa
))
389 warnx(_("failed to get size of the new partition; ignoring --move-data"));
390 else if (!fdisk_partition_has_start(pa
))
391 warnx(_("failed to get start of the new partition; ignoring --move-data"));
392 else if (!fdisk_partition_has_size(orig_pa
))
393 warnx(_("failed to get size of the old partition; ignoring --move-data"));
394 else if (!fdisk_partition_has_start(orig_pa
))
395 warnx(_("failed to get start of the old partition; ignoring --move-data"));
396 else if (fdisk_partition_get_start(pa
) == fdisk_partition_get_start(orig_pa
))
397 warnx(_("start of the partition has not been moved; ignoring --move-data"));
398 else if (fdisk_partition_get_size(orig_pa
) < fdisk_partition_get_size(pa
))
399 warnx(_("new partition is smaller than original; ignoring --move-data"));
405 DBG(MISC
, ul_debug("moving data"));
407 fd
= fdisk_get_devfd(sf
->cxt
);
409 /* set move direction and overlay */
410 nsectors
= fdisk_partition_get_size(orig_pa
);
411 from
= fdisk_partition_get_start(orig_pa
);
412 to
= fdisk_partition_get_start(pa
);
415 if ((to
>= from
&& from
+ nsectors
>= to
) ||
416 (from
>= to
&& to
+ nsectors
>= from
)) {
417 /* source and target overlay, check if we need to copy
418 * backwardly from end of the source */
419 DBG(MISC
, ul_debug("overlay between source and target"));
420 backward
= from
< to
;
421 DBG(MISC
, ul_debug(" copy order: %s", backward
? "backward" : "forward"));
424 /* set optimal step size -- nearest to 1MiB aligned to optimal I/O */
425 io
= fdisk_get_optimal_iosize(sf
->cxt
);
426 ss
= fdisk_get_sector_size(sf
->cxt
);
429 if (io
< 1024 * 1024)
430 step_bytes
= ((1024 * 1024) + io
/2) / io
* io
;
434 step
= step_bytes
/ ss
;
435 nbytes
= nsectors
* ss
;
437 DBG(MISC
, ul_debug(" step: %ju (%zu bytes)", (uintmax_t)step
, step_bytes
));
439 #if defined(POSIX_FADV_SEQUENTIAL) && defined(HAVE_POSIX_FADVISE)
441 posix_fadvise(fd
, from
* ss
, nsectors
* ss
, POSIX_FADV_SEQUENTIAL
);
443 devname
= fdisk_partname(fdisk_get_devname(sf
->cxt
), partno
+1);
444 if (sf
->move_typescript
)
445 typescript
= mk_backup_filename_tpl(sf
->move_typescript
, devname
, ".move");
448 fdisk_info(sf
->cxt
,"");
449 color_scheme_enable("header", UL_COLOR_BOLD
);
450 fdisk_info(sf
->cxt
, sf
->noact
? _("Data move: (--no-act)") : _("Data move:"));
453 fdisk_info(sf
->cxt
, _(" typescript file: %s"), typescript
);
454 printf(_(" start sector: (from/to) %ju / %ju\n"), (uintmax_t) from
, (uintmax_t) to
);
455 printf(_(" sectors: %ju\n"), (uintmax_t) nsectors
);
456 printf(_(" step size: %zu bytes\n"), step_bytes
);
460 if (isatty(fileno(stdout
)))
464 if (sf
->interactive
) {
466 fdisk_ask_yesno(sf
->cxt
, _("Do you want to move partition data?"), &yes
);
468 fdisk_info(sf
->cxt
, _("Leaving."));
474 f
= fopen(typescript
, "w");
476 fdisk_warn(sf
->cxt
, _("cannot open %s"), typescript
);
480 /* don't translate */
481 fprintf(f
, "# sfdisk: " PACKAGE_STRING
"\n");
482 fprintf(f
, "# Disk: %s\n", devname
);
483 fprintf(f
, "# Partition: %zu\n", partno
+ 1);
484 fprintf(f
, "# Operation: move data\n");
485 fprintf(f
, "# Sector size: %zu\n", ss
);
486 fprintf(f
, "# Original start offset (sectors/bytes): %ju/%ju\n",
487 (uintmax_t)from
, (uintmax_t)from
* ss
);
488 fprintf(f
, "# New start offset (sectors/bytes): %ju/%ju\n",
489 (uintmax_t)to
, (uintmax_t)to
* ss
);
490 fprintf(f
, "# Area size (sectors/bytes): %ju/%ju\n",
491 (uintmax_t)nsectors
, (uintmax_t)nsectors
* ss
);
492 fprintf(f
, "# Step size (sectors/bytes): %zu/%zu\n", step
, step_bytes
);
493 fprintf(f
, "# Steps: %ju\n", ((uintmax_t) nsectors
/ step
) + 1);
495 fprintf(f
, "# <step>: <from> <to> (step offsets in bytes)\n");
498 src
= (backward
? from
+ nsectors
: from
) * ss
;
499 dst
= (backward
? to
+ nsectors
: to
) * ss
;
500 buf
= xmalloc(step_bytes
);
502 DBG(MISC
, ul_debug(" initial: src=%ju dst=%ju", src
, dst
));
504 gettimeofday(&prev_time
, NULL
);
507 for (cc
= 1, i
= 0; i
< nsectors
&& nbytes
> 0; i
+= step
, cc
++) {
511 src
-= step_bytes
, dst
-= step_bytes
;
513 DBG(MISC
, ul_debug("#%05zu: src=%ju dst=%ju", cc
, src
, dst
));
515 if (nbytes
< step_bytes
) {
516 DBG(MISC
, ul_debug(" aligning step from %ju to %ju",
517 step_bytes
, nbytes
));
520 nbytes
-= step_bytes
;
524 if (lseek(fd
, src
, SEEK_SET
) == (off_t
) -1)
526 rc
= read(fd
, buf
, step_bytes
);
527 if (rc
< 0 || rc
!= (ssize_t
) step_bytes
)
531 if (lseek(fd
, dst
, SEEK_SET
) == (off_t
) -1)
533 rc
= write(fd
, buf
, step_bytes
);
534 if (rc
< 0 || rc
!= (ssize_t
) step_bytes
)
542 fprintf(f
, "%05zu: %12ju %12ju\n", cc
, src
, dst
);
544 if (progress
&& i
% 10 == 0) {
545 unsigned int elapsed
= 0; /* usec */
546 struct timeval cur_time
;
548 gettimeofday(&cur_time
, NULL
);
549 if (cur_time
.tv_sec
- prev_time
.tv_sec
> 1) {
550 elapsed
= ((cur_time
.tv_sec
- prev_time
.tv_sec
) * 1000000) +
551 (cur_time
.tv_usec
- prev_time
.tv_usec
);
553 bytes_per_sec
= ((i
- prev
) * ss
) / elapsed
; /* per usec */
554 bytes_per_sec
*= 1000000; /* per sec */
556 prev_time
= cur_time
;
561 fprintf(stdout
, _("Moved %ju from %ju sectors (%.3f%%, %.1f MiB/s)."),
563 100.0 / ((double) nsectors
/(i
+1)),
564 (double) (bytes_per_sec
/ (1024 * 1024)));
566 fprintf(stdout
, _("Moved %ju from %ju sectors (%.3f%%)."),
568 100.0 / ((double) nsectors
/(i
+1)));
575 src
+= step_bytes
, dst
+= step_bytes
;
579 int x
= get_terminal_width(80);
584 fprintf(stdout
, _("Moved %ju from %ju sectors (%.0f%%)."),
586 100.0 / ((double) nsectors
/(i
+1)));
596 fdisk_info(sf
->cxt
, _("Your data has not been moved (--no-act)."));
601 warn(_("%s: failed to move data"), devname
);
611 static int write_changes(struct sfdisk
*sf
)
616 fdisk_info(sf
->cxt
, _("The partition table is unchanged (--no-act)."));
618 rc
= fdisk_write_disklabel(sf
->cxt
);
620 if (rc
== 0 && sf
->movedata
&& sf
->orig_pa
)
621 rc
= move_partition_data(sf
, sf
->partno
, sf
->orig_pa
);
623 if (!sf
->noact
&& !rc
) {
624 fdisk_info(sf
->cxt
, _("\nThe partition table has been altered."));
626 /* Let's wait a little bit. It's possible that our
627 * system is still busy with a previous re-read
628 * ioctl (on sfdisk start) or with another task
629 * related to the write to the device.
632 fdisk_reread_partition_table(sf
->cxt
);
637 rc
= fdisk_deassign_device(sf
->cxt
,
638 sf
->noact
|| sf
->notell
); /* no-sync */
643 * sfdisk --list [<device ..]
645 static int command_list_partitions(struct sfdisk
*sf
, int argc
, char **argv
)
648 fdisk_enable_listonly(sf
->cxt
, 1);
653 for (i
= 0; i
< argc
; i
++) {
655 fputs("\n\n", stdout
);
656 if (print_device_pt(sf
->cxt
, argv
[i
], 1, sf
->verify
) != 0)
661 print_all_devices_pt(sf
->cxt
, sf
->verify
);
667 * sfdisk --list-free [<device ..]
669 static int command_list_freespace(struct sfdisk
*sf
, int argc
, char **argv
)
672 fdisk_enable_listonly(sf
->cxt
, 1);
677 for (i
= 0; i
< argc
; i
++) {
679 fputs("\n\n", stdout
);
680 if (print_device_freespace(sf
->cxt
, argv
[i
], 1) != 0)
685 print_all_devices_freespace(sf
->cxt
);
691 * sfdisk --list-types
693 static int command_list_types(struct sfdisk
*sf
)
695 const struct fdisk_parttype
*t
;
696 struct fdisk_label
*lb
;
704 name
= sf
->label
? sf
->label
: "dos";
705 lb
= fdisk_get_label(sf
->cxt
, name
);
707 errx(EXIT_FAILURE
, _("unsupported label '%s'"), name
);
709 codes
= fdisk_label_has_code_parttypes(lb
);
710 fputs(_("Id Name\n\n"), stdout
);
712 while ((t
= fdisk_label_get_parttype(lb
, i
++))) {
714 printf("%2x %s\n", fdisk_parttype_get_code(t
),
715 fdisk_parttype_get_name(t
));
717 printf("%s %s\n", fdisk_parttype_get_string(t
),
718 fdisk_parttype_get_name(t
));
724 static int verify_device(struct sfdisk
*sf
, const char *devname
)
728 fdisk_enable_listonly(sf
->cxt
, 1);
730 if (fdisk_assign_device(sf
->cxt
, devname
, 1)) {
731 warn(_("cannot open %s"), devname
);
735 color_scheme_enable("header", UL_COLOR_BOLD
);
736 fdisk_info(sf
->cxt
, "%s:", devname
);
739 if (!fdisk_has_label(sf
->cxt
))
740 fdisk_info(sf
->cxt
, _("unrecognized partition table type"));
742 rc
= fdisk_verify_disklabel(sf
->cxt
);
744 fdisk_deassign_device(sf
->cxt
, 1);
749 * sfdisk --verify [<device ..]
751 static int command_verify(struct sfdisk
*sf
, int argc
, char **argv
)
753 int nfails
= 0, ct
= 0;
757 for (i
= 0; i
< argc
; i
++) {
759 fdisk_info(sf
->cxt
, " ");
760 if (verify_device(sf
, argv
[i
]) < 0)
767 while ((dev
= next_proc_partition(&f
))) {
769 fdisk_info(sf
->cxt
, " ");
770 if (verify_device(sf
, dev
) < 0)
780 static int get_size(const char *dev
, int silent
, uintmax_t *sz
)
784 fd
= open(dev
, O_RDONLY
);
787 warn(_("cannot open %s"), dev
);
791 if (blkdev_get_sectors(fd
, (unsigned long long *) sz
) == -1) {
793 warn(_("Cannot get size of %s"), dev
);
802 * sfdisk --show-size [<device ..]
804 * (silly, but just for backward compatibility)
806 static int command_show_size(struct sfdisk
*sf
__attribute__((__unused__
)),
807 int argc
, char **argv
)
813 for (i
= 0; i
< argc
; i
++) {
814 if (get_size(argv
[i
], 0, &sz
) == 0)
815 printf("%ju\n", sz
/ 2);
822 while ((dev
= next_proc_partition(&f
))) {
823 if (get_size(dev
, 1, &sz
) == 0) {
824 printf("%s: %9ju\n", dev
, sz
/ 2);
830 printf(_("total: %ju blocks\n"), total
);
836 static int print_geom(struct sfdisk
*sf
, const char *devname
)
838 fdisk_enable_listonly(sf
->cxt
, 1);
840 if (fdisk_assign_device(sf
->cxt
, devname
, 1)) {
841 warn(_("cannot open %s"), devname
);
845 fdisk_info(sf
->cxt
, "%s: %ju cylinders, %ju heads, %ju sectors/track",
847 (uintmax_t) fdisk_get_geom_cylinders(sf
->cxt
),
848 (uintmax_t) fdisk_get_geom_heads(sf
->cxt
),
849 (uintmax_t) fdisk_get_geom_sectors(sf
->cxt
));
851 fdisk_deassign_device(sf
->cxt
, 1);
856 * sfdisk --show-geometry [<device ..]
858 static int command_show_geometry(struct sfdisk
*sf
, int argc
, char **argv
)
864 for (i
= 0; i
< argc
; i
++) {
865 if (print_geom(sf
, argv
[i
]) < 0)
872 while ((dev
= next_proc_partition(&f
))) {
873 if (print_geom(sf
, dev
) < 0)
883 * sfdisk --activate <device> [<partno> ...]
885 static int command_activate(struct sfdisk
*sf
, int argc
, char **argv
)
887 int rc
, nparts
, i
, listonly
;
888 struct fdisk_partition
*pa
= NULL
;
889 const char *devname
= NULL
;
892 errx(EXIT_FAILURE
, _("no disk device specified"));
895 /* --activate <device> */
896 listonly
= argc
== 1;
898 rc
= fdisk_assign_device(sf
->cxt
, devname
, listonly
);
900 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
902 if (fdisk_is_label(sf
->cxt
, GPT
)) {
903 if (fdisk_gpt_is_hybrid(sf
->cxt
))
904 errx(EXIT_FAILURE
, _("toggle boot flags is unsupported for Hybrid GPT/MBR"));
906 /* Switch from GPT to PMBR */
907 sf
->cxt
= fdisk_new_nested_context(sf
->cxt
, "dos");
909 err(EXIT_FAILURE
, _("cannot switch to PMBR"));
910 fdisk_info(sf
->cxt
, _("Activation is unsupported for GPT -- entering nested PMBR."));
912 } else if (!fdisk_is_label(sf
->cxt
, DOS
))
913 errx(EXIT_FAILURE
, _("toggle boot flags is supported for MBR or PMBR only"));
915 if (!listonly
&& sf
->backup
)
916 backup_partition_table(sf
, devname
);
918 nparts
= fdisk_get_npartitions(sf
->cxt
);
919 for (i
= 0; i
< nparts
; i
++) {
922 /* note that fdisk_get_partition() reuses the @pa pointer, you
923 * don't have to (re)allocate it */
924 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0)
927 /* sfdisk --activate list bootable partitions */
929 if (!fdisk_partition_is_bootable(pa
))
931 if (fdisk_partition_to_string(pa
, sf
->cxt
,
932 FDISK_FIELD_DEVICE
, &data
) == 0) {
933 printf("%s\n", data
);
937 /* deactivate all active partitions */
938 } else if (fdisk_partition_is_bootable(pa
))
939 fdisk_toggle_partition_flag(sf
->cxt
, i
, DOS_FLAG_ACTIVE
);
942 /* sfdisk --activate <partno> [..] */
943 for (i
= 1; i
< argc
; i
++) {
946 if (i
== 1 && strcmp(argv
[1], "-") == 0)
948 n
= strtou32_or_err(argv
[i
], _("failed to parse partition number"));
950 rc
= fdisk_toggle_partition_flag(sf
->cxt
, n
- 1, DOS_FLAG_ACTIVE
);
953 _("%s: partition %d: failed to toggle bootable flag"),
957 fdisk_unref_partition(pa
);
960 rc
= fdisk_deassign_device(sf
->cxt
, 1);
962 rc
= write_changes(sf
);
967 * sfdisk --delete <device> [<partno> ...]
969 static int command_delete(struct sfdisk
*sf
, int argc
, char **argv
)
972 const char *devname
= NULL
;
975 errx(EXIT_FAILURE
, _("no disk device specified"));
978 if (fdisk_assign_device(sf
->cxt
, devname
, 0) != 0)
979 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
982 backup_partition_table(sf
, devname
);
986 size_t nparts
= fdisk_get_npartitions(sf
->cxt
);
987 for (i
= 0; i
< nparts
; i
++) {
988 if (fdisk_is_partition_used(sf
->cxt
, i
) &&
989 fdisk_delete_partition(sf
->cxt
, i
) != 0)
990 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to delete"), devname
, i
+ 1);
992 /* delete specified */
994 for (i
= 1; i
< (size_t) argc
; i
++) {
995 size_t n
= strtou32_or_err(argv
[i
], _("failed to parse partition number"));
997 if (fdisk_delete_partition(sf
->cxt
, n
- 1) != 0)
998 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to delete"), devname
, n
);
1002 return write_changes(sf
);
1006 * sfdisk --reorder <device>
1008 static int command_reorder(struct sfdisk
*sf
, int argc
, char **argv
)
1010 const char *devname
= NULL
;
1016 errx(EXIT_FAILURE
, _("no disk device specified"));
1018 rc
= fdisk_assign_device(sf
->cxt
, devname
, 0); /* read-write */
1020 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1023 backup_partition_table(sf
, devname
);
1025 if (fdisk_reorder_partitions(sf
->cxt
) == 1) /* unchanged */
1026 rc
= fdisk_deassign_device(sf
->cxt
, 1);
1028 rc
= write_changes(sf
);
1035 * sfdisk --dump <device>
1037 static int command_dump(struct sfdisk
*sf
, int argc
, char **argv
)
1039 const char *devname
= NULL
;
1040 struct fdisk_script
*dp
;
1046 errx(EXIT_FAILURE
, _("no disk device specified"));
1048 rc
= fdisk_assign_device(sf
->cxt
, devname
, 1); /* read-only */
1050 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1052 if (!fdisk_has_label(sf
->cxt
))
1053 errx(EXIT_FAILURE
, _("%s: does not contain a recognized partition table"), devname
);
1055 dp
= fdisk_new_script(sf
->cxt
);
1057 err(EXIT_FAILURE
, _("failed to allocate dump struct"));
1059 rc
= fdisk_script_read_context(dp
, NULL
);
1061 errx(EXIT_FAILURE
, _("%s: failed to dump partition table"), devname
);
1064 fdisk_script_enable_json(dp
, 1);
1065 fdisk_script_write_file(dp
, stdout
);
1067 fdisk_unref_script(dp
);
1068 fdisk_deassign_device(sf
->cxt
, 1); /* no-sync() */
1072 static void assign_device_partition(struct sfdisk
*sf
,
1073 const char *devname
,
1079 struct fdisk_label
*lb
= NULL
;
1084 /* read-only when a new <type> undefined */
1085 rc
= fdisk_assign_device(sf
->cxt
, devname
, rdonly
);
1087 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1089 lb
= fdisk_get_label(sf
->cxt
, NULL
);
1091 errx(EXIT_FAILURE
, _("%s: no partition table found"), devname
);
1093 n
= fdisk_get_npartitions(sf
->cxt
);
1095 errx(EXIT_FAILURE
, _("%s: partition %zu: partition table contains "
1096 "only %zu partitions"), devname
, partno
, n
);
1097 if (!fdisk_is_partition_used(sf
->cxt
, partno
- 1))
1098 errx(EXIT_FAILURE
, _("%s: partition %zu: partition is unused"),
1103 * sfdisk --part-type <device> <partno> [<type>]
1105 static int command_parttype(struct sfdisk
*sf
, int argc
, char **argv
)
1108 struct fdisk_parttype
*type
= NULL
;
1109 struct fdisk_label
*lb
;
1110 const char *devname
= NULL
, *typestr
= NULL
;
1113 errx(EXIT_FAILURE
, _("no disk device specified"));
1117 errx(EXIT_FAILURE
, _("no partition number specified"));
1118 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1123 errx(EXIT_FAILURE
, _("unexpected arguments"));
1125 /* read-only when a new <type> undefined */
1126 assign_device_partition(sf
, devname
, partno
, !typestr
);
1128 lb
= fdisk_get_label(sf
->cxt
, NULL
);
1130 /* print partition type */
1132 const struct fdisk_parttype
*t
= NULL
;
1133 struct fdisk_partition
*pa
= NULL
;
1135 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1136 t
= fdisk_partition_get_type(pa
);
1138 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition type"),
1141 if (fdisk_label_has_code_parttypes(lb
))
1142 printf("%2x\n", fdisk_parttype_get_code(t
));
1144 printf("%s\n", fdisk_parttype_get_string(t
));
1146 fdisk_unref_partition(pa
);
1147 fdisk_deassign_device(sf
->cxt
, 1);
1152 backup_partition_table(sf
, devname
);
1154 /* parse <type> and apply to PT */
1155 type
= fdisk_label_parse_parttype(lb
, typestr
);
1157 errx(EXIT_FAILURE
, _("failed to parse %s partition type '%s'"),
1158 fdisk_label_get_name(lb
), typestr
);
1160 else if (fdisk_set_partition_type(sf
->cxt
, partno
- 1, type
) != 0)
1161 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition type"),
1163 fdisk_unref_parttype(type
);
1164 return write_changes(sf
);
1168 * sfdisk --part-uuid <device> <partno> [<uuid>]
1170 static int command_partuuid(struct sfdisk
*sf
, int argc
, char **argv
)
1173 struct fdisk_partition
*pa
= NULL
;
1174 const char *devname
= NULL
, *uuid
= NULL
;
1177 errx(EXIT_FAILURE
, _("no disk device specified"));
1181 errx(EXIT_FAILURE
, _("no partition number specified"));
1182 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1187 errx(EXIT_FAILURE
, _("unexpected arguments"));
1189 /* read-only if uuid not given */
1190 assign_device_partition(sf
, devname
, partno
, !uuid
);
1192 /* print partition uuid */
1194 const char *str
= NULL
;
1196 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1197 str
= fdisk_partition_get_uuid(pa
);
1199 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition UUID"),
1201 printf("%s\n", str
);
1202 fdisk_unref_partition(pa
);
1203 fdisk_deassign_device(sf
->cxt
, 1);
1208 backup_partition_table(sf
, devname
);
1210 pa
= fdisk_new_partition();
1212 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1214 if (fdisk_partition_set_uuid(pa
, uuid
) != 0 ||
1215 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1216 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition UUID"),
1218 fdisk_unref_partition(pa
);
1219 return write_changes(sf
);
1223 * sfdisk --part-label <device> <partno> [<label>]
1225 static int command_partlabel(struct sfdisk
*sf
, int argc
, char **argv
)
1228 struct fdisk_partition
*pa
= NULL
;
1229 const char *devname
= NULL
, *name
= NULL
;
1232 errx(EXIT_FAILURE
, _("no disk device specified"));
1236 errx(EXIT_FAILURE
, _("no partition number specified"));
1237 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1242 errx(EXIT_FAILURE
, _("unexpected arguments"));
1244 /* read-only if name not given */
1245 assign_device_partition(sf
, devname
, partno
, !name
);
1247 /* print partition name */
1249 const char *str
= NULL
;
1251 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1252 str
= fdisk_partition_get_name(pa
);
1254 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition name"),
1256 printf("%s\n", str
);
1257 fdisk_unref_partition(pa
);
1258 fdisk_deassign_device(sf
->cxt
, 1);
1263 backup_partition_table(sf
, devname
);
1265 pa
= fdisk_new_partition();
1267 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1269 if (fdisk_partition_set_name(pa
, name
) != 0 ||
1270 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1271 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition name"),
1274 fdisk_unref_partition(pa
);
1275 return write_changes(sf
);
1279 * sfdisk --part-attrs <device> <partno> [<attrs>]
1281 static int command_partattrs(struct sfdisk
*sf
, int argc
, char **argv
)
1284 struct fdisk_partition
*pa
= NULL
;
1285 const char *devname
= NULL
, *attrs
= NULL
;
1288 errx(EXIT_FAILURE
, _("no disk device specified"));
1292 errx(EXIT_FAILURE
, _("no partition number specified"));
1293 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1298 errx(EXIT_FAILURE
, _("unexpected arguments"));
1300 /* read-only if name not given */
1301 assign_device_partition(sf
, devname
, partno
, !attrs
);
1303 /* print partition name */
1305 const char *str
= NULL
;
1307 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1308 str
= fdisk_partition_get_attrs(pa
);
1310 printf("%s\n", str
);
1311 fdisk_unref_partition(pa
);
1312 fdisk_deassign_device(sf
->cxt
, 1);
1317 backup_partition_table(sf
, devname
);
1319 pa
= fdisk_new_partition();
1321 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1323 if (fdisk_partition_set_attrs(pa
, attrs
) != 0 ||
1324 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1325 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition attributes"),
1328 fdisk_unref_partition(pa
);
1329 return write_changes(sf
);
1333 * sfdisk --disk-id <device> [<str>]
1335 static int command_diskid(struct sfdisk
*sf
, int argc
, char **argv
)
1337 const char *devname
= NULL
;
1341 errx(EXIT_FAILURE
, _("no disk device specified"));
1347 errx(EXIT_FAILURE
, _("unexpected arguments"));
1349 if (fdisk_assign_device(sf
->cxt
, devname
, !str
) != 0)
1350 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1354 fdisk_get_disklabel_id(sf
->cxt
, &str
);
1356 printf("%s\n", str
);
1358 fdisk_deassign_device(sf
->cxt
, 1);
1364 backup_partition_table(sf
, devname
);
1366 if (fdisk_set_disklabel_id_from_string(sf
->cxt
, str
) != 0)
1367 errx(EXIT_FAILURE
, _("%s: failed to set disklabel ID"), devname
);
1369 return write_changes(sf
);
1373 * sfdisk --relocate <mode> <device>
1375 static int command_relocate(struct sfdisk
*sf
, int argc
, char **argv
)
1377 const char *devname
= NULL
;
1378 const char *oper
= NULL
;
1379 struct fdisk_label
*lb
;
1382 errx(EXIT_FAILURE
, _("no relocate operation specified"));
1384 errx(EXIT_FAILURE
, _("no disk device specified"));
1386 errx(EXIT_FAILURE
, _("unexpected arguments"));
1390 lb
= fdisk_get_label(sf
->cxt
, "gpt");
1392 if (strcmp(oper
, "gpt-bak-mini") == 0)
1393 fdisk_gpt_enable_minimize(lb
, 1);
1395 else if (strcmp(oper
, "gpt-bak-std") != 0)
1396 errx(EXIT_FAILURE
, _("unsupported relocation operation"));
1398 if (fdisk_assign_device(sf
->cxt
, devname
, 0) != 0)
1399 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1401 fdisk_label_set_changed(lb
, 1);
1403 return write_changes(sf
);
1406 static void sfdisk_print_partition(struct sfdisk
*sf
, size_t n
)
1408 struct fdisk_partition
*pa
= NULL
;
1415 if (fdisk_get_partition(sf
->cxt
, n
, &pa
) != 0)
1418 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_DEVICE
, &data
);
1419 printf("%12s : ", data
);
1421 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_START
, &data
);
1422 printf("%12s ", data
);
1424 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_END
, &data
);
1425 printf("%12s ", data
);
1427 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_SIZE
, &data
);
1428 printf("(%s) ", data
);
1430 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_TYPE
, &data
);
1431 printf("%s\n", data
);
1433 fdisk_unref_partition(pa
);
1436 static void command_fdisk_help(void)
1438 fputs(_("\nHelp:\n"), stdout
);
1440 fputc('\n', stdout
);
1441 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1442 fputs(_(" Commands:\n"), stdout
);
1444 fputs(_(" write write table to disk and exit\n"), stdout
);
1445 fputs(_(" quit show new situation and wait for user's feedback before write\n"), stdout
);
1446 fputs(_(" abort exit sfdisk shell\n"), stdout
);
1447 fputs(_(" print display the partition table\n"), stdout
);
1448 fputs(_(" help show this help text\n"), stdout
);
1449 fputc('\n', stdout
);
1450 fputs(_(" Ctrl-D the same as 'quit'\n"), stdout
);
1452 fputc('\n', stdout
);
1453 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1454 fputs(_(" Input format:\n"), stdout
);
1456 fputs(_(" <start>, <size>, <type>, <bootable>\n"), stdout
);
1458 fputc('\n', stdout
);
1459 fputs(_(" <start> Beginning of the partition in sectors, or bytes if\n"
1460 " specified in the format <number>{K,M,G,T,P,E,Z,Y}.\n"
1461 " The default is the first free space.\n"), stdout
);
1463 fputc('\n', stdout
);
1464 fputs(_(" <size> Size of the partition in sectors, or bytes if\n"
1465 " specified in the format <number>{K,M,G,T,P,E,Z,Y}.\n"
1466 " The default is all available space.\n"), stdout
);
1468 fputc('\n', stdout
);
1469 fputs(_(" <type> The partition type. Default is a Linux data partition.\n"), stdout
);
1470 fputs(_(" MBR: hex or L,S,E,X,U,R,V shortcuts.\n"), stdout
);
1471 fputs(_(" GPT: UUID or L,S,H,U,R,V shortcuts.\n"), stdout
);
1473 fputc('\n', stdout
);
1474 fputs(_(" <bootable> Use '*' to mark an MBR partition as bootable.\n"), stdout
);
1476 fputc('\n', stdout
);
1477 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1478 fputs(_(" Example:\n"), stdout
);
1480 fputs(_(" , 4G Creates a 4GiB partition at default start offset.\n"), stdout
);
1481 fputc('\n', stdout
);
1485 SFDISK_DONE_NONE
= 0,
1492 /* returns: 0 on success, <0 on error, 1 successfully stop sfdisk */
1493 static int loop_control_commands(struct sfdisk
*sf
,
1494 struct fdisk_script
*dp
,
1497 const char *p
= skip_blank(buf
);
1498 int rc
= SFDISK_DONE_NONE
;
1500 if (strcmp(p
, "print") == 0)
1501 list_disklabel(sf
->cxt
);
1502 else if (strcmp(p
, "help") == 0)
1503 command_fdisk_help();
1504 else if (strcmp(p
, "quit") == 0)
1505 rc
= SFDISK_DONE_ASK
;
1506 else if (strcmp(p
, "write") == 0)
1507 rc
= SFDISK_DONE_WRITE
;
1508 else if (strcmp(p
, "abort") == 0)
1509 rc
= SFDISK_DONE_ABORT
;
1511 if (sf
->interactive
)
1512 fdisk_warnx(sf
->cxt
, _("unsupported command"));
1514 fdisk_warnx(sf
->cxt
, _("line %d: unsupported command"),
1515 fdisk_script_get_nlines(dp
));
1522 static int has_container(struct sfdisk
*sf
)
1525 struct fdisk_partition
*pa
= NULL
;
1528 return sf
->container
;
1530 nparts
= fdisk_get_npartitions(sf
->cxt
);
1531 for (i
= 0; i
< nparts
; i
++) {
1532 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0)
1534 if (fdisk_partition_is_container(pa
)) {
1540 fdisk_unref_partition(pa
);
1541 return sf
->container
;
1544 static size_t last_pt_partno(struct sfdisk
*sf
)
1546 size_t i
, nparts
, partno
= 0;
1547 struct fdisk_partition
*pa
= NULL
;
1550 nparts
= fdisk_get_npartitions(sf
->cxt
);
1551 for (i
= 0; i
< nparts
; i
++) {
1554 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0 ||
1555 !fdisk_partition_is_used(pa
))
1557 x
= fdisk_partition_get_partno(pa
);
1562 fdisk_unref_partition(pa
);
1566 #ifdef HAVE_LIBREADLINE
1567 static char *sfdisk_fgets(struct fdisk_script
*dp
,
1568 char *buf
, size_t bufsz
, FILE *f
)
1570 struct sfdisk
*sf
= (struct sfdisk
*) fdisk_script_get_userdata(dp
);
1576 if (sf
->interactive
) {
1577 char *p
= readline(sf
->prompt
);
1583 if (len
> bufsz
- 2)
1586 memcpy(buf
, p
, len
);
1587 buf
[len
] = '\n'; /* append \n to be compatible with libc fgetc() */
1588 buf
[len
+ 1] = '\0';
1593 return fgets(buf
, bufsz
, f
);
1597 static int ignore_partition(struct fdisk_partition
*pa
)
1599 /* incomplete partition setting */
1600 if (!fdisk_partition_has_start(pa
) && !fdisk_partition_start_is_default(pa
))
1602 if (!fdisk_partition_has_size(pa
) && !fdisk_partition_end_is_default(pa
))
1605 /* probably dump from old sfdisk with start=0 size=0 */
1606 if (fdisk_partition_has_start(pa
) && fdisk_partition_get_start(pa
) == 0 &&
1607 fdisk_partition_has_size(pa
) && fdisk_partition_get_size(pa
) == 0)
1613 static void follow_wipe_mode(struct sfdisk
*sf
)
1615 int dowipe
= sf
->wipemode
== WIPEMODE_ALWAYS
? 1 : 0;
1617 if (sf
->interactive
&& sf
->wipemode
== WIPEMODE_AUTO
)
1618 dowipe
= 1; /* do it in interactive mode */
1620 if (fdisk_is_ptcollision(sf
->cxt
) && sf
->wipemode
!= WIPEMODE_NEVER
)
1621 dowipe
= 1; /* always wipe old PT */
1623 fdisk_enable_wipe(sf
->cxt
, dowipe
);
1628 if (!fdisk_is_ptcollision(sf
->cxt
)) {
1629 fdisk_warnx(sf
->cxt
, _(
1630 "The device contains '%s' signature and it will be removed by a write command. "
1631 "See sfdisk(8) man page and --wipe option for more details."),
1632 fdisk_get_collision(sf
->cxt
));
1633 fputc('\n', stdout
);
1636 fdisk_warnx(sf
->cxt
, _(
1637 "The device contains '%s' signature and it may remain on the device. "
1638 "It is recommended to wipe the device with wipefs(8) or "
1639 "sfdisk --wipe, in order to avoid possible collisions."),
1640 fdisk_get_collision(sf
->cxt
));
1641 fputc('\n', stderr
);
1645 static int wipe_partition(struct sfdisk
*sf
, size_t partno
)
1648 char *fstype
= NULL
;
1649 struct fdisk_partition
*tmp
= NULL
;
1651 DBG(MISC
, ul_debug("checking for signature"));
1653 rc
= fdisk_get_partition(sf
->cxt
, partno
, &tmp
);
1657 rc
= fdisk_partition_to_string(tmp
, sf
->cxt
, FDISK_FIELD_FSTYPE
, &fstype
);
1658 if (rc
|| fstype
== NULL
)
1661 fdisk_warnx(sf
->cxt
, _("Partition #%zu contains a %s signature."), partno
+ 1, fstype
);
1663 if (sf
->pwipemode
== WIPEMODE_AUTO
&& isatty(STDIN_FILENO
))
1664 fdisk_ask_yesno(sf
->cxt
, _("Do you want to remove the signature?"), &yes
);
1665 else if (sf
->pwipemode
== WIPEMODE_ALWAYS
)
1669 fdisk_info(sf
->cxt
, _("The signature will be removed by a write command."));
1670 rc
= fdisk_wipe_partition(sf
->cxt
, partno
, TRUE
);
1673 fdisk_unref_partition(tmp
);
1675 DBG(MISC
, ul_debug("partition wipe check end [rc=%d]", rc
));
1679 static void refresh_prompt_buffer(struct sfdisk
*sf
, const char *devname
,
1680 size_t next_partno
, int created
)
1683 char *partname
= fdisk_partname(devname
, next_partno
+ 1);
1685 err(EXIT_FAILURE
, _("failed to allocate partition name"));
1687 if (!sf
->prompt
|| !startswith(sf
->prompt
, partname
)) {
1689 xasprintf(&sf
->prompt
,"%s: ", partname
);
1692 } else if (!sf
->prompt
|| !startswith(sf
->prompt
, SFDISK_PROMPT
)) {
1694 sf
->prompt
= xstrdup(SFDISK_PROMPT
);
1699 * sfdisk <device> [[-N] <partno>]
1701 * Note that the option -N is there for backward compatibility only.
1703 static int command_fdisk(struct sfdisk
*sf
, int argc
, char **argv
)
1705 int rc
= 0, partno
= sf
->partno
, created
= 0, unused
= 0;
1706 struct fdisk_script
*dp
;
1707 struct fdisk_table
*tb
= NULL
;
1708 const char *devname
= NULL
, *label
;
1710 size_t next_partno
= (size_t) -1;
1714 if (partno
< 0 && argc
> 1)
1715 partno
= strtou32_or_err(argv
[1],
1716 _("failed to parse partition number"));
1718 errx(EXIT_FAILURE
, _("no disk device specified"));
1720 rc
= fdisk_assign_device(sf
->cxt
, devname
, 0);
1722 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1724 dp
= fdisk_new_script(sf
->cxt
);
1726 err(EXIT_FAILURE
, _("failed to allocate script handler"));
1727 fdisk_set_script(sf
->cxt
, dp
);
1728 #ifdef HAVE_LIBREADLINE
1729 fdisk_script_set_fgets(dp
, sfdisk_fgets
);
1731 fdisk_script_set_userdata(dp
, (void *) sf
);
1734 * Don't create a new disklabel when [-N] <partno> specified. In this
1735 * case reuse already specified disklabel. Let's check that the disk
1736 * really contains the partition.
1741 if (!fdisk_has_label(sf
->cxt
))
1742 errx(EXIT_FAILURE
, _("%s: cannot modify partition %d: "
1743 "no partition table was found"),
1744 devname
, partno
+ 1);
1745 n
= fdisk_get_npartitions(sf
->cxt
);
1746 if ((size_t) partno
> n
)
1747 errx(EXIT_FAILURE
, _("%s: cannot modify partition %d: "
1748 "partition table contains only %zu "
1750 devname
, partno
+ 1, n
);
1752 if (!fdisk_is_partition_used(sf
->cxt
, partno
)) {
1753 fdisk_warnx(sf
->cxt
, _("warning: %s: partition %d is not defined yet"),
1754 devname
, partno
+ 1);
1758 next_partno
= partno
;
1761 sf
->orig_pa
= get_partition(sf
->cxt
, partno
);
1766 next_partno
= last_pt_partno(sf
) + 1;
1769 if (!sf
->quiet
&& sf
->interactive
) {
1770 color_scheme_enable("welcome", UL_COLOR_GREEN
);
1771 fdisk_info(sf
->cxt
, _("\nWelcome to sfdisk (%s)."), PACKAGE_STRING
);
1773 fdisk_info(sf
->cxt
, _("Changes will remain in memory only, until you decide to write them.\n"
1774 "Be careful before using the write command.\n"));
1777 if (!sf
->noact
&& !sf
->noreread
) {
1779 fputs(_("Checking that no-one is using this disk right now ..."), stdout
);
1780 if (fdisk_device_is_used(sf
->cxt
)) {
1782 fputs(_(" FAILED\n\n"), stdout
);
1784 fdisk_warnx(sf
->cxt
, _(
1785 "This disk is currently in use - repartitioning is probably a bad idea.\n"
1786 "Umount all file systems, and swapoff all swap partitions on this disk.\n"
1787 "Use the --no-reread flag to suppress this check.\n"));
1790 errx(EXIT_FAILURE
, _("Use the --force flag to overrule all checks."));
1791 } else if (!sf
->quiet
)
1792 fputs(_(" OK\n\n"), stdout
);
1795 if (fdisk_get_collision(sf
->cxt
))
1796 follow_wipe_mode(sf
);
1799 backup_partition_table(sf
, devname
);
1802 list_disk_geometry(sf
->cxt
);
1803 if (fdisk_has_label(sf
->cxt
)) {
1804 fdisk_info(sf
->cxt
, _("\nOld situation:"));
1805 list_disklabel(sf
->cxt
);
1811 else if (fdisk_has_label(sf
->cxt
))
1812 label
= fdisk_label_get_name(fdisk_get_label(sf
->cxt
, NULL
));
1814 label
= "dos"; /* just for backward compatibility */
1816 if (fdisk_script_set_header(dp
, "label", label
) != 0)
1817 errx(EXIT_FAILURE
, _("failed to set script header"));
1819 if (!sf
->quiet
&& sf
->interactive
) {
1820 if (!fdisk_has_label(sf
->cxt
) && !sf
->label
)
1822 _("\nsfdisk is going to create a new '%s' disk label.\n"
1823 "Use 'label: <name>' before you define a first partition\n"
1824 "to override the default."), label
);
1825 fdisk_info(sf
->cxt
, _("\nType 'help' to get more information.\n"));
1826 } else if (!sf
->quiet
)
1827 fputc('\n', stdout
);
1829 tb
= fdisk_script_get_table(dp
);
1835 DBG(PARSE
, ul_debug("<---next-line--->"));
1836 if (next_partno
== (size_t) -1)
1837 next_partno
= fdisk_table_get_nents(tb
);
1841 && next_partno
== fdisk_get_npartitions(sf
->cxt
)
1842 && !has_container(sf
)) {
1843 fdisk_info(sf
->cxt
, _("All partitions used."));
1844 rc
= SFDISK_DONE_ASK
;
1848 refresh_prompt_buffer(sf
, devname
, next_partno
, created
);
1851 if (sf
->prompt
&& (sf
->interactive
|| !sf
->quiet
)) {
1852 #ifndef HAVE_LIBREADLINE
1853 fputs(sf
->prompt
, stdout
);
1855 if (!sf
->interactive
)
1856 fputs(sf
->prompt
, stdout
);
1860 rc
= fdisk_script_read_line(dp
, stdin
, buf
, sizeof(buf
));
1861 if (rc
== -ENOTSUP
) {
1862 buf
[sizeof(buf
) - 1] = '\0';
1863 fdisk_warnx(sf
->cxt
, _("Unknown script header '%s' -- ignore."), buf
);
1865 } else if (rc
< 0) {
1866 DBG(PARSE
, ul_debug("script parsing failed, trying sfdisk specific commands"));
1867 buf
[sizeof(buf
) - 1] = '\0';
1868 rc
= loop_control_commands(sf
, dp
, buf
);
1872 } else if (rc
== 1) {
1873 rc
= SFDISK_DONE_EOF
;
1875 fputs(_("Done.\n"), stdout
);
1879 nparts
= fdisk_table_get_nents(tb
);
1881 size_t cur_partno
= (size_t) -1;
1882 struct fdisk_partition
*pa
= fdisk_table_get_partition(tb
, nparts
- 1);
1886 if (ignore_partition(pa
)) {
1887 fdisk_info(sf
->cxt
, _("Ignoring partition."));
1891 if (!created
) { /* create a new disklabel */
1892 rc
= fdisk_apply_script_headers(sf
->cxt
, dp
);
1895 fdisk_warnx(sf
->cxt
, _(
1896 "Failed to apply script headers, "
1897 "disk label not created."));
1899 if (rc
== 0 && fdisk_get_collision(sf
->cxt
))
1900 follow_wipe_mode(sf
);
1902 if (!rc
&& partno
>= 0) { /* -N <partno>, modify partition */
1903 rc
= fdisk_set_partition(sf
->cxt
, partno
, pa
);
1904 rc
= rc
== 0 ? SFDISK_DONE_ASK
: SFDISK_DONE_ABORT
;
1906 } else if (!rc
) { /* add partition */
1907 if (!sf
->interactive
&& !sf
->quiet
&&
1908 (!sf
->prompt
|| startswith(sf
->prompt
, SFDISK_PROMPT
))) {
1909 refresh_prompt_buffer(sf
, devname
, next_partno
, created
);
1910 fputs(sf
->prompt
, stdout
);
1912 rc
= fdisk_add_partition(sf
->cxt
, pa
, &cur_partno
);
1915 fdisk_warn(sf
->cxt
, _("Failed to add #%d partition"), next_partno
+ 1);
1919 /* wipe partition on success
1921 * Note that unused=1 means -N <partno> for unused,
1922 * otherwise we wipe only newly created partitions.
1924 if (rc
== 0 && (unused
|| partno
< 0)) {
1925 rc
= wipe_partition(sf
, unused
? (size_t) partno
: cur_partno
);
1931 /* success print result */
1932 if (sf
->interactive
)
1933 sfdisk_print_partition(sf
, cur_partno
);
1934 next_partno
= cur_partno
+ 1;
1935 } else if (pa
) /* error, drop partition from script */
1936 fdisk_table_remove_partition(tb
, pa
);
1938 fdisk_info(sf
->cxt
, _("Script header accepted."));
1940 if (rc
&& !sf
->interactive
) {
1941 rc
= SFDISK_DONE_ABORT
;
1946 /* create empty disk label if label, but no partition specified */
1947 if ((rc
== SFDISK_DONE_EOF
|| rc
== SFDISK_DONE_WRITE
) && created
== 0
1948 && fdisk_script_has_force_label(dp
) == 1
1949 && fdisk_table_get_nents(tb
) == 0
1950 && fdisk_script_get_header(dp
, "label")) {
1952 int xrc
= fdisk_apply_script_headers(sf
->cxt
, dp
);
1954 fdisk_warnx(sf
->cxt
, _(
1955 "Failed to apply script headers, "
1956 "disk label not created."));
1957 rc
= SFDISK_DONE_ABORT
;
1961 if (!sf
->quiet
&& rc
!= SFDISK_DONE_ABORT
) {
1962 fdisk_info(sf
->cxt
, _("\nNew situation:"));
1963 list_disk_identifier(sf
->cxt
);
1964 list_disklabel(sf
->cxt
);
1968 case SFDISK_DONE_ASK
:
1969 case SFDISK_DONE_EOF
:
1970 if (sf
->interactive
) {
1972 fdisk_ask_yesno(sf
->cxt
, _("Do you want to write this to disk?"), &yes
);
1974 fdisk_info(sf
->cxt
, _("Leaving."));
1980 case SFDISK_DONE_WRITE
:
1981 rc
= write_changes(sf
);
1983 case SFDISK_DONE_ABORT
:
1984 default: /* rc < 0 on error */
1985 fdisk_info(sf
->cxt
, _("Leaving.\n"));
1989 fdisk_set_script(sf
->cxt
, NULL
);
1990 fdisk_unref_script(dp
);
1994 static void __attribute__((__noreturn__
)) usage(void)
1997 fputs(USAGE_HEADER
, out
);
2000 _(" %1$s [options] <dev> [[-N] <part>]\n"
2001 " %1$s [options] <command>\n"), program_invocation_short_name
);
2003 fputs(USAGE_SEPARATOR
, out
);
2004 fputs(_("Display or manipulate a disk partition table.\n"), out
);
2006 fputs(USAGE_COMMANDS
, out
);
2007 fputs(_(" -A, --activate <dev> [<part> ...] list or set bootable (P)MBR partitions\n"), out
);
2008 fputs(_(" -d, --dump <dev> dump partition table (usable for later input)\n"), out
);
2009 fputs(_(" -J, --json <dev> dump partition table in JSON format\n"), out
);
2010 fputs(_(" -g, --show-geometry [<dev> ...] list geometry of all or specified devices\n"), out
);
2011 fputs(_(" -l, --list [<dev> ...] list partitions of each device\n"), out
);
2012 fputs(_(" -F, --list-free [<dev> ...] list unpartitioned free areas of each device\n"), out
);
2013 fputs(_(" -r, --reorder <dev> fix partitions order (by start offset)\n"), out
);
2014 fputs(_(" -s, --show-size [<dev> ...] list sizes of all or specified devices\n"), out
);
2015 fputs(_(" -T, --list-types print the recognized types (see -X)\n"), out
);
2016 fputs(_(" -V, --verify [<dev> ...] test whether partitions seem correct\n"), out
);
2017 fputs(_(" --delete <dev> [<part> ...] delete all or specified partitions\n"), out
);
2019 fputs(USAGE_SEPARATOR
, out
);
2020 fputs(_(" --part-label <dev> <part> [<str>] print or change partition label\n"), out
);
2021 fputs(_(" --part-type <dev> <part> [<type>] print or change partition type\n"), out
);
2022 fputs(_(" --part-uuid <dev> <part> [<uuid>] print or change partition uuid\n"), out
);
2023 fputs(_(" --part-attrs <dev> <part> [<str>] print or change partition attributes\n"), out
);
2025 fputs(USAGE_SEPARATOR
, out
);
2026 fputs(_(" --disk-id <dev> [<str>] print or change disk label ID (UUID)\n"), out
);
2027 fputs(_(" --relocate <oper> <dev> move partition header\n"), out
);
2029 fputs(USAGE_ARGUMENTS
, out
);
2030 fputs(_(" <dev> device (usually disk) path\n"), out
);
2031 fputs(_(" <part> partition number\n"), out
);
2032 fputs(_(" <type> partition type, GUID for GPT, hex for MBR\n"), out
);
2034 fputs(USAGE_OPTIONS
, out
);
2035 fputs(_(" -a, --append append partitions to existing partition table\n"), out
);
2036 fputs(_(" -b, --backup backup partition table sectors (see -O)\n"), out
);
2037 fputs(_(" --bytes print SIZE in bytes rather than in human readable format\n"), out
);
2038 fputs(_(" --move-data[=<typescript>] move partition data after relocation (requires -N)\n"), out
);
2039 fputs(_(" --move-use-fsync use fsync after each write when move data\n"), out
);
2040 fputs(_(" -f, --force disable all consistency checking\n"), out
);
2043 _(" --color[=<when>] colorize output (%s, %s or %s)\n"), "auto", "always", "never");
2045 " %s\n", USAGE_COLORS_DEFAULT
);
2046 fputs(_(" -N, --partno <num> specify partition number\n"), out
);
2047 fputs(_(" -n, --no-act do everything except write to device\n"), out
);
2048 fputs(_(" --no-reread do not check whether the device is in use\n"), out
);
2049 fputs(_(" --no-tell-kernel do not tell kernel about changes\n"), out
);
2050 fputs(_(" -O, --backup-file <path> override default backup file name\n"), out
);
2051 fputs(_(" -o, --output <list> output columns\n"), out
);
2052 fputs(_(" -q, --quiet suppress extra info messages\n"), out
);
2054 _(" -w, --wipe <mode> wipe signatures (%s, %s or %s)\n"), "auto", "always", "never");
2056 _(" -W, --wipe-partitions <mode> wipe signatures from new partitions (%s, %s or %s)\n"), "auto", "always", "never");
2057 fputs(_(" -X, --label <name> specify label type (dos, gpt, ...)\n"), out
);
2058 fputs(_(" -Y, --label-nested <name> specify nested label type (dos, bsd)\n"), out
);
2059 fputs(USAGE_SEPARATOR
, out
);
2060 fputs(_(" -G, --show-pt-geometry deprecated, alias to --show-geometry\n"), out
);
2061 fputs(_(" -L, --Linux deprecated, only for backward compatibility\n"), out
);
2062 fputs(_(" -u, --unit S deprecated, only sector unit is supported\n"), out
);
2064 fputs(USAGE_SEPARATOR
, out
);
2065 printf( " -h, --help %s\n", USAGE_OPTSTR_HELP
);
2066 printf( " -v, --version %s\n", USAGE_OPTSTR_VERSION
);
2068 list_available_columns(out
);
2070 printf(USAGE_MAN_TAIL("sfdisk(8)"));
2075 int main(int argc
, char *argv
[])
2077 const char *outarg
= NULL
;
2078 int rc
= -EINVAL
, c
, longidx
= -1, bytes
= 0;
2079 int colormode
= UL_COLORMODE_UNDEF
;
2080 struct sfdisk _sf
= {
2082 .wipemode
= WIPEMODE_AUTO
,
2083 .pwipemode
= WIPEMODE_AUTO
,
2084 .interactive
= isatty(STDIN_FILENO
) ? 1 : 0,
2088 OPT_CHANGE_ID
= CHAR_MAX
+ 1,
2106 static const struct option longopts
[] = {
2107 { "activate",no_argument
, NULL
, 'A' },
2108 { "append", no_argument
, NULL
, 'a' },
2109 { "backup", no_argument
, NULL
, 'b' },
2110 { "backup-file", required_argument
, NULL
, 'O' },
2111 { "bytes", no_argument
, NULL
, OPT_BYTES
},
2112 { "color", optional_argument
, NULL
, OPT_COLOR
},
2113 { "delete", no_argument
, NULL
, OPT_DELETE
},
2114 { "dump", no_argument
, NULL
, 'd' },
2115 { "help", no_argument
, NULL
, 'h' },
2116 { "force", no_argument
, NULL
, 'f' },
2117 { "json", no_argument
, NULL
, 'J' },
2118 { "label", required_argument
, NULL
, 'X' },
2119 { "label-nested", required_argument
, NULL
, 'Y' },
2120 { "list", no_argument
, NULL
, 'l' },
2121 { "list-free", no_argument
, NULL
, 'F' },
2122 { "list-types", no_argument
, NULL
, 'T' },
2123 { "no-act", no_argument
, NULL
, 'n' },
2124 { "no-reread", no_argument
, NULL
, OPT_NOREREAD
},
2125 { "no-tell-kernel", no_argument
, NULL
, OPT_NOTELL
},
2126 { "move-data", optional_argument
, NULL
, OPT_MOVEDATA
},
2127 { "move-use-fsync", no_argument
, NULL
, OPT_MOVEFSYNC
},
2128 { "output", required_argument
, NULL
, 'o' },
2129 { "partno", required_argument
, NULL
, 'N' },
2130 { "reorder", no_argument
, NULL
, 'r' },
2131 { "show-geometry", no_argument
, NULL
, 'g' },
2132 { "quiet", no_argument
, NULL
, 'q' },
2133 { "verify", no_argument
, NULL
, 'V' },
2134 { "version", no_argument
, NULL
, 'v' },
2135 { "wipe", required_argument
, NULL
, 'w' },
2136 { "wipe-partitions", required_argument
, NULL
, 'W' },
2138 { "relocate", no_argument
, NULL
, OPT_RELOCATE
},
2140 { "part-uuid", no_argument
, NULL
, OPT_PARTUUID
},
2141 { "part-label", no_argument
, NULL
, OPT_PARTLABEL
},
2142 { "part-type", no_argument
, NULL
, OPT_PARTTYPE
},
2143 { "part-attrs", no_argument
, NULL
, OPT_PARTATTRS
},
2145 { "disk-id", no_argument
, NULL
, OPT_DISKID
},
2147 { "show-pt-geometry", no_argument
, NULL
, 'G' }, /* deprecated */
2148 { "unit", required_argument
, NULL
, 'u' }, /* deprecated */
2149 { "Linux", no_argument
, NULL
, 'L' }, /* deprecated */
2150 { "show-size", no_argument
, NULL
, 's' }, /* deprecated */
2152 { "change-id",no_argument
, NULL
, OPT_CHANGE_ID
}, /* deprecated */
2153 { "id", no_argument
, NULL
, 'c' }, /* deprecated */
2154 { "print-id",no_argument
, NULL
, OPT_PRINT_ID
}, /* deprecated */
2156 { NULL
, 0, NULL
, 0 },
2158 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
2159 { 'F','J','d'}, /* --list-free --json --dump */
2160 { 's','u'}, /* --show-size --unit */
2163 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
2166 setlocale(LC_ALL
, "");
2167 bindtextdomain(PACKAGE
, LOCALEDIR
);
2168 textdomain(PACKAGE
);
2169 close_stdout_atexit();
2171 while ((c
= getopt_long(argc
, argv
, "aAbcdfFgGhJlLo:O:nN:qrsTu:vVX:Y:w:W:",
2172 longopts
, &longidx
)) != -1) {
2174 err_exclusive_options(c
, longopts
, excl
, excl_st
);
2178 sf
->act
= ACT_ACTIVATE
;
2189 warnx(_("%s is deprecated in favour of --part-type"),
2190 longopts
[longidx
].name
);
2191 sf
->act
= ACT_PARTTYPE
;
2194 warnx(_("--id is deprecated in favour of --part-type"));
2195 sf
->act
= ACT_PARTTYPE
;
2204 sf
->act
= ACT_LIST_FREE
;
2210 warnx(_("--show-pt-geometry is no more implemented. Using --show-geometry."));
2213 sf
->act
= ACT_SHOW_GEOM
;
2222 warnx(_("--Linux option is unnecessary and deprecated"));
2229 sf
->backup_file
= optarg
;
2235 sf
->partno
= strtou32_or_err(optarg
, _("failed to parse partition number")) - 1;
2241 sf
->act
= ACT_REORDER
;
2244 sf
->act
= ACT_SHOW_SIZE
;
2247 sf
->act
= ACT_LIST_TYPES
;
2251 errx(EXIT_FAILURE
, _("unsupported unit '%c'"), *optarg
);
2254 print_version(EXIT_SUCCESS
);
2259 sf
->wipemode
= wipemode_from_string(optarg
);
2260 if (sf
->wipemode
< 0)
2261 errx(EXIT_FAILURE
, _("unsupported wipe mode"));
2264 sf
->pwipemode
= wipemode_from_string(optarg
);
2265 if (sf
->pwipemode
< 0)
2266 errx(EXIT_FAILURE
, _("unsupported wipe mode"));
2272 sf
->label_nested
= optarg
;
2276 sf
->act
= ACT_PARTUUID
;
2279 sf
->act
= ACT_PARTTYPE
;
2282 sf
->act
= ACT_PARTLABEL
;
2285 sf
->act
= ACT_PARTATTRS
;
2288 sf
->act
= ACT_DISKID
;
2297 colormode
= UL_COLORMODE_AUTO
;
2299 colormode
= colormode_or_err(optarg
,
2300 _("unsupported color mode"));
2304 sf
->move_typescript
= optarg
;
2310 sf
->act
= ACT_DELETE
;
2316 sf
->act
= ACT_RELOCATE
;
2319 errtryhelp(EXIT_FAILURE
);
2323 colors_init(colormode
, "sfdisk");
2327 fdisk_set_size_unit(sf
->cxt
, FDISK_SIZEUNIT_BYTES
);
2330 init_fields(NULL
, outarg
, NULL
);
2332 if (sf
->verify
&& !sf
->act
)
2333 sf
->act
= ACT_VERIFY
; /* --verify make be used with --list too */
2335 sf
->act
= ACT_FDISK
; /* default */
2337 if (sf
->movedata
&& !(sf
->act
== ACT_FDISK
&& sf
->partno
>= 0))
2338 errx(EXIT_FAILURE
, _("--movedata requires -N"));
2342 rc
= command_activate(sf
, argc
- optind
, argv
+ optind
);
2346 rc
= command_delete(sf
, argc
- optind
, argv
+ optind
);
2350 rc
= command_list_partitions(sf
, argc
- optind
, argv
+ optind
);
2353 case ACT_LIST_TYPES
:
2354 rc
= command_list_types(sf
);
2358 rc
= command_list_freespace(sf
, argc
- optind
, argv
+ optind
);
2362 rc
= command_fdisk(sf
, argc
- optind
, argv
+ optind
);
2366 rc
= command_dump(sf
, argc
- optind
, argv
+ optind
);
2370 rc
= command_show_size(sf
, argc
- optind
, argv
+ optind
);
2374 rc
= command_show_geometry(sf
, argc
- optind
, argv
+ optind
);
2378 rc
= command_verify(sf
, argc
- optind
, argv
+ optind
);
2382 rc
= command_parttype(sf
, argc
- optind
, argv
+ optind
);
2386 rc
= command_partuuid(sf
, argc
- optind
, argv
+ optind
);
2390 rc
= command_partlabel(sf
, argc
- optind
, argv
+ optind
);
2394 rc
= command_partattrs(sf
, argc
- optind
, argv
+ optind
);
2398 rc
= command_diskid(sf
, argc
- optind
, argv
+ optind
);
2402 rc
= command_reorder(sf
, argc
- optind
, argv
+ optind
);
2406 rc
= command_relocate(sf
, argc
- optind
, argv
+ optind
);
2412 DBG(MISC
, ul_debug("bye! [rc=%d]", rc
));
2413 return rc
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;