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)
95 int partno
; /* -N <partno>, default -1 */
96 int wipemode
; /* remove foreign signatures from disk */
97 int pwipemode
; /* remove foreign signatures from partitions */
98 const char *label
; /* --label <label> */
99 const char *label_nested
; /* --label-nested <label> */
100 const char *backup_file
; /* -O <path> */
101 const char *move_typescript
; /* --movedata <typescript> */
104 struct fdisk_context
*cxt
; /* libfdisk context */
105 struct fdisk_partition
*orig_pa
; /* -N <partno> before the change */
107 unsigned int verify
: 1, /* call fdisk_verify_disklabel() */
108 quiet
: 1, /* suppress extra messages */
109 interactive
: 1, /* running on tty */
110 noreread
: 1, /* don't check device is in use */
111 force
: 1, /* do also stupid things */
112 backup
: 1, /* backup sectors before write PT */
113 container
: 1, /* PT contains container (MBR extended) partitions */
114 append
: 1, /* don't create new PT, append partitions only */
115 json
: 1, /* JSON dump */
116 movedata
: 1, /* move data after resize */
117 movefsync
: 1, /* use fsync() after each write() */
118 notell
: 1, /* don't tell kernel aout new PT */
119 noact
: 1; /* do not write to device */
122 #define SFDISK_PROMPT ">>> "
124 static void sfdiskprog_init_debug(void)
126 __UL_INIT_DEBUG_FROM_ENV(sfdisk
, SFDISKPROG_DEBUG_
, 0, SFDISK_DEBUG
);
130 static int get_user_reply(const char *prompt
, char *buf
, size_t bufsz
)
135 #ifdef HAVE_LIBREADLINE
136 if (isatty(STDIN_FILENO
)) {
137 p
= readline(prompt
);
140 xstrncpy(buf
, p
, bufsz
);
145 fputs(prompt
, stdout
);
148 if (!fgets(buf
, bufsz
, stdin
))
152 for (p
= buf
; *p
&& !isgraph(*p
); p
++); /* get first non-blank */
155 memmove(buf
, p
, p
- buf
); /* remove blank space */
157 if (sz
&& *(buf
+ sz
- 1) == '\n')
158 *(buf
+ sz
- 1) = '\0';
160 DBG(ASK
, ul_debug("user's reply: >>>%s<<<", buf
));
164 static int ask_callback(struct fdisk_context
*cxt
__attribute__((__unused__
)),
165 struct fdisk_ask
*ask
,
168 struct sfdisk
*sf
= (struct sfdisk
*) data
;
173 switch(fdisk_ask_get_type(ask
)) {
174 case FDISK_ASKTYPE_INFO
:
177 fputs(fdisk_ask_print_get_mesg(ask
), stdout
);
180 case FDISK_ASKTYPE_WARNX
:
182 color_scheme_fenable("warn", UL_COLOR_RED
, stderr
);
183 fputs(fdisk_ask_print_get_mesg(ask
), stderr
);
184 color_fdisable(stderr
);
187 case FDISK_ASKTYPE_WARN
:
189 color_scheme_fenable("warn", UL_COLOR_RED
, stderr
);
190 fputs(fdisk_ask_print_get_mesg(ask
), stderr
);
191 errno
= fdisk_ask_print_get_errno(ask
);
192 fprintf(stderr
, ": %m\n");
193 color_fdisable(stderr
);
195 case FDISK_ASKTYPE_YESNO
:
197 char buf
[BUFSIZ
] = { '\0' };
201 fputs(fdisk_ask_get_query(ask
), stdout
);
202 rc
= get_user_reply(_(" [Y]es/[N]o: "), buf
, sizeof(buf
));
206 if (x
== RPMATCH_YES
|| x
== RPMATCH_NO
) {
207 fdisk_ask_yesno_set_result(ask
, x
);
211 DBG(ASK
, ul_debug("yes-no ask: reply '%s' [rc=%d]", buf
, rc
));
220 static void sfdisk_init(struct sfdisk
*sf
)
224 sfdiskprog_init_debug();
226 sf
->cxt
= fdisk_new_context();
228 err(EXIT_FAILURE
, _("failed to allocate libfdisk context"));
229 fdisk_set_ask(sf
->cxt
, ask_callback
, (void *) sf
);
230 fdisk_enable_bootbits_protection(sf
->cxt
, 1);
232 if (sf
->label_nested
) {
233 struct fdisk_context
*x
= fdisk_new_nested_context(sf
->cxt
,
236 err(EXIT_FAILURE
, _("failed to allocate nested libfdisk context"));
237 /* the original context is available by fdisk_get_parent() */
242 static int sfdisk_deinit(struct sfdisk
*sf
)
244 struct fdisk_context
*parent
;
249 parent
= fdisk_get_parent(sf
->cxt
);
251 fdisk_unref_context(sf
->cxt
);
255 fdisk_unref_context(sf
->cxt
);
258 memset(sf
, 0, sizeof(*sf
));
262 static struct fdisk_partition
*get_partition(struct fdisk_context
*cxt
, size_t partno
)
264 struct fdisk_table
*tb
= NULL
;
265 struct fdisk_partition
*pa
;
267 if (fdisk_get_partitions(cxt
, &tb
) != 0)
270 pa
= fdisk_table_get_partition_by_partno(tb
, partno
);
272 fdisk_ref_partition(pa
);
273 fdisk_unref_table(tb
);
277 static void backup_sectors(struct sfdisk
*sf
,
281 uint64_t offset
, size_t size
)
286 devfd
= fdisk_get_devfd(sf
->cxt
);
289 xasprintf(&fname
, "%s0x%08"PRIx64
".bak", tpl
, offset
);
291 fd
= open(fname
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
);
295 if (lseek(devfd
, (off_t
) offset
, SEEK_SET
) == (off_t
) -1) {
296 fdisk_warn(sf
->cxt
, _("cannot seek %s"), devname
);
299 unsigned char *buf
= xmalloc(size
);
301 if (read_all(devfd
, (char *) buf
, size
) != (ssize_t
) size
) {
302 fdisk_warn(sf
->cxt
, _("cannot read %s"), devname
);
306 if (write_all(fd
, buf
, size
) != 0) {
307 fdisk_warn(sf
->cxt
, _("cannot write %s"), fname
);
314 fdisk_info(sf
->cxt
, _("%12s (offset %5ju, size %5ju): %s"),
315 name
, (uintmax_t) offset
, (uintmax_t) size
, fname
);
320 errx(EXIT_FAILURE
, _("%s: failed to create a backup"), devname
);
323 static char *mk_backup_filename_tpl(const char *filename
, const char *devname
, const char *suffix
)
326 char *name
, *buf
= xstrdup(devname
);
328 name
= basename(buf
);
330 if (!filename
|| strcmp(filename
, "@default") == 0) {
331 const char *home
= getenv ("HOME");
333 errx(EXIT_FAILURE
, _("failed to create a backup file, $HOME undefined"));
334 xasprintf(&tpl
, "%s/sfdisk-%s%s", home
, name
, suffix
);
336 xasprintf(&tpl
, "%s-%s%s", filename
, name
, suffix
);
343 static void backup_partition_table(struct sfdisk
*sf
, const char *devname
)
353 if (!fdisk_has_label(sf
->cxt
))
356 tpl
= mk_backup_filename_tpl(sf
->backup_file
, devname
, "-");
358 color_scheme_enable("header", UL_COLOR_BOLD
);
359 fdisk_info(sf
->cxt
, _("Backup files:"));
362 while (fdisk_locate_disklabel(sf
->cxt
, i
++, &name
, &offset
, &size
) == 0 && size
)
363 backup_sectors(sf
, tpl
, name
, devname
, offset
, size
);
370 static int move_partition_data(struct sfdisk
*sf
, size_t partno
, struct fdisk_partition
*orig_pa
)
372 struct fdisk_partition
*pa
= get_partition(sf
->cxt
, partno
);
373 char *devname
= NULL
, *typescript
= NULL
, *buf
= NULL
;
375 int ok
= 0, fd
, backward
= 0;
376 fdisk_sector_t nsectors
, from
, to
, step
, i
, prev
;
377 size_t io
, ss
, step_bytes
, cc
;
378 uintmax_t src
, dst
, nbytes
;
379 int errsv
, progress
= 0;
380 struct timeval prev_time
;
381 uint64_t bytes_per_sec
= 0;
383 assert(sf
->movedata
);
386 warnx(_("failed to read new partition from device; ignoring --move-data"));
387 else if (!fdisk_partition_has_size(pa
))
388 warnx(_("failed to get size of the new partition; ignoring --move-data"));
389 else if (!fdisk_partition_has_start(pa
))
390 warnx(_("failed to get start of the new partition; ignoring --move-data"));
391 else if (!fdisk_partition_has_size(orig_pa
))
392 warnx(_("failed to get size of the old partition; ignoring --move-data"));
393 else if (!fdisk_partition_has_start(orig_pa
))
394 warnx(_("failed to get start of the old partition; ignoring --move-data"));
395 else if (fdisk_partition_get_start(pa
) == fdisk_partition_get_start(orig_pa
))
396 warnx(_("start of the partition has not been moved; ignoring --move-data"));
397 else if (fdisk_partition_get_size(orig_pa
) < fdisk_partition_get_size(pa
))
398 warnx(_("new partition is smaller than original; ignoring --move-data"));
404 DBG(MISC
, ul_debug("moving data"));
406 fd
= fdisk_get_devfd(sf
->cxt
);
408 /* set move direction and overlay */
409 nsectors
= fdisk_partition_get_size(orig_pa
);
410 from
= fdisk_partition_get_start(orig_pa
);
411 to
= fdisk_partition_get_start(pa
);
414 if ((to
>= from
&& from
+ nsectors
>= to
) ||
415 (from
>= to
&& to
+ nsectors
>= from
)) {
416 /* source and target overlay, check if we need to copy
417 * backwardly from end of the source */
418 DBG(MISC
, ul_debug("overlay between source and target"));
419 backward
= from
< to
;
420 DBG(MISC
, ul_debug(" copy order: %s", backward
? "backward" : "forward"));
423 /* set optimal step size -- nearest to 1MiB aligned to optimal I/O */
424 io
= fdisk_get_optimal_iosize(sf
->cxt
);
425 ss
= fdisk_get_sector_size(sf
->cxt
);
428 if (io
< 1024 * 1024)
429 step_bytes
= ((1024 * 1024) + io
/2) / io
* io
;
433 step
= step_bytes
/ ss
;
434 nbytes
= nsectors
* ss
;
436 DBG(MISC
, ul_debug(" step: %ju (%zu bytes)", (uintmax_t)step
, step_bytes
));
438 #if defined(POSIX_FADV_SEQUENTIAL) && defined(HAVE_POSIX_FADVISE)
440 posix_fadvise(fd
, from
* ss
, nsectors
* ss
, POSIX_FADV_SEQUENTIAL
);
442 devname
= fdisk_partname(fdisk_get_devname(sf
->cxt
), partno
+1);
443 if (sf
->move_typescript
)
444 typescript
= mk_backup_filename_tpl(sf
->move_typescript
, devname
, ".move");
447 fdisk_info(sf
->cxt
,"");
448 color_scheme_enable("header", UL_COLOR_BOLD
);
449 fdisk_info(sf
->cxt
, sf
->noact
? _("Data move: (--no-act)") : _("Data move:"));
452 fdisk_info(sf
->cxt
, _(" typescript file: %s"), typescript
);
453 printf(_(" start sector: (from/to) %ju / %ju\n"), (uintmax_t) from
, (uintmax_t) to
);
454 printf(_(" sectors: %ju\n"), (uintmax_t) nsectors
);
455 printf(_(" step size: %zu bytes\n"), step_bytes
);
459 if (isatty(fileno(stdout
)))
463 if (sf
->interactive
) {
465 fdisk_ask_yesno(sf
->cxt
, _("Do you want to move partition data?"), &yes
);
467 fdisk_info(sf
->cxt
, _("Leaving."));
473 f
= fopen(typescript
, "w");
475 fdisk_warn(sf
->cxt
, _("cannot open %s"), typescript
);
479 /* don't translate */
480 fprintf(f
, "# sfdisk: " PACKAGE_STRING
"\n");
481 fprintf(f
, "# Disk: %s\n", devname
);
482 fprintf(f
, "# Partition: %zu\n", partno
+ 1);
483 fprintf(f
, "# Operation: move data\n");
484 fprintf(f
, "# Sector size: %zu\n", ss
);
485 fprintf(f
, "# Original start offset (sectors/bytes): %ju/%ju\n",
486 (uintmax_t)from
, (uintmax_t)from
* ss
);
487 fprintf(f
, "# New start offset (sectors/bytes): %ju/%ju\n",
488 (uintmax_t)to
, (uintmax_t)to
* ss
);
489 fprintf(f
, "# Area size (sectors/bytes): %ju/%ju\n",
490 (uintmax_t)nsectors
, (uintmax_t)nsectors
* ss
);
491 fprintf(f
, "# Step size (sectors/bytes): %zu/%zu\n", step
, step_bytes
);
492 fprintf(f
, "# Steps: %ju\n", ((uintmax_t) nsectors
/ step
) + 1);
494 fprintf(f
, "# <step>: <from> <to> (step offsets in bytes)\n");
497 src
= (backward
? from
+ nsectors
: from
) * ss
;
498 dst
= (backward
? to
+ nsectors
: to
) * ss
;
499 buf
= xmalloc(step_bytes
);
501 DBG(MISC
, ul_debug(" initial: src=%ju dst=%ju", src
, dst
));
503 gettimeofday(&prev_time
, NULL
);
506 for (cc
= 1, i
= 0; i
< nsectors
&& nbytes
> 0; i
+= step
, cc
++) {
510 src
-= step_bytes
, dst
-= step_bytes
;
512 DBG(MISC
, ul_debug("#%05zu: src=%ju dst=%ju", cc
, src
, dst
));
514 if (nbytes
< step_bytes
) {
515 DBG(MISC
, ul_debug(" aligning step from %ju to %ju",
516 step_bytes
, nbytes
));
519 nbytes
-= step_bytes
;
523 if (lseek(fd
, src
, SEEK_SET
) == (off_t
) -1)
525 rc
= read(fd
, buf
, step_bytes
);
526 if (rc
< 0 || rc
!= (ssize_t
) step_bytes
)
530 if (lseek(fd
, dst
, SEEK_SET
) == (off_t
) -1)
532 rc
= write(fd
, buf
, step_bytes
);
533 if (rc
< 0 || rc
!= (ssize_t
) step_bytes
)
541 fprintf(f
, "%05zu: %12ju %12ju\n", cc
, src
, dst
);
543 if (progress
&& i
% 10 == 0) {
544 unsigned int elapsed
= 0; /* usec */
545 struct timeval cur_time
;
547 gettimeofday(&cur_time
, NULL
);
548 if (cur_time
.tv_sec
- prev_time
.tv_sec
> 1) {
549 elapsed
= ((cur_time
.tv_sec
- prev_time
.tv_sec
) * 1000000) +
550 (cur_time
.tv_usec
- prev_time
.tv_usec
);
552 bytes_per_sec
= ((i
- prev
) * ss
) / elapsed
; /* per usec */
553 bytes_per_sec
*= 1000000; /* per sec */
555 prev_time
= cur_time
;
560 fprintf(stdout
, _("Moved %ju from %ju sectors (%.3f%%, %.1f MiB/s)."),
562 100.0 / ((double) nsectors
/(i
+1)),
563 (double) (bytes_per_sec
/ (1024 * 1024)));
565 fprintf(stdout
, _("Moved %ju from %ju sectors (%.3f%%)."),
567 100.0 / ((double) nsectors
/(i
+1)));
574 src
+= step_bytes
, dst
+= step_bytes
;
578 int x
= get_terminal_width(80);
583 fprintf(stdout
, _("Moved %ju from %ju sectors (%.0f%%)."),
585 100.0 / ((double) nsectors
/(i
+1)));
595 fdisk_info(sf
->cxt
, _("Your data has not been moved (--no-act)."));
600 warn(_("%s: failed to move data"), devname
);
610 static int write_changes(struct sfdisk
*sf
)
615 fdisk_info(sf
->cxt
, _("The partition table is unchanged (--no-act)."));
617 rc
= fdisk_write_disklabel(sf
->cxt
);
619 if (rc
== 0 && sf
->movedata
&& sf
->orig_pa
)
620 rc
= move_partition_data(sf
, sf
->partno
, sf
->orig_pa
);
622 if (!sf
->noact
&& !rc
) {
623 fdisk_info(sf
->cxt
, _("\nThe partition table has been altered."));
625 /* Let's wait a little bit. It's possible that our
626 * system is still busy with a previous re-read
627 * ioctl (on sfdisk start) or with another task
628 * related to the write to the device.
631 fdisk_reread_partition_table(sf
->cxt
);
636 rc
= fdisk_deassign_device(sf
->cxt
,
637 sf
->noact
|| sf
->notell
); /* no-sync */
642 * sfdisk --list [<device ..]
644 static int command_list_partitions(struct sfdisk
*sf
, int argc
, char **argv
)
647 fdisk_enable_listonly(sf
->cxt
, 1);
652 for (i
= 0; i
< argc
; i
++) {
654 fputs("\n\n", stdout
);
655 if (print_device_pt(sf
->cxt
, argv
[i
], 1, sf
->verify
) != 0)
660 print_all_devices_pt(sf
->cxt
, sf
->verify
);
666 * sfdisk --list-free [<device ..]
668 static int command_list_freespace(struct sfdisk
*sf
, int argc
, char **argv
)
671 fdisk_enable_listonly(sf
->cxt
, 1);
676 for (i
= 0; i
< argc
; i
++) {
678 fputs("\n\n", stdout
);
679 if (print_device_freespace(sf
->cxt
, argv
[i
], 1) != 0)
684 print_all_devices_freespace(sf
->cxt
);
690 * sfdisk --list-types
692 static int command_list_types(struct sfdisk
*sf
)
694 const struct fdisk_parttype
*t
;
695 struct fdisk_label
*lb
;
703 name
= sf
->label
? sf
->label
: "dos";
704 lb
= fdisk_get_label(sf
->cxt
, name
);
706 errx(EXIT_FAILURE
, _("unsupported label '%s'"), name
);
708 codes
= fdisk_label_has_code_parttypes(lb
);
709 fputs(_("Id Name\n\n"), stdout
);
711 while ((t
= fdisk_label_get_parttype(lb
, i
++))) {
713 printf("%2x %s\n", fdisk_parttype_get_code(t
),
714 fdisk_parttype_get_name(t
));
716 printf("%s %s\n", fdisk_parttype_get_string(t
),
717 fdisk_parttype_get_name(t
));
723 static int verify_device(struct sfdisk
*sf
, const char *devname
)
727 fdisk_enable_listonly(sf
->cxt
, 1);
729 if (fdisk_assign_device(sf
->cxt
, devname
, 1)) {
730 warn(_("cannot open %s"), devname
);
734 color_scheme_enable("header", UL_COLOR_BOLD
);
735 fdisk_info(sf
->cxt
, "%s:", devname
);
738 if (!fdisk_has_label(sf
->cxt
))
739 fdisk_info(sf
->cxt
, _("unrecognized partition table type"));
741 rc
= fdisk_verify_disklabel(sf
->cxt
);
743 fdisk_deassign_device(sf
->cxt
, 1);
748 * sfdisk --verify [<device ..]
750 static int command_verify(struct sfdisk
*sf
, int argc
, char **argv
)
752 int nfails
= 0, ct
= 0;
756 for (i
= 0; i
< argc
; i
++) {
758 fdisk_info(sf
->cxt
, " ");
759 if (verify_device(sf
, argv
[i
]) < 0)
766 while ((dev
= next_proc_partition(&f
))) {
768 fdisk_info(sf
->cxt
, " ");
769 if (verify_device(sf
, dev
) < 0)
779 static int get_size(const char *dev
, int silent
, uintmax_t *sz
)
783 fd
= open(dev
, O_RDONLY
);
786 warn(_("cannot open %s"), dev
);
790 if (blkdev_get_sectors(fd
, (unsigned long long *) sz
) == -1) {
792 warn(_("Cannot get size of %s"), dev
);
801 * sfdisk --show-size [<device ..]
803 * (silly, but just for backward compatibility)
805 static int command_show_size(struct sfdisk
*sf
__attribute__((__unused__
)),
806 int argc
, char **argv
)
812 for (i
= 0; i
< argc
; i
++) {
813 if (get_size(argv
[i
], 0, &sz
) == 0)
814 printf("%ju\n", sz
/ 2);
821 while ((dev
= next_proc_partition(&f
))) {
822 if (get_size(dev
, 1, &sz
) == 0) {
823 printf("%s: %9ju\n", dev
, sz
/ 2);
829 printf(_("total: %ju blocks\n"), total
);
835 static int print_geom(struct sfdisk
*sf
, const char *devname
)
837 fdisk_enable_listonly(sf
->cxt
, 1);
839 if (fdisk_assign_device(sf
->cxt
, devname
, 1)) {
840 warn(_("cannot open %s"), devname
);
844 fdisk_info(sf
->cxt
, "%s: %ju cylinders, %ju heads, %ju sectors/track",
846 (uintmax_t) fdisk_get_geom_cylinders(sf
->cxt
),
847 (uintmax_t) fdisk_get_geom_heads(sf
->cxt
),
848 (uintmax_t) fdisk_get_geom_sectors(sf
->cxt
));
850 fdisk_deassign_device(sf
->cxt
, 1);
855 * sfdisk --show-geometry [<device ..]
857 static int command_show_geometry(struct sfdisk
*sf
, int argc
, char **argv
)
863 for (i
= 0; i
< argc
; i
++) {
864 if (print_geom(sf
, argv
[i
]) < 0)
871 while ((dev
= next_proc_partition(&f
))) {
872 if (print_geom(sf
, dev
) < 0)
882 * sfdisk --activate <device> [<partno> ...]
884 static int command_activate(struct sfdisk
*sf
, int argc
, char **argv
)
886 int rc
, nparts
, i
, listonly
;
887 struct fdisk_partition
*pa
= NULL
;
888 const char *devname
= NULL
;
891 errx(EXIT_FAILURE
, _("no disk device specified"));
894 /* --activate <device> */
895 listonly
= argc
== 1;
897 rc
= fdisk_assign_device(sf
->cxt
, devname
, listonly
);
899 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
901 if (fdisk_is_label(sf
->cxt
, GPT
)) {
902 if (fdisk_gpt_is_hybrid(sf
->cxt
))
903 errx(EXIT_FAILURE
, _("toggle boot flags is unsupported for Hybrid GPT/MBR"));
905 /* Switch from GPT to PMBR */
906 sf
->cxt
= fdisk_new_nested_context(sf
->cxt
, "dos");
908 err(EXIT_FAILURE
, _("cannot switch to PMBR"));
909 fdisk_info(sf
->cxt
, _("Activation is unsupported for GPT -- entering nested PMBR."));
911 } else if (!fdisk_is_label(sf
->cxt
, DOS
))
912 errx(EXIT_FAILURE
, _("toggle boot flags is supported for MBR or PMBR only"));
914 if (!listonly
&& sf
->backup
)
915 backup_partition_table(sf
, devname
);
917 nparts
= fdisk_get_npartitions(sf
->cxt
);
918 for (i
= 0; i
< nparts
; i
++) {
921 /* note that fdisk_get_partition() reuses the @pa pointer, you
922 * don't have to (re)allocate it */
923 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0)
926 /* sfdisk --activate list bootable partitions */
928 if (!fdisk_partition_is_bootable(pa
))
930 if (fdisk_partition_to_string(pa
, sf
->cxt
,
931 FDISK_FIELD_DEVICE
, &data
) == 0) {
932 printf("%s\n", data
);
936 /* deactivate all active partitions */
937 } else if (fdisk_partition_is_bootable(pa
))
938 fdisk_toggle_partition_flag(sf
->cxt
, i
, DOS_FLAG_ACTIVE
);
941 /* sfdisk --activate <partno> [..] */
942 for (i
= 1; i
< argc
; i
++) {
945 if (i
== 1 && strcmp(argv
[1], "-") == 0)
947 n
= strtou32_or_err(argv
[i
], _("failed to parse partition number"));
949 rc
= fdisk_toggle_partition_flag(sf
->cxt
, n
- 1, DOS_FLAG_ACTIVE
);
952 _("%s: partition %d: failed to toggle bootable flag"),
956 fdisk_unref_partition(pa
);
959 rc
= fdisk_deassign_device(sf
->cxt
, 1);
961 rc
= write_changes(sf
);
966 * sfdisk --delete <device> [<partno> ...]
968 static int command_delete(struct sfdisk
*sf
, int argc
, char **argv
)
971 const char *devname
= NULL
;
974 errx(EXIT_FAILURE
, _("no disk device specified"));
977 if (fdisk_assign_device(sf
->cxt
, devname
, 0) != 0)
978 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
981 backup_partition_table(sf
, devname
);
985 size_t nparts
= fdisk_get_npartitions(sf
->cxt
);
986 for (i
= 0; i
< nparts
; i
++) {
987 if (fdisk_is_partition_used(sf
->cxt
, i
) &&
988 fdisk_delete_partition(sf
->cxt
, i
) != 0)
989 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to delete"), devname
, i
+ 1);
991 /* delete specified */
993 for (i
= 1; i
< (size_t) argc
; i
++) {
994 size_t n
= strtou32_or_err(argv
[i
], _("failed to parse partition number"));
996 if (fdisk_delete_partition(sf
->cxt
, n
- 1) != 0)
997 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to delete"), devname
, n
);
1001 return write_changes(sf
);
1005 * sfdisk --reorder <device>
1007 static int command_reorder(struct sfdisk
*sf
, int argc
, char **argv
)
1009 const char *devname
= NULL
;
1015 errx(EXIT_FAILURE
, _("no disk device specified"));
1017 rc
= fdisk_assign_device(sf
->cxt
, devname
, 0); /* read-write */
1019 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1022 backup_partition_table(sf
, devname
);
1024 if (fdisk_reorder_partitions(sf
->cxt
) == 1) /* unchanged */
1025 rc
= fdisk_deassign_device(sf
->cxt
, 1);
1027 rc
= write_changes(sf
);
1034 * sfdisk --dump <device>
1036 static int command_dump(struct sfdisk
*sf
, int argc
, char **argv
)
1038 const char *devname
= NULL
;
1039 struct fdisk_script
*dp
;
1045 errx(EXIT_FAILURE
, _("no disk device specified"));
1047 rc
= fdisk_assign_device(sf
->cxt
, devname
, 1); /* read-only */
1049 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1051 if (!fdisk_has_label(sf
->cxt
))
1052 errx(EXIT_FAILURE
, _("%s: does not contain a recognized partition table"), devname
);
1054 dp
= fdisk_new_script(sf
->cxt
);
1056 err(EXIT_FAILURE
, _("failed to allocate dump struct"));
1058 rc
= fdisk_script_read_context(dp
, NULL
);
1060 errx(EXIT_FAILURE
, _("%s: failed to dump partition table"), devname
);
1063 fdisk_script_enable_json(dp
, 1);
1064 fdisk_script_write_file(dp
, stdout
);
1066 fdisk_unref_script(dp
);
1067 fdisk_deassign_device(sf
->cxt
, 1); /* no-sync() */
1071 static void assign_device_partition(struct sfdisk
*sf
,
1072 const char *devname
,
1078 struct fdisk_label
*lb
= NULL
;
1083 /* read-only when a new <type> undefined */
1084 rc
= fdisk_assign_device(sf
->cxt
, devname
, rdonly
);
1086 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1088 lb
= fdisk_get_label(sf
->cxt
, NULL
);
1090 errx(EXIT_FAILURE
, _("%s: no partition table found"), devname
);
1092 n
= fdisk_get_npartitions(sf
->cxt
);
1094 errx(EXIT_FAILURE
, _("%s: partition %zu: partition table contains "
1095 "only %zu partitions"), devname
, partno
, n
);
1096 if (!fdisk_is_partition_used(sf
->cxt
, partno
- 1))
1097 errx(EXIT_FAILURE
, _("%s: partition %zu: partition is unused"),
1102 * sfdisk --part-type <device> <partno> [<type>]
1104 static int command_parttype(struct sfdisk
*sf
, int argc
, char **argv
)
1107 struct fdisk_parttype
*type
= NULL
;
1108 struct fdisk_label
*lb
;
1109 const char *devname
= NULL
, *typestr
= NULL
;
1112 errx(EXIT_FAILURE
, _("no disk device specified"));
1116 errx(EXIT_FAILURE
, _("no partition number specified"));
1117 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1122 errx(EXIT_FAILURE
, _("unexpected arguments"));
1124 /* read-only when a new <type> undefined */
1125 assign_device_partition(sf
, devname
, partno
, !typestr
);
1127 lb
= fdisk_get_label(sf
->cxt
, NULL
);
1129 /* print partition type */
1131 const struct fdisk_parttype
*t
= NULL
;
1132 struct fdisk_partition
*pa
= NULL
;
1134 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1135 t
= fdisk_partition_get_type(pa
);
1137 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition type"),
1140 if (fdisk_label_has_code_parttypes(lb
))
1141 printf("%2x\n", fdisk_parttype_get_code(t
));
1143 printf("%s\n", fdisk_parttype_get_string(t
));
1145 fdisk_unref_partition(pa
);
1146 fdisk_deassign_device(sf
->cxt
, 1);
1151 backup_partition_table(sf
, devname
);
1153 /* parse <type> and apply to PT */
1154 type
= fdisk_label_parse_parttype(lb
, typestr
);
1156 errx(EXIT_FAILURE
, _("failed to parse %s partition type '%s'"),
1157 fdisk_label_get_name(lb
), typestr
);
1159 else if (fdisk_set_partition_type(sf
->cxt
, partno
- 1, type
) != 0)
1160 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition type"),
1162 fdisk_unref_parttype(type
);
1163 return write_changes(sf
);
1167 * sfdisk --part-uuid <device> <partno> [<uuid>]
1169 static int command_partuuid(struct sfdisk
*sf
, int argc
, char **argv
)
1172 struct fdisk_partition
*pa
= NULL
;
1173 const char *devname
= NULL
, *uuid
= NULL
;
1176 errx(EXIT_FAILURE
, _("no disk device specified"));
1180 errx(EXIT_FAILURE
, _("no partition number specified"));
1181 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1186 errx(EXIT_FAILURE
, _("unexpected arguments"));
1188 /* read-only if uuid not given */
1189 assign_device_partition(sf
, devname
, partno
, !uuid
);
1191 /* print partition uuid */
1193 const char *str
= NULL
;
1195 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1196 str
= fdisk_partition_get_uuid(pa
);
1198 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition UUID"),
1200 printf("%s\n", str
);
1201 fdisk_unref_partition(pa
);
1202 fdisk_deassign_device(sf
->cxt
, 1);
1207 backup_partition_table(sf
, devname
);
1209 pa
= fdisk_new_partition();
1211 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1213 if (fdisk_partition_set_uuid(pa
, uuid
) != 0 ||
1214 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1215 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition UUID"),
1217 fdisk_unref_partition(pa
);
1218 return write_changes(sf
);
1222 * sfdisk --part-label <device> <partno> [<label>]
1224 static int command_partlabel(struct sfdisk
*sf
, int argc
, char **argv
)
1227 struct fdisk_partition
*pa
= NULL
;
1228 const char *devname
= NULL
, *name
= NULL
;
1231 errx(EXIT_FAILURE
, _("no disk device specified"));
1235 errx(EXIT_FAILURE
, _("no partition number specified"));
1236 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1241 errx(EXIT_FAILURE
, _("unexpected arguments"));
1243 /* read-only if name not given */
1244 assign_device_partition(sf
, devname
, partno
, !name
);
1246 /* print partition name */
1248 const char *str
= NULL
;
1250 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1251 str
= fdisk_partition_get_name(pa
);
1253 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to get partition name"),
1255 printf("%s\n", str
);
1256 fdisk_unref_partition(pa
);
1257 fdisk_deassign_device(sf
->cxt
, 1);
1262 backup_partition_table(sf
, devname
);
1264 pa
= fdisk_new_partition();
1266 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1268 if (fdisk_partition_set_name(pa
, name
) != 0 ||
1269 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1270 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition name"),
1273 fdisk_unref_partition(pa
);
1274 return write_changes(sf
);
1278 * sfdisk --part-attrs <device> <partno> [<attrs>]
1280 static int command_partattrs(struct sfdisk
*sf
, int argc
, char **argv
)
1283 struct fdisk_partition
*pa
= NULL
;
1284 const char *devname
= NULL
, *attrs
= NULL
;
1287 errx(EXIT_FAILURE
, _("no disk device specified"));
1291 errx(EXIT_FAILURE
, _("no partition number specified"));
1292 partno
= strtou32_or_err(argv
[1], _("failed to parse partition number"));
1297 errx(EXIT_FAILURE
, _("unexpected arguments"));
1299 /* read-only if name not given */
1300 assign_device_partition(sf
, devname
, partno
, !attrs
);
1302 /* print partition name */
1304 const char *str
= NULL
;
1306 if (fdisk_get_partition(sf
->cxt
, partno
- 1, &pa
) == 0)
1307 str
= fdisk_partition_get_attrs(pa
);
1309 printf("%s\n", str
);
1310 fdisk_unref_partition(pa
);
1311 fdisk_deassign_device(sf
->cxt
, 1);
1316 backup_partition_table(sf
, devname
);
1318 pa
= fdisk_new_partition();
1320 err(EXIT_FAILURE
, _("failed to allocate partition object"));
1322 if (fdisk_partition_set_attrs(pa
, attrs
) != 0 ||
1323 fdisk_set_partition(sf
->cxt
, partno
- 1, pa
) != 0)
1324 errx(EXIT_FAILURE
, _("%s: partition %zu: failed to set partition attributes"),
1327 fdisk_unref_partition(pa
);
1328 return write_changes(sf
);
1332 * sfdisk --disk-id <device> [<str>]
1334 static int command_diskid(struct sfdisk
*sf
, int argc
, char **argv
)
1336 const char *devname
= NULL
;
1340 errx(EXIT_FAILURE
, _("no disk device specified"));
1346 errx(EXIT_FAILURE
, _("unexpected arguments"));
1348 if (fdisk_assign_device(sf
->cxt
, devname
, !str
) != 0)
1349 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1353 fdisk_get_disklabel_id(sf
->cxt
, &str
);
1355 printf("%s\n", str
);
1357 fdisk_deassign_device(sf
->cxt
, 1);
1363 backup_partition_table(sf
, devname
);
1365 if (fdisk_set_disklabel_id_from_string(sf
->cxt
, str
) != 0)
1366 errx(EXIT_FAILURE
, _("%s: failed to set disklabel ID"), devname
);
1368 return write_changes(sf
);
1371 static void sfdisk_print_partition(struct sfdisk
*sf
, size_t n
)
1373 struct fdisk_partition
*pa
= NULL
;
1380 if (fdisk_get_partition(sf
->cxt
, n
, &pa
) != 0)
1383 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_DEVICE
, &data
);
1384 printf("%12s : ", data
);
1386 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_START
, &data
);
1387 printf("%12s ", data
);
1389 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_END
, &data
);
1390 printf("%12s ", data
);
1392 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_SIZE
, &data
);
1393 printf("(%s) ", data
);
1395 fdisk_partition_to_string(pa
, sf
->cxt
, FDISK_FIELD_TYPE
, &data
);
1396 printf("%s\n", data
);
1398 fdisk_unref_partition(pa
);
1401 static void command_fdisk_help(void)
1403 fputs(_("\nHelp:\n"), stdout
);
1405 fputc('\n', stdout
);
1406 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1407 fputs(_(" Commands:\n"), stdout
);
1409 fputs(_(" write write table to disk and exit\n"), stdout
);
1410 fputs(_(" quit show new situation and wait for user's feedback before write\n"), stdout
);
1411 fputs(_(" abort exit sfdisk shell\n"), stdout
);
1412 fputs(_(" print display the partition table\n"), stdout
);
1413 fputs(_(" help show this help text\n"), stdout
);
1414 fputc('\n', stdout
);
1415 fputs(_(" Ctrl-D the same as 'quit'\n"), stdout
);
1417 fputc('\n', stdout
);
1418 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1419 fputs(_(" Input format:\n"), stdout
);
1421 fputs(_(" <start>, <size>, <type>, <bootable>\n"), stdout
);
1423 fputc('\n', stdout
);
1424 fputs(_(" <start> Beginning of the partition in sectors, or bytes if\n"
1425 " specified in the format <number>{K,M,G,T,P,E,Z,Y}.\n"
1426 " The default is the first free space.\n"), stdout
);
1428 fputc('\n', stdout
);
1429 fputs(_(" <size> Size of the partition in sectors, or bytes if\n"
1430 " specified in the format <number>{K,M,G,T,P,E,Z,Y}.\n"
1431 " The default is all available space.\n"), stdout
);
1433 fputc('\n', stdout
);
1434 fputs(_(" <type> The partition type. Default is a Linux data partition.\n"), stdout
);
1435 fputs(_(" MBR: hex or L,S,E,X,U,R,V shortcuts.\n"), stdout
);
1436 fputs(_(" GPT: UUID or L,S,H,U,R,V shortcuts.\n"), stdout
);
1438 fputc('\n', stdout
);
1439 fputs(_(" <bootable> Use '*' to mark an MBR partition as bootable.\n"), stdout
);
1441 fputc('\n', stdout
);
1442 color_scheme_enable("help-title", UL_COLOR_BOLD
);
1443 fputs(_(" Example:\n"), stdout
);
1445 fputs(_(" , 4G Creates a 4GiB partition at default start offset.\n"), stdout
);
1446 fputc('\n', stdout
);
1450 SFDISK_DONE_NONE
= 0,
1457 /* returns: 0 on success, <0 on error, 1 successfully stop sfdisk */
1458 static int loop_control_commands(struct sfdisk
*sf
,
1459 struct fdisk_script
*dp
,
1462 const char *p
= skip_blank(buf
);
1463 int rc
= SFDISK_DONE_NONE
;
1465 if (strcmp(p
, "print") == 0)
1466 list_disklabel(sf
->cxt
);
1467 else if (strcmp(p
, "help") == 0)
1468 command_fdisk_help();
1469 else if (strcmp(p
, "quit") == 0)
1470 rc
= SFDISK_DONE_ASK
;
1471 else if (strcmp(p
, "write") == 0)
1472 rc
= SFDISK_DONE_WRITE
;
1473 else if (strcmp(p
, "abort") == 0)
1474 rc
= SFDISK_DONE_ABORT
;
1476 if (sf
->interactive
)
1477 fdisk_warnx(sf
->cxt
, _("unsupported command"));
1479 fdisk_warnx(sf
->cxt
, _("line %d: unsupported command"),
1480 fdisk_script_get_nlines(dp
));
1487 static int has_container(struct sfdisk
*sf
)
1490 struct fdisk_partition
*pa
= NULL
;
1493 return sf
->container
;
1495 nparts
= fdisk_get_npartitions(sf
->cxt
);
1496 for (i
= 0; i
< nparts
; i
++) {
1497 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0)
1499 if (fdisk_partition_is_container(pa
)) {
1505 fdisk_unref_partition(pa
);
1506 return sf
->container
;
1509 static size_t last_pt_partno(struct sfdisk
*sf
)
1511 size_t i
, nparts
, partno
= 0;
1512 struct fdisk_partition
*pa
= NULL
;
1515 nparts
= fdisk_get_npartitions(sf
->cxt
);
1516 for (i
= 0; i
< nparts
; i
++) {
1519 if (fdisk_get_partition(sf
->cxt
, i
, &pa
) != 0 ||
1520 !fdisk_partition_is_used(pa
))
1522 x
= fdisk_partition_get_partno(pa
);
1527 fdisk_unref_partition(pa
);
1531 #ifdef HAVE_LIBREADLINE
1532 static char *sfdisk_fgets(struct fdisk_script
*dp
,
1533 char *buf
, size_t bufsz
, FILE *f
)
1535 struct sfdisk
*sf
= (struct sfdisk
*) fdisk_script_get_userdata(dp
);
1541 if (sf
->interactive
) {
1542 char *p
= readline(sf
->prompt
);
1548 if (len
> bufsz
- 2)
1551 memcpy(buf
, p
, len
);
1552 buf
[len
] = '\n'; /* append \n to be compatible with libc fgetc() */
1553 buf
[len
+ 1] = '\0';
1558 return fgets(buf
, bufsz
, f
);
1562 static int ignore_partition(struct fdisk_partition
*pa
)
1564 /* incomplete partition setting */
1565 if (!fdisk_partition_has_start(pa
) && !fdisk_partition_start_is_default(pa
))
1567 if (!fdisk_partition_has_size(pa
) && !fdisk_partition_end_is_default(pa
))
1570 /* probably dump from old sfdisk with start=0 size=0 */
1571 if (fdisk_partition_has_start(pa
) && fdisk_partition_get_start(pa
) == 0 &&
1572 fdisk_partition_has_size(pa
) && fdisk_partition_get_size(pa
) == 0)
1578 static void follow_wipe_mode(struct sfdisk
*sf
)
1580 int dowipe
= sf
->wipemode
== WIPEMODE_ALWAYS
? 1 : 0;
1582 if (sf
->interactive
&& sf
->wipemode
== WIPEMODE_AUTO
)
1583 dowipe
= 1; /* do it in interactive mode */
1585 if (fdisk_is_ptcollision(sf
->cxt
) && sf
->wipemode
!= WIPEMODE_NEVER
)
1586 dowipe
= 1; /* always wipe old PT */
1588 fdisk_enable_wipe(sf
->cxt
, dowipe
);
1593 if (!fdisk_is_ptcollision(sf
->cxt
)) {
1594 fdisk_warnx(sf
->cxt
, _(
1595 "The device contains '%s' signature and it will be removed by a write command. "
1596 "See sfdisk(8) man page and --wipe option for more details."),
1597 fdisk_get_collision(sf
->cxt
));
1598 fputc('\n', stdout
);
1601 fdisk_warnx(sf
->cxt
, _(
1602 "The device contains '%s' signature and it may remain on the device. "
1603 "It is recommended to wipe the device with wipefs(8) or "
1604 "sfdisk --wipe, in order to avoid possible collisions."),
1605 fdisk_get_collision(sf
->cxt
));
1606 fputc('\n', stderr
);
1610 static int wipe_partition(struct sfdisk
*sf
, size_t partno
)
1613 char *fstype
= NULL
;
1614 struct fdisk_partition
*tmp
= NULL
;
1616 DBG(MISC
, ul_debug("checking for signature"));
1618 rc
= fdisk_get_partition(sf
->cxt
, partno
, &tmp
);
1622 rc
= fdisk_partition_to_string(tmp
, sf
->cxt
, FDISK_FIELD_FSTYPE
, &fstype
);
1623 if (rc
|| fstype
== NULL
)
1626 fdisk_warnx(sf
->cxt
, _("Partition #%zu contains a %s signature."), partno
+ 1, fstype
);
1628 if (sf
->pwipemode
== WIPEMODE_AUTO
&& isatty(STDIN_FILENO
))
1629 fdisk_ask_yesno(sf
->cxt
, _("Do you want to remove the signature?"), &yes
);
1630 else if (sf
->pwipemode
== WIPEMODE_ALWAYS
)
1634 fdisk_info(sf
->cxt
, _("The signature will be removed by a write command."));
1635 rc
= fdisk_wipe_partition(sf
->cxt
, partno
, TRUE
);
1638 fdisk_unref_partition(tmp
);
1640 DBG(MISC
, ul_debug("partition wipe check end [rc=%d]", rc
));
1644 static void refresh_prompt_buffer(struct sfdisk
*sf
, const char *devname
,
1645 size_t next_partno
, int created
)
1648 char *partname
= fdisk_partname(devname
, next_partno
+ 1);
1650 err(EXIT_FAILURE
, _("failed to allocate partition name"));
1652 if (!sf
->prompt
|| !startswith(sf
->prompt
, partname
)) {
1654 xasprintf(&sf
->prompt
,"%s: ", partname
);
1657 } else if (!sf
->prompt
|| !startswith(sf
->prompt
, SFDISK_PROMPT
)) {
1659 sf
->prompt
= xstrdup(SFDISK_PROMPT
);
1664 * sfdisk <device> [[-N] <partno>]
1666 * Note that the option -N is there for backward compatibility only.
1668 static int command_fdisk(struct sfdisk
*sf
, int argc
, char **argv
)
1670 int rc
= 0, partno
= sf
->partno
, created
= 0, unused
= 0;
1671 struct fdisk_script
*dp
;
1672 struct fdisk_table
*tb
= NULL
;
1673 const char *devname
= NULL
, *label
;
1675 size_t next_partno
= (size_t) -1;
1679 if (partno
< 0 && argc
> 1)
1680 partno
= strtou32_or_err(argv
[1],
1681 _("failed to parse partition number"));
1683 errx(EXIT_FAILURE
, _("no disk device specified"));
1685 rc
= fdisk_assign_device(sf
->cxt
, devname
, 0);
1687 err(EXIT_FAILURE
, _("cannot open %s"), devname
);
1689 dp
= fdisk_new_script(sf
->cxt
);
1691 err(EXIT_FAILURE
, _("failed to allocate script handler"));
1692 fdisk_set_script(sf
->cxt
, dp
);
1693 #ifdef HAVE_LIBREADLINE
1694 fdisk_script_set_fgets(dp
, sfdisk_fgets
);
1696 fdisk_script_set_userdata(dp
, (void *) sf
);
1699 * Don't create a new disklabel when [-N] <partno> specified. In this
1700 * case reuse already specified disklabel. Let's check that the disk
1701 * really contains the partition.
1706 if (!fdisk_has_label(sf
->cxt
))
1707 errx(EXIT_FAILURE
, _("%s: cannot modify partition %d: "
1708 "no partition table was found"),
1709 devname
, partno
+ 1);
1710 n
= fdisk_get_npartitions(sf
->cxt
);
1711 if ((size_t) partno
> n
)
1712 errx(EXIT_FAILURE
, _("%s: cannot modify partition %d: "
1713 "partition table contains only %zu "
1715 devname
, partno
+ 1, n
);
1717 if (!fdisk_is_partition_used(sf
->cxt
, partno
)) {
1718 fdisk_warnx(sf
->cxt
, _("warning: %s: partition %d is not defined yet"),
1719 devname
, partno
+ 1);
1723 next_partno
= partno
;
1726 sf
->orig_pa
= get_partition(sf
->cxt
, partno
);
1731 next_partno
= last_pt_partno(sf
) + 1;
1734 if (!sf
->quiet
&& sf
->interactive
) {
1735 color_scheme_enable("welcome", UL_COLOR_GREEN
);
1736 fdisk_info(sf
->cxt
, _("\nWelcome to sfdisk (%s)."), PACKAGE_STRING
);
1738 fdisk_info(sf
->cxt
, _("Changes will remain in memory only, until you decide to write them.\n"
1739 "Be careful before using the write command.\n"));
1742 if (!sf
->noact
&& !sf
->noreread
) {
1744 fputs(_("Checking that no-one is using this disk right now ..."), stdout
);
1745 if (fdisk_device_is_used(sf
->cxt
)) {
1747 fputs(_(" FAILED\n\n"), stdout
);
1749 fdisk_warnx(sf
->cxt
, _(
1750 "This disk is currently in use - repartitioning is probably a bad idea.\n"
1751 "Umount all file systems, and swapoff all swap partitions on this disk.\n"
1752 "Use the --no-reread flag to suppress this check.\n"));
1755 errx(EXIT_FAILURE
, _("Use the --force flag to overrule all checks."));
1756 } else if (!sf
->quiet
)
1757 fputs(_(" OK\n\n"), stdout
);
1760 if (fdisk_get_collision(sf
->cxt
))
1761 follow_wipe_mode(sf
);
1764 backup_partition_table(sf
, devname
);
1767 list_disk_geometry(sf
->cxt
);
1768 if (fdisk_has_label(sf
->cxt
)) {
1769 fdisk_info(sf
->cxt
, _("\nOld situation:"));
1770 list_disklabel(sf
->cxt
);
1776 else if (fdisk_has_label(sf
->cxt
))
1777 label
= fdisk_label_get_name(fdisk_get_label(sf
->cxt
, NULL
));
1779 label
= "dos"; /* just for backward compatibility */
1781 if (fdisk_script_set_header(dp
, "label", label
) != 0)
1782 errx(EXIT_FAILURE
, _("failed to set script header"));
1784 if (!sf
->quiet
&& sf
->interactive
) {
1785 if (!fdisk_has_label(sf
->cxt
) && !sf
->label
)
1787 _("\nsfdisk is going to create a new '%s' disk label.\n"
1788 "Use 'label: <name>' before you define a first partition\n"
1789 "to override the default."), label
);
1790 fdisk_info(sf
->cxt
, _("\nType 'help' to get more information.\n"));
1791 } else if (!sf
->quiet
)
1792 fputc('\n', stdout
);
1794 tb
= fdisk_script_get_table(dp
);
1800 DBG(PARSE
, ul_debug("<---next-line--->"));
1801 if (next_partno
== (size_t) -1)
1802 next_partno
= fdisk_table_get_nents(tb
);
1806 && next_partno
== fdisk_get_npartitions(sf
->cxt
)
1807 && !has_container(sf
)) {
1808 fdisk_info(sf
->cxt
, _("All partitions used."));
1809 rc
= SFDISK_DONE_ASK
;
1813 refresh_prompt_buffer(sf
, devname
, next_partno
, created
);
1816 if (sf
->prompt
&& (sf
->interactive
|| !sf
->quiet
)) {
1817 #ifndef HAVE_LIBREADLINE
1818 fputs(sf
->prompt
, stdout
);
1820 if (!sf
->interactive
)
1821 fputs(sf
->prompt
, stdout
);
1825 rc
= fdisk_script_read_line(dp
, stdin
, buf
, sizeof(buf
));
1826 if (rc
== -ENOTSUP
) {
1827 buf
[sizeof(buf
) - 1] = '\0';
1828 fdisk_warnx(sf
->cxt
, _("Unknown script header '%s' -- ignore."), buf
);
1830 } else if (rc
< 0) {
1831 DBG(PARSE
, ul_debug("script parsing failed, trying sfdisk specific commands"));
1832 buf
[sizeof(buf
) - 1] = '\0';
1833 rc
= loop_control_commands(sf
, dp
, buf
);
1837 } else if (rc
== 1) {
1838 rc
= SFDISK_DONE_EOF
;
1840 fputs(_("Done.\n"), stdout
);
1844 nparts
= fdisk_table_get_nents(tb
);
1846 size_t cur_partno
= (size_t) -1;
1847 struct fdisk_partition
*pa
= fdisk_table_get_partition(tb
, nparts
- 1);
1851 if (ignore_partition(pa
)) {
1852 fdisk_info(sf
->cxt
, _("Ignoring partition."));
1856 if (!created
) { /* create a new disklabel */
1857 rc
= fdisk_apply_script_headers(sf
->cxt
, dp
);
1860 fdisk_warnx(sf
->cxt
, _(
1861 "Failed to apply script headers, "
1862 "disk label not created."));
1864 if (rc
== 0 && fdisk_get_collision(sf
->cxt
))
1865 follow_wipe_mode(sf
);
1867 if (!rc
&& partno
>= 0) { /* -N <partno>, modify partition */
1868 rc
= fdisk_set_partition(sf
->cxt
, partno
, pa
);
1869 rc
= rc
== 0 ? SFDISK_DONE_ASK
: SFDISK_DONE_ABORT
;
1871 } else if (!rc
) { /* add partition */
1872 if (!sf
->interactive
&& !sf
->quiet
&&
1873 (!sf
->prompt
|| startswith(sf
->prompt
, SFDISK_PROMPT
))) {
1874 refresh_prompt_buffer(sf
, devname
, next_partno
, created
);
1875 fputs(sf
->prompt
, stdout
);
1877 rc
= fdisk_add_partition(sf
->cxt
, pa
, &cur_partno
);
1880 fdisk_warn(sf
->cxt
, _("Failed to add #%d partition"), next_partno
+ 1);
1884 /* wipe partition on success
1886 * Note that unused=1 means -N <partno> for unused,
1887 * otherwise we wipe only newly created partitions.
1889 if (rc
== 0 && (unused
|| partno
< 0)) {
1890 rc
= wipe_partition(sf
, unused
? (size_t) partno
: cur_partno
);
1896 /* success print result */
1897 if (sf
->interactive
)
1898 sfdisk_print_partition(sf
, cur_partno
);
1899 next_partno
= cur_partno
+ 1;
1900 } else if (pa
) /* error, drop partition from script */
1901 fdisk_table_remove_partition(tb
, pa
);
1903 fdisk_info(sf
->cxt
, _("Script header accepted."));
1905 if (rc
&& !sf
->interactive
) {
1906 rc
= SFDISK_DONE_ABORT
;
1911 /* create empty disk label if label, but no partition specified */
1912 if ((rc
== SFDISK_DONE_EOF
|| rc
== SFDISK_DONE_WRITE
) && created
== 0
1913 && fdisk_script_has_force_label(dp
) == 1
1914 && fdisk_table_get_nents(tb
) == 0
1915 && fdisk_script_get_header(dp
, "label")) {
1917 int xrc
= fdisk_apply_script_headers(sf
->cxt
, dp
);
1919 fdisk_warnx(sf
->cxt
, _(
1920 "Failed to apply script headers, "
1921 "disk label not created."));
1922 rc
= SFDISK_DONE_ABORT
;
1926 if (!sf
->quiet
&& rc
!= SFDISK_DONE_ABORT
) {
1927 fdisk_info(sf
->cxt
, _("\nNew situation:"));
1928 list_disk_identifier(sf
->cxt
);
1929 list_disklabel(sf
->cxt
);
1933 case SFDISK_DONE_ASK
:
1934 case SFDISK_DONE_EOF
:
1935 if (sf
->interactive
) {
1937 fdisk_ask_yesno(sf
->cxt
, _("Do you want to write this to disk?"), &yes
);
1939 fdisk_info(sf
->cxt
, _("Leaving."));
1945 case SFDISK_DONE_WRITE
:
1946 rc
= write_changes(sf
);
1948 case SFDISK_DONE_ABORT
:
1949 default: /* rc < 0 on error */
1950 fdisk_info(sf
->cxt
, _("Leaving.\n"));
1954 fdisk_unref_script(dp
);
1958 static void __attribute__((__noreturn__
)) usage(void)
1961 fputs(USAGE_HEADER
, out
);
1964 _(" %1$s [options] <dev> [[-N] <part>]\n"
1965 " %1$s [options] <command>\n"), program_invocation_short_name
);
1967 fputs(USAGE_SEPARATOR
, out
);
1968 fputs(_("Display or manipulate a disk partition table.\n"), out
);
1970 fputs(USAGE_COMMANDS
, out
);
1971 fputs(_(" -A, --activate <dev> [<part> ...] list or set bootable (P)MBR partitions\n"), out
);
1972 fputs(_(" -d, --dump <dev> dump partition table (usable for later input)\n"), out
);
1973 fputs(_(" -J, --json <dev> dump partition table in JSON format\n"), out
);
1974 fputs(_(" -g, --show-geometry [<dev> ...] list geometry of all or specified devices\n"), out
);
1975 fputs(_(" -l, --list [<dev> ...] list partitions of each device\n"), out
);
1976 fputs(_(" -F, --list-free [<dev> ...] list unpartitioned free areas of each device\n"), out
);
1977 fputs(_(" -r, --reorder <dev> fix partitions order (by start offset)\n"), out
);
1978 fputs(_(" -s, --show-size [<dev> ...] list sizes of all or specified devices\n"), out
);
1979 fputs(_(" -T, --list-types print the recognized types (see -X)\n"), out
);
1980 fputs(_(" -V, --verify [<dev> ...] test whether partitions seem correct\n"), out
);
1981 fputs(_(" --delete <dev> [<part> ...] delete all or specified partitions\n"), out
);
1983 fputs(USAGE_SEPARATOR
, out
);
1984 fputs(_(" --part-label <dev> <part> [<str>] print or change partition label\n"), out
);
1985 fputs(_(" --part-type <dev> <part> [<type>] print or change partition type\n"), out
);
1986 fputs(_(" --part-uuid <dev> <part> [<uuid>] print or change partition uuid\n"), out
);
1987 fputs(_(" --part-attrs <dev> <part> [<str>] print or change partition attributes\n"), out
);
1989 fputs(USAGE_SEPARATOR
, out
);
1990 fputs(_(" --disk-id <dev> [<str>] print or change disk label ID (UUID)\n"), out
);
1992 fputs(USAGE_SEPARATOR
, out
);
1993 fputs(_(" <dev> device (usually disk) path\n"), out
);
1994 fputs(_(" <part> partition number\n"), out
);
1995 fputs(_(" <type> partition type, GUID for GPT, hex for MBR\n"), out
);
1997 fputs(USAGE_OPTIONS
, out
);
1998 fputs(_(" -a, --append append partitions to existing partition table\n"), out
);
1999 fputs(_(" -b, --backup backup partition table sectors (see -O)\n"), out
);
2000 fputs(_(" --bytes print SIZE in bytes rather than in human readable format\n"), out
);
2001 fputs(_(" --move-data[=<typescript>] move partition data after relocation (requires -N)\n"), out
);
2002 fputs(_(" --move-use-fsync use fsync after each write when move data\n"), out
);
2003 fputs(_(" -f, --force disable all consistency checking\n"), out
);
2005 _(" --color[=<when>] colorize output (%s, %s or %s)\n"), "auto", "always", "never");
2007 " %s\n", USAGE_COLORS_DEFAULT
);
2008 fputs(_(" -N, --partno <num> specify partition number\n"), out
);
2009 fputs(_(" -n, --no-act do everything except write to device\n"), out
);
2010 fputs(_(" --no-reread do not check whether the device is in use\n"), out
);
2011 fputs(_(" --no-tell-kernel do not tell kernel about changes\n"), out
);
2012 fputs(_(" -O, --backup-file <path> override default backup file name\n"), out
);
2013 fputs(_(" -o, --output <list> output columns\n"), out
);
2014 fputs(_(" -q, --quiet suppress extra info messages\n"), out
);
2016 _(" -w, --wipe <mode> wipe signatures (%s, %s or %s)\n"), "auto", "always", "never");
2018 _(" -W, --wipe-partitions <mode> wipe signatures from new partitions (%s, %s or %s)\n"), "auto", "always", "never");
2019 fputs(_(" -X, --label <name> specify label type (dos, gpt, ...)\n"), out
);
2020 fputs(_(" -Y, --label-nested <name> specify nested label type (dos, bsd)\n"), out
);
2021 fputs(USAGE_SEPARATOR
, out
);
2022 fputs(_(" -G, --show-pt-geometry deprecated, alias to --show-geometry\n"), out
);
2023 fputs(_(" -L, --Linux deprecated, only for backward compatibility\n"), out
);
2024 fputs(_(" -u, --unit S deprecated, only sector unit is supported\n"), out
);
2026 fputs(USAGE_SEPARATOR
, out
);
2027 printf( " -h, --help %s\n", USAGE_OPTSTR_HELP
);
2028 printf( " -v, --version %s\n", USAGE_OPTSTR_VERSION
);
2030 list_available_columns(out
);
2032 printf(USAGE_MAN_TAIL("sfdisk(8)"));
2037 int main(int argc
, char *argv
[])
2039 const char *outarg
= NULL
;
2040 int rc
= -EINVAL
, c
, longidx
= -1, bytes
= 0;
2041 int colormode
= UL_COLORMODE_UNDEF
;
2042 struct sfdisk _sf
= {
2044 .wipemode
= WIPEMODE_AUTO
,
2045 .pwipemode
= WIPEMODE_AUTO
,
2046 .interactive
= isatty(STDIN_FILENO
) ? 1 : 0,
2050 OPT_CHANGE_ID
= CHAR_MAX
+ 1,
2067 static const struct option longopts
[] = {
2068 { "activate",no_argument
, NULL
, 'A' },
2069 { "append", no_argument
, NULL
, 'a' },
2070 { "backup", no_argument
, NULL
, 'b' },
2071 { "backup-file", required_argument
, NULL
, 'O' },
2072 { "bytes", no_argument
, NULL
, OPT_BYTES
},
2073 { "color", optional_argument
, NULL
, OPT_COLOR
},
2074 { "delete", no_argument
, NULL
, OPT_DELETE
},
2075 { "dump", no_argument
, NULL
, 'd' },
2076 { "help", no_argument
, NULL
, 'h' },
2077 { "force", no_argument
, NULL
, 'f' },
2078 { "json", no_argument
, NULL
, 'J' },
2079 { "label", required_argument
, NULL
, 'X' },
2080 { "label-nested", required_argument
, NULL
, 'Y' },
2081 { "list", no_argument
, NULL
, 'l' },
2082 { "list-free", no_argument
, NULL
, 'F' },
2083 { "list-types", no_argument
, NULL
, 'T' },
2084 { "no-act", no_argument
, NULL
, 'n' },
2085 { "no-reread", no_argument
, NULL
, OPT_NOREREAD
},
2086 { "no-tell-kernel", no_argument
, NULL
, OPT_NOTELL
},
2087 { "move-data", optional_argument
, NULL
, OPT_MOVEDATA
},
2088 { "move-use-fsync", no_argument
, NULL
, OPT_MOVEFSYNC
},
2089 { "output", required_argument
, NULL
, 'o' },
2090 { "partno", required_argument
, NULL
, 'N' },
2091 { "reorder", no_argument
, NULL
, 'r' },
2092 { "show-geometry", no_argument
, NULL
, 'g' },
2093 { "quiet", no_argument
, NULL
, 'q' },
2094 { "verify", no_argument
, NULL
, 'V' },
2095 { "version", no_argument
, NULL
, 'v' },
2096 { "wipe", required_argument
, NULL
, 'w' },
2097 { "wipe-partitions", required_argument
, NULL
, 'W' },
2099 { "part-uuid", no_argument
, NULL
, OPT_PARTUUID
},
2100 { "part-label", no_argument
, NULL
, OPT_PARTLABEL
},
2101 { "part-type", no_argument
, NULL
, OPT_PARTTYPE
},
2102 { "part-attrs", no_argument
, NULL
, OPT_PARTATTRS
},
2104 { "disk-id", no_argument
, NULL
, OPT_DISKID
},
2106 { "show-pt-geometry", no_argument
, NULL
, 'G' }, /* deprecated */
2107 { "unit", required_argument
, NULL
, 'u' }, /* deprecated */
2108 { "Linux", no_argument
, NULL
, 'L' }, /* deprecated */
2109 { "show-size", no_argument
, NULL
, 's' }, /* deprecated */
2111 { "change-id",no_argument
, NULL
, OPT_CHANGE_ID
}, /* deprecated */
2112 { "id", no_argument
, NULL
, 'c' }, /* deprecated */
2113 { "print-id",no_argument
, NULL
, OPT_PRINT_ID
}, /* deprecated */
2115 { NULL
, 0, NULL
, 0 },
2117 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
2118 { 'F','J','d'}, /* --list-free --json --dump */
2119 { 's','u'}, /* --show-size --unit */
2122 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
2125 setlocale(LC_ALL
, "");
2126 bindtextdomain(PACKAGE
, LOCALEDIR
);
2127 textdomain(PACKAGE
);
2128 close_stdout_atexit();
2130 while ((c
= getopt_long(argc
, argv
, "aAbcdfFgGhJlLo:O:nN:qrsTu:vVX:Y:w:W:",
2131 longopts
, &longidx
)) != -1) {
2133 err_exclusive_options(c
, longopts
, excl
, excl_st
);
2137 sf
->act
= ACT_ACTIVATE
;
2148 warnx(_("%s is deprecated in favour of --part-type"),
2149 longopts
[longidx
].name
);
2150 sf
->act
= ACT_PARTTYPE
;
2153 warnx(_("--id is deprecated in favour of --part-type"));
2154 sf
->act
= ACT_PARTTYPE
;
2163 sf
->act
= ACT_LIST_FREE
;
2169 warnx(_("--show-pt-geometry is no more implemented. Using --show-geometry."));
2172 sf
->act
= ACT_SHOW_GEOM
;
2181 warnx(_("--Linux option is unnecessary and deprecated"));
2188 sf
->backup_file
= optarg
;
2194 sf
->partno
= strtou32_or_err(optarg
, _("failed to parse partition number")) - 1;
2200 sf
->act
= ACT_REORDER
;
2203 sf
->act
= ACT_SHOW_SIZE
;
2206 sf
->act
= ACT_LIST_TYPES
;
2210 errx(EXIT_FAILURE
, _("unsupported unit '%c'"), *optarg
);
2213 print_version(EXIT_SUCCESS
);
2218 sf
->wipemode
= wipemode_from_string(optarg
);
2219 if (sf
->wipemode
< 0)
2220 errx(EXIT_FAILURE
, _("unsupported wipe mode"));
2223 sf
->pwipemode
= wipemode_from_string(optarg
);
2224 if (sf
->pwipemode
< 0)
2225 errx(EXIT_FAILURE
, _("unsupported wipe mode"));
2231 sf
->label_nested
= optarg
;
2235 sf
->act
= ACT_PARTUUID
;
2238 sf
->act
= ACT_PARTTYPE
;
2241 sf
->act
= ACT_PARTLABEL
;
2244 sf
->act
= ACT_PARTATTRS
;
2247 sf
->act
= ACT_DISKID
;
2256 colormode
= UL_COLORMODE_AUTO
;
2258 colormode
= colormode_or_err(optarg
,
2259 _("unsupported color mode"));
2263 sf
->move_typescript
= optarg
;
2269 sf
->act
= ACT_DELETE
;
2275 errtryhelp(EXIT_FAILURE
);
2279 colors_init(colormode
, "sfdisk");
2283 fdisk_set_size_unit(sf
->cxt
, FDISK_SIZEUNIT_BYTES
);
2286 init_fields(NULL
, outarg
, NULL
);
2288 if (sf
->verify
&& !sf
->act
)
2289 sf
->act
= ACT_VERIFY
; /* --verify make be used with --list too */
2291 sf
->act
= ACT_FDISK
; /* default */
2293 if (sf
->movedata
&& !(sf
->act
== ACT_FDISK
&& sf
->partno
>= 0))
2294 errx(EXIT_FAILURE
, _("--movedata requires -N"));
2298 rc
= command_activate(sf
, argc
- optind
, argv
+ optind
);
2302 rc
= command_delete(sf
, argc
- optind
, argv
+ optind
);
2306 rc
= command_list_partitions(sf
, argc
- optind
, argv
+ optind
);
2309 case ACT_LIST_TYPES
:
2310 rc
= command_list_types(sf
);
2314 rc
= command_list_freespace(sf
, argc
- optind
, argv
+ optind
);
2318 rc
= command_fdisk(sf
, argc
- optind
, argv
+ optind
);
2322 rc
= command_dump(sf
, argc
- optind
, argv
+ optind
);
2326 rc
= command_show_size(sf
, argc
- optind
, argv
+ optind
);
2330 rc
= command_show_geometry(sf
, argc
- optind
, argv
+ optind
);
2334 rc
= command_verify(sf
, argc
- optind
, argv
+ optind
);
2338 rc
= command_parttype(sf
, argc
- optind
, argv
+ optind
);
2342 rc
= command_partuuid(sf
, argc
- optind
, argv
+ optind
);
2346 rc
= command_partlabel(sf
, argc
- optind
, argv
+ optind
);
2350 rc
= command_partattrs(sf
, argc
- optind
, argv
+ optind
);
2354 rc
= command_diskid(sf
, argc
- optind
, argv
+ optind
);
2358 rc
= command_reorder(sf
, argc
- optind
, argv
+ optind
);
2364 DBG(MISC
, ul_debug("bye! [rc=%d]", rc
));
2365 return rc
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;