]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/fdisk_pc98/fdisk.c
Fix memory disclosure vulnerability in libalias.
[FreeBSD/FreeBSD.git] / sbin / fdisk_pc98 / fdisk.c
1 /*
2  * Mach Operating System
3  * Copyright (c) 1992 Carnegie Mellon University
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify and distribute this software and its
7  * documentation is hereby granted, provided that both the copyright
8  * notice and this permission notice appear in all copies of the
9  * software, derivative works or modified versions, and any portions
10  * thereof, and that both notices appear in supporting documentation.
11  *
12  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
13  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
14  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
15  *
16  * Carnegie Mellon requests users of this software to return to
17  *
18  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
19  *  School of Computer Science
20  *  Carnegie Mellon University
21  *  Pittsburgh PA 15213-3890
22  *
23  * any improvements or extensions that they make and grant Carnegie Mellon
24  * the rights to redistribute these changes.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/disk.h>
31 #include <sys/disklabel.h>
32 #include <sys/diskpc98.h>
33 #include <sys/param.h>
34 #include <sys/stat.h>
35 #include <sys/mount.h>
36 #include <ctype.h>
37 #include <fcntl.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <libgeom.h>
41 #include <paths.h>
42 #include <regex.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48
49 int iotest;
50
51 #define LBUF 100
52 static char lbuf[LBUF];
53
54 /*
55  *
56  * Ported to 386bsd by Julian Elischer  Thu Oct 15 20:26:46 PDT 1992
57  *
58  * 14-Dec-89  Robert Baron (rvb) at Carnegie-Mellon University
59  *      Copyright (c) 1989      Robert. V. Baron
60  *      Created.
61  */
62
63 #define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp
64 #define String(str, ans, len) {char *z = ans; char **dflt = &z; if (string(str, dflt)) strncpy(ans, *dflt, len); }
65
66 #define MAX_SEC_SIZE 2048       /* maximum section size that is supported */
67 #define MIN_SEC_SIZE 512        /* the sector size to start sensing at */
68 static int secsize = 0;         /* the sensed sector size */
69
70 static char *disk;
71
72 static int cyls, sectors, heads, cylsecs, disksecs;
73
74 struct mboot {
75         unsigned char padding[2]; /* force the longs to be long aligned */
76         unsigned char bootinst[510];
77         unsigned short int      signature;
78         struct  pc98_partition parts[8];
79         unsigned char large_sector_overflow[MAX_SEC_SIZE-MIN_SEC_SIZE];
80 };
81
82 static struct mboot mboot;
83 static int fd;
84
85 static uint dos_cyls;
86 static uint dos_heads;
87 static uint dos_sectors;
88 static uint dos_cylsecs;
89
90 #define MAX_ARGS        10
91
92 typedef struct cmd {
93     char                cmd;
94     int                 n_args;
95     struct arg {
96         char    argtype;
97         int     arg_val;
98     }                   args[MAX_ARGS];
99 } CMD;
100
101 static int B_flag  = 0;         /* replace boot code */
102 static int I_flag  = 0;         /* Inizialize disk to defaults */
103 static int a_flag  = 0;         /* set active partition */
104 static int i_flag  = 0;         /* replace partition data */
105 static int u_flag  = 0;         /* update partition data */
106 static int s_flag  = 0;         /* Print a summary and exit */
107 static int t_flag  = 0;         /* test only */
108 static char *f_flag = NULL;     /* Read config info from file */
109 static int v_flag  = 0;         /* Be verbose */
110
111 static struct part_type
112 {
113         unsigned char type;
114         const char *name;
115 } part_types[] = {
116          {0x00, "unused"}
117         ,{0x01, "Primary DOS with 12 bit FAT"}
118         ,{0x11, "MSDOS"}
119         ,{0x20, "MSDOS"}
120         ,{0x21, "MSDOS"}
121         ,{0x22, "MSDOS"}
122         ,{0x23, "MSDOS"}
123         ,{0x02, "XENIX / file system"}  
124         ,{0x03, "XENIX /usr file system"}  
125         ,{0x04, "PC-UX"}   
126         ,{0x05, "Extended DOS"}   
127         ,{0x06, "Primary 'big' DOS (> 32MB)"}   
128         ,{0x07, "OS/2 HPFS, QNX or Advanced UNIX"}  
129         ,{0x08, "AIX file system"}   
130         ,{0x09, "AIX boot partition or Coherent"}  
131         ,{0x0A, "OS/2 Boot Manager or OPUS"}  
132         ,{0x10, "OPUS"} 
133         ,{0x14, "FreeBSD/NetBSD/386BSD"}  
134         ,{0x94, "FreeBSD/NetBSD/386BSD"}
135         ,{0x40, "VENIX 286"}  
136         ,{0x50, "DM"}   
137         ,{0x51, "DM"}   
138         ,{0x52, "CP/M or Microport SysV/AT"}
139         ,{0x56, "GB"}
140         ,{0x61, "Speed"}
141         ,{0x63, "ISC UNIX, other System V/386, GNU HURD or Mach"}
142         ,{0x64, "Novell Netware 2.xx"}
143         ,{0x65, "Novell Netware 3.xx"}
144         ,{0x75, "PCIX"}
145         ,{0x40, "Minix"} 
146 };
147
148 static void print_s0(int which);
149 static void print_part(int i);
150 static void init_sector0(unsigned long start);
151 static void init_boot(void);
152 static void change_part(int i, int force);
153 static void print_params(void);
154 static void change_active(int which);
155 static void change_code(void);
156 static void get_params_to_use(void);
157 static char *get_rootdisk(void);
158 static void dos(u_int32_t start, u_int32_t size, struct pc98_partition *partp);
159 static int open_disk(int flag);
160 static ssize_t read_disk(off_t sector, void *buf);
161 static int write_disk(off_t sector, void *buf);
162 static int get_params(void);
163 static int read_s0(void);
164 static int write_s0(void);
165 static int ok(const char *str);
166 static int decimal(const char *str, int *num, int deflt);
167 static const char *get_type(int type);
168 static void usage(void);
169 static int string(const char *str, char **ans);
170 static void reset_boot(void);
171
172 int
173 main(int argc, char *argv[])
174 {
175         struct  stat sb;
176         int     c, i;
177         int     partition = -1;
178         struct  pc98_partition *partp;
179
180         while ((c = getopt(argc, argv, "BIa:f:istuv12345678")) != -1)
181                 switch (c) {
182                 case 'B':
183                         B_flag = 1;
184                         break;
185                 case 'I':
186                         I_flag = 1;
187                         break;
188                 case 'a':
189                         a_flag = 1;
190                         break;
191                 case 'f':
192                         f_flag = optarg;
193                         break;
194                 case 'i':
195                         i_flag = 1;
196                         break;
197                 case 's':
198                         s_flag = 1;
199                         break;
200                 case 't':
201                         t_flag = 1;
202                         break;
203                 case 'u':
204                         u_flag = 1;
205                         break;
206                 case 'v':
207                         v_flag = 1;
208                         break;
209                 case '1':
210                 case '2':
211                 case '3':
212                 case '4':
213                 case '5':
214                 case '6':
215                 case '7':
216                 case '8':
217                         partition = c - '0';
218                         break;
219                 default:
220                         usage();
221                 }
222         if (f_flag || i_flag)
223                 u_flag = 1;
224         if (t_flag)
225                 v_flag = 1;
226         argc -= optind;
227         argv += optind;
228
229         if (argc == 0) {
230                 disk = get_rootdisk();
231         } else {
232                 if (stat(argv[0], &sb) == 0) {
233                         /* OK, full pathname given */
234                         disk = argv[0];
235                 } else if (errno == ENOENT && argv[0][0] != '/') {
236                         /* Try prepending "/dev" */
237                         asprintf(&disk, "%s%s", _PATH_DEV, argv[0]);
238                         if (disk == NULL)
239                                 errx(1, "out of memory");
240                 } else {
241                         /* other stat error, let it fail below */
242                         disk = argv[0];
243                 }
244         }
245         if (open_disk(u_flag) < 0)
246                 err(1, "cannot open disk %s", disk);
247
248         if (s_flag) {
249                 if (read_s0())
250                         err(1, "read_s0");
251                 printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads,
252                     dos_sectors);
253                 printf("Part  %11s %11s %4s %4s %-16s\n", "Start", "Size", "MID",
254                     "SID", "Name");
255                 for (i = 0; i < PC98_NPARTS; i++) {
256                         partp = ((struct pc98_partition *) &mboot.parts) + i;
257                         if (partp->dp_sid == 0)
258                                 continue;
259                         printf("%4d: %11u %11u 0x%02x 0x%02x %-16.16s\n", i + 1,
260                             partp->dp_scyl * cylsecs,
261                             (partp->dp_ecyl - partp->dp_scyl + 1) * cylsecs,
262                             partp->dp_mid, partp->dp_sid, partp->dp_name);
263                 }
264                 exit(0);
265         }
266
267         printf("******* Working on device %s *******\n",disk);
268
269         if (I_flag) {
270                 read_s0();
271                 reset_boot();
272                 partp = (struct pc98_partition *) (&mboot.parts[0]);
273                 partp->dp_mid = DOSMID_386BSD;
274                 partp->dp_sid = DOSSID_386BSD;
275                 strncpy(partp->dp_name, "FreeBSD", sizeof(partp->dp_name));
276                 /* Start c/h/s. */
277                 partp->dp_scyl = partp->dp_ipl_cyl = 1;
278                 partp->dp_shd = partp->dp_ipl_head = 1;
279                 partp->dp_ssect = partp->dp_ipl_sct = 0;
280
281                 /* End c/h/s. */
282                 partp->dp_ecyl = dos_cyls - 1;
283                 partp->dp_ehd = dos_cylsecs / dos_sectors;
284                 partp->dp_esect = dos_sectors;
285
286                 if (v_flag)
287                         print_s0(-1);
288                 if (!t_flag)
289                         write_s0();
290                 exit(0);
291         }
292
293         if (f_flag) {
294             if (v_flag)
295                 print_s0(-1);
296             if (!t_flag)
297                 write_s0();
298         } else {
299             if(u_flag)
300                 get_params_to_use();
301             else
302                 print_params();
303
304             if (read_s0())
305                 init_sector0(dos_sectors);
306
307             printf("Media sector size is %d\n", secsize);
308             printf("Warning: BIOS sector numbering starts with sector 1\n");
309             printf("Information from DOS bootblock is:\n");
310             if (partition == -1)
311                 for (i = 1; i <= PC98_NPARTS; i++)
312                     change_part(i, v_flag);
313             else
314                 change_part(partition, 1);
315
316             if (u_flag || a_flag)
317                 change_active(partition);
318
319             if (B_flag)
320                 change_code();
321
322             if (u_flag || a_flag || B_flag) {
323                 if (!t_flag) {
324                     printf("\nWe haven't changed the partition table yet.  ");
325                     printf("This is your last chance.\n");
326                 }
327                 print_s0(-1);
328                 if (!t_flag) {
329                     if (ok("Should we write new partition table?"))
330                         write_s0();
331                 } else {
332                     printf("\n-t flag specified -- partition table not written.\n");
333                 }
334             }
335         }
336
337         exit(0);
338 }
339
340 static void
341 usage()
342 {
343         fprintf(stderr, "%s%s",
344                 "usage: fdisk [-BIaistu] [-12345678] [disk]\n",
345                 "       fdisk -f configfile [-itv] [disk]\n");
346         exit(1);
347 }
348
349 static struct pc98_partition mtpart;
350
351 static int
352 part_unused(int i)
353 {
354         struct    pc98_partition *partp;
355
356         partp = ((struct pc98_partition *) &mboot.parts) + i - 1;
357         return (bcmp(partp, &mtpart, sizeof (struct pc98_partition)) == 0);
358 }
359
360 static void
361 print_s0(int which)
362 {
363         int     i;
364
365         print_params();
366         printf("Information from DOS bootblock is:\n");
367         if (which == -1) {
368                 for (i = 1; i <= PC98_NPARTS; i++)
369                         if (v_flag || !part_unused(i)) {
370                                 printf("%d: ", i);
371                                 print_part(i);
372                         }
373         }
374         else
375                 print_part(which);
376 }
377
378 static void
379 print_part(int i)
380 {
381         struct    pc98_partition *partp;
382         u_int64_t part_sz, part_mb;
383
384         if (part_unused(i)) {
385                 printf("<UNUSED>\n");
386                 return;
387         }
388         /*
389          * Be careful not to overflow.
390          */
391         partp = ((struct pc98_partition *) &mboot.parts) + i - 1;
392         part_sz = (partp->dp_ecyl - partp->dp_scyl + 1) * cylsecs;
393         part_mb = part_sz * secsize;
394         part_mb /= (1024 * 1024);
395         printf("sysmid %d (%#04x),(%s)\n", partp->dp_mid, partp->dp_mid,
396             get_type(partp->dp_mid));
397         printf("    start %lu, size %lu (%ju Meg), sid %d\n",
398                 (u_long)(partp->dp_scyl * cylsecs), (u_long)part_sz,
399                 (uintmax_t)part_mb, partp->dp_sid);
400         printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n"
401                 ,partp->dp_scyl
402                 ,partp->dp_shd
403                 ,partp->dp_ssect
404                 ,partp->dp_ecyl
405                 ,partp->dp_ehd
406                 ,partp->dp_esect);
407         printf ("\tsystem Name %.16s\n", partp->dp_name);
408 }
409
410
411 static void
412 init_boot(void)
413 {
414
415         mboot.signature = PC98_MAGIC;
416 }
417
418
419 static void
420 init_sector0(unsigned long start)
421 {
422         struct pc98_partition *partp =
423                 (struct pc98_partition *)(&mboot.parts[0]);
424
425         init_boot();
426
427         partp->dp_mid = DOSMID_386BSD;
428         partp->dp_sid = DOSSID_386BSD;
429
430         dos(start, disksecs - start, partp);
431 }
432
433 static void
434 change_part(int i, int force)
435 {
436         struct pc98_partition *partp =
437                 ((struct pc98_partition *) &mboot.parts) + i - 1;
438
439         if (!force && part_unused(i))
440                 return;
441
442         printf("The data for partition %d is:\n", i);
443         print_part(i);
444
445         if (u_flag && ok("Do you want to change it?")) {
446                 int tmp;
447
448                 if (i_flag) {
449                         bzero((char *)partp, sizeof (struct pc98_partition));
450                         if (i == 1) {
451                                 init_sector0(1);
452                                 printf("\nThe static data for the slice 1 has been reinitialized to:\n");
453                                 print_part(i);
454                         }
455                 }
456                 do {
457                         int x_start = partp->dp_scyl * cylsecs ;
458                         int x_size  = (partp->dp_ecyl - partp->dp_scyl + 1) * cylsecs;
459                         Decimal("sysmid", partp->dp_mid, tmp);
460                         Decimal("syssid", partp->dp_sid, tmp);
461                         String ("system name", partp->dp_name, 16);
462                         Decimal("start", x_start, tmp);
463                         Decimal("size", x_size, tmp);
464
465                         if (ok("Explicitly specify beg/end address ?"))
466                         {
467                                 int     tsec,tcyl,thd;
468                                 tcyl = partp->dp_scyl;
469                                 thd = partp->dp_shd;
470                                 tsec = partp->dp_ssect;
471                                 Decimal("beginning cylinder", tcyl, tmp);
472                                 Decimal("beginning head", thd, tmp);
473                                 Decimal("beginning sector", tsec, tmp);
474                                 partp->dp_scyl = tcyl;
475                                 partp->dp_ssect = tsec;
476                                 partp->dp_shd = thd;
477                                 partp->dp_ipl_cyl = partp->dp_scyl;
478                                 partp->dp_ipl_sct = partp->dp_ssect;
479                                 partp->dp_ipl_head = partp->dp_shd;
480
481                                 tcyl = partp->dp_ecyl;
482                                 thd = partp->dp_ehd;
483                                 tsec = partp->dp_esect;
484                                 Decimal("ending cylinder", tcyl, tmp);
485                                 Decimal("ending head", thd, tmp);
486                                 Decimal("ending sector", tsec, tmp);
487                                 partp->dp_ecyl = tcyl;
488                                 partp->dp_esect = tsec;
489                                 partp->dp_ehd = thd;
490                         } else
491                                 dos(x_start, x_size, partp);
492
493                         print_part(i);
494                 } while (!ok("Are we happy with this entry?"));
495         }
496 }
497
498 static void
499 print_params()
500 {
501         printf("parameters extracted from in-core disklabel are:\n");
502         printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
503                         ,cyls,heads,sectors,cylsecs);
504         if (dos_cyls > 65535 || dos_heads > 255 || dos_sectors > 255)
505                 printf("Figures below won't work with BIOS for partitions not in cyl 1\n");
506         printf("parameters to be used for BIOS calculations are:\n");
507         printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n"
508                 ,dos_cyls,dos_heads,dos_sectors,dos_cylsecs);
509 }
510
511 static void
512 change_active(int which)
513 {
514         struct pc98_partition *partp = &mboot.parts[0];
515         int active, i, new, tmp;
516
517         active = -1;
518         for (i = 0; i < PC98_NPARTS; i++) {
519                 if ((partp[i].dp_sid & PC98_SID_ACTIVE) == 0)
520                         continue;
521                 printf("Partition %d is marked active\n", i + 1);
522                 if (active == -1)
523                         active = i + 1;
524         }
525         if (a_flag && which != -1)
526                 active = which;
527         else if (active == -1)
528                 active = 1;
529
530         if (!ok("Do you want to change the active partition?"))
531                 return;
532 setactive:
533         do {
534                 new = active;
535                 Decimal("active partition", new, tmp);
536                 if (new < 1 || new > 8) {
537                         printf("Active partition number must be in range 1-8."
538                                         "  Try again.\n");
539                         goto setactive;
540                 }
541                 active = new;
542         } while (!ok("Are you happy with this choice"));
543         if (active > 0 && active <= 8)
544                 partp[active-1].dp_sid |= PC98_SID_ACTIVE;
545 }
546
547 static void
548 change_code()
549 {
550         if (ok("Do you want to change the boot code?"))
551                 init_boot();
552 }
553
554 void
555 get_params_to_use()
556 {
557         int     tmp;
558         print_params();
559         if (ok("Do you want to change our idea of what BIOS thinks ?"))
560         {
561                 do
562                 {
563                         Decimal("BIOS's idea of #cylinders", dos_cyls, tmp);
564                         Decimal("BIOS's idea of #heads", dos_heads, tmp);
565                         Decimal("BIOS's idea of #sectors", dos_sectors, tmp);
566                         dos_cylsecs = dos_heads * dos_sectors;
567                         print_params();
568                 }
569                 while(!ok("Are you happy with this choice"));
570         }
571 }
572
573
574 /***********************************************\
575 * Change real numbers into strange dos numbers  *
576 \***********************************************/
577 static void
578 dos(u_int32_t start, u_int32_t size, struct pc98_partition *partp)
579 {
580         u_int32_t end;
581
582         if (partp->dp_mid == 0 && partp->dp_sid == 0 &&
583             start == 0 && size == 0) {
584                 memcpy(partp, &mtpart, sizeof(*partp));
585                 return;
586         }
587
588         /* Start c/h/s. */
589         partp->dp_scyl = partp->dp_ipl_cyl = start / dos_cylsecs;
590         partp->dp_shd = partp->dp_ipl_head = start % dos_cylsecs / dos_sectors;
591         partp->dp_ssect = partp->dp_ipl_sct = start % dos_sectors;
592
593         /* End c/h/s. */
594         end = start + size - cylsecs;
595         partp->dp_ecyl = end / dos_cylsecs;
596         partp->dp_ehd = end % dos_cylsecs / dos_sectors;
597         partp->dp_esect = end % dos_sectors;
598 }
599
600 static int
601 open_disk(int flag)
602 {
603         struct stat     st;
604         int rwmode;
605
606         if (stat(disk, &st) == -1) {
607                 if (errno == ENOENT)
608                         return -2;
609                 warnx("can't get file status of %s", disk);
610                 return -1;
611         }
612         if ( !(st.st_mode & S_IFCHR) )
613                 warnx("device %s is not character special", disk);
614         rwmode = I_flag || a_flag || B_flag || flag ? O_RDWR : O_RDONLY;
615         fd = open(disk, rwmode);
616         if (fd == -1 && errno == EPERM && rwmode == O_RDWR)
617                 fd = open(disk, O_RDONLY);
618         if (fd == -1 && errno == ENXIO)
619                 return -2;
620         if (fd == -1) {
621                 warnx("can't open device %s", disk);
622                 return -1;
623         }
624         if (get_params() == -1) {
625                 warnx("can't get disk parameters on %s", disk);
626                 return -1;
627         }
628         return fd;
629 }
630
631 static ssize_t
632 read_disk(off_t sector, void *buf)
633 {
634
635         lseek(fd, (sector * 512), 0);
636         return read(fd, buf,
637                     secsize > MIN_SEC_SIZE ? secsize : MIN_SEC_SIZE * 2);
638 }
639
640 static int
641 write_disk(off_t sector, void *buf)
642 {
643         int error;
644         struct gctl_req *grq;
645         const char *q;
646         char fbuf[BUFSIZ];
647         int i, fdw, sz;
648
649         sz = secsize > MIN_SEC_SIZE ? secsize : MIN_SEC_SIZE * 2;
650         grq = gctl_get_handle();
651         gctl_ro_param(grq, "verb", -1, "write PC98");
652         gctl_ro_param(grq, "class", -1, "PC98");
653         q = strrchr(disk, '/');
654         if (q == NULL)
655                 q = disk;
656         else
657                 q++;
658         gctl_ro_param(grq, "geom", -1, q);
659         gctl_ro_param(grq, "data", sz, buf);
660         q = gctl_issue(grq);
661         if (q == NULL) {
662                 gctl_free(grq);
663                 return(0);
664         }
665         warnx("Geom problem: %s", q);
666         gctl_free(grq);
667
668         warnx("Warning: Partitioning via geom failed, trying raw write");
669         error = pwrite(fd, buf, sz, sector * 512);
670         if (error == sz)
671                 return (0);
672
673         for (i = 0; i < PC98_NPARTS; i++) {
674                 sprintf(fbuf, "%ss%d", disk, i + 1);
675                 fdw = open(fbuf, O_RDWR, 0);
676                 if (fdw < 0)
677                         continue;
678                 error = ioctl(fdw, DIOCSPC98, buf);
679                 close(fdw);
680                 if (error == 0)
681                         return (0);
682         }
683         warnx("Failed to write sector zero");
684         return(EINVAL);
685 }
686
687 static int
688 get_params()
689 {
690         int error;
691         u_int u;
692         off_t o;
693
694         error = ioctl(fd, DIOCGFWSECTORS, &u);
695         if (error == 0)
696                 sectors = dos_sectors = u;
697         else
698                 sectors = dos_sectors = 17;
699
700         error = ioctl(fd, DIOCGFWHEADS, &u);
701         if (error == 0)
702                 heads = dos_heads = u;
703         else
704                 heads = dos_heads = 8;
705
706         dos_cylsecs = cylsecs = heads * sectors;
707         disksecs = cyls * heads * sectors;
708
709         error = ioctl(fd, DIOCGSECTORSIZE, &u);
710         if (error != 0 || u == 0)
711                 u = 512;
712         secsize = u;
713
714         error = ioctl(fd, DIOCGMEDIASIZE, &o);
715         if (error == 0) {
716                 disksecs = o / u;
717                 cyls = dos_cyls = o / (u * dos_heads * dos_sectors);
718         }
719
720         return (disksecs);
721 }
722 \f
723
724 static int
725 read_s0()
726 {
727
728         if (read_disk(0, (char *) mboot.bootinst) == -1) {
729                 warnx("can't read fdisk partition table");
730                 return -1;
731         }
732         if (mboot.signature != PC98_MAGIC) {
733                 warnx("invalid fdisk partition table found");
734                 /* So should we initialize things */
735                 return -1;
736         }
737
738         return 0;
739 }
740
741 static int
742 write_s0()
743 {
744
745         if (iotest) {
746                 print_s0(-1);
747                 return 0;
748         }
749
750         /*
751          * write enable label sector before write (if necessary),
752          * disable after writing.
753          * needed if the disklabel protected area also protects
754          * sector 0. (e.g. empty disk)
755          */
756         if (write_disk(0, (char *) mboot.bootinst) == -1) {
757                 warn("can't write fdisk partition table");
758                 return -1;
759         }
760
761         return(0);
762 }
763
764
765 static int
766 ok(const char *str)
767 {
768         printf("%s [n] ", str);
769         fflush(stdout);
770         if (fgets(lbuf, LBUF, stdin) == NULL)
771                 exit(1);
772         lbuf[strlen(lbuf)-1] = 0;
773
774         if (*lbuf &&
775                 (!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") ||
776                  !strcmp(lbuf, "y") || !strcmp(lbuf, "Y")))
777                 return 1;
778         else
779                 return 0;
780 }
781
782 static int
783 decimal(const char *str, int *num, int deflt)
784 {
785         int acc = 0, c;
786         char *cp;
787
788         while (1) {
789                 printf("Supply a decimal value for \"%s\" [%d] ", str, deflt);
790                 fflush(stdout);
791                 if (fgets(lbuf, LBUF, stdin) == NULL)
792                         exit(1);
793                 lbuf[strlen(lbuf)-1] = 0;
794
795                 if (!*lbuf)
796                         return 0;
797
798                 cp = lbuf;
799                 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
800                 if (!c)
801                         return 0;
802                 while ((c = *cp++)) {
803                         if (c <= '9' && c >= '0')
804                                 acc = acc * 10 + c - '0';
805                         else
806                                 break;
807                 }
808                 if (c == ' ' || c == '\t')
809                         while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
810                 if (!c) {
811                         *num = acc;
812                         return 1;
813                 } else
814                         printf("%s is an invalid decimal number.  Try again.\n",
815                                 lbuf);
816         }
817
818 }
819
820 static int
821 string(const char *str, char **ans)
822 {
823         int i, c;
824         char *cp = lbuf;
825
826         while (1) {
827                 printf("Supply a string value for \"%s\" [%s] ", str, *ans);
828                 fgets(lbuf, LBUF, stdin);
829                 lbuf[strlen(lbuf)-1] = 0;
830
831                 if (!*lbuf)
832                         return 0;
833
834                 while ((c = *cp) && (c == ' ' || c == '\t')) cp++;
835                 if (c == '"') {
836                         c = *++cp;
837                         *ans = cp;
838                         while ((c = *cp) && c != '"') cp++;
839                 } else {
840                         *ans = cp;
841                         while ((c = *cp) && c != ' ' && c != '\t') cp++;
842                 }
843
844                 for (i = strlen(*ans); i < 16; i++)
845                         (*ans)[i] = ' ';
846                 (*ans)[16] = 0;
847
848                 return 1;
849         }
850 }
851
852 static const char *
853 get_type(int type)
854 {
855         size_t i;
856
857         for (i = 0; i < nitems(part_types); i++)
858                 if (part_types[i].type == (type & 0x7f))
859                         return(part_types[i].name);
860         return("unknown");
861 }
862
863 /*
864  * Try figuring out the root device's canonical disk name.
865  * The following choices are considered:
866  *   /dev/ad0s1a     => /dev/ad0
867  *   /dev/da0a       => /dev/da0
868  *   /dev/vinum/root => /dev/vinum/root
869  */
870 static char *
871 get_rootdisk(void)
872 {
873         struct statfs rootfs;
874         regex_t re;
875 #define NMATCHES 2
876         regmatch_t rm[NMATCHES];
877         char *s;
878         int rv;
879
880         if (statfs("/", &rootfs) == -1)
881                 err(1, "statfs(\"/\")");
882
883         if ((rv = regcomp(&re, "^(/dev/[a-z]+[0-9]+)([sp][0-9]+)?[a-h]?$",
884                     REG_EXTENDED)) != 0)
885                 errx(1, "regcomp() failed (%d)", rv);
886         if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0)
887                 errx(1,
888 "mounted root fs resource doesn't match expectations (regexec returned %d)",
889                     rv);
890         if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL)
891                 errx(1, "out of memory");
892         memcpy(s, rootfs.f_mntfromname + rm[1].rm_so,
893             rm[1].rm_eo - rm[1].rm_so);
894         s[rm[1].rm_eo - rm[1].rm_so] = 0;
895
896         return s;
897 }
898
899 static void
900 reset_boot(void)
901 {
902         int i;
903         struct pc98_partition *partp;
904
905         init_boot();
906         for (i = 1; i <= PC98_NPARTS; i++) {
907                 partp = ((struct pc98_partition *) &mboot.parts) + i - 1;
908                 bzero((char *)partp, sizeof (struct pc98_partition));
909         }
910 }