• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2     Copyright (C) 2010-2022  <Roderick W. Smith>
3 
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8 
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13 
14     You should have received a copy of the GNU General Public License along
15     with this program; if not, write to the Free Software Foundation, Inc.,
16     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17 
18 */
19 
20 /* This class implements an interactive text-mode interface atop the
21    GPTData class */
22 
23 #include <string.h>
24 #include <errno.h>
25 #include <stdint.h>
26 #include <limits.h>
27 #include <iostream>
28 #include <fstream>
29 #include <sstream>
30 #include <cstdio>
31 #include "attributes.h"
32 #include "gpttext.h"
33 #include "support.h"
34 
35 using namespace std;
36 
37 /********************************************
38  *                                          *
39  * GPTDataText class and related structures *
40  *                                          *
41  ********************************************/
42 
GPTDataTextUI(void)43 GPTDataTextUI::GPTDataTextUI(void) : GPTData() {
44 } // default constructor
45 
GPTDataTextUI(string filename)46 GPTDataTextUI::GPTDataTextUI(string filename) : GPTData(filename) {
47 } // constructor passing filename
48 
~GPTDataTextUI(void)49 GPTDataTextUI::~GPTDataTextUI(void) {
50 } // default destructor
51 
52 /*********************************************************************
53  *                                                                   *
54  * The following functions are extended (interactive) versions of    *
55  * simpler functions in the base class....                           *
56  *                                                                   *
57  *********************************************************************/
58 
59 // Overridden function; calls base-class function and then makes
60 // additional queries of the user, if the base-class function can't
61 // decide what to do.
UseWhichPartitions(void)62 WhichToUse GPTDataTextUI::UseWhichPartitions(void) {
63    WhichToUse which;
64    MBRValidity mbrState;
65    int answer;
66 
67    which = GPTData::UseWhichPartitions();
68    if ((which != use_abort) || beQuiet)
69       return which;
70 
71    // If we get past here, it means that the non-interactive tests were
72    // inconclusive, so we must ask the user which table to use....
73    mbrState = protectiveMBR.GetValidity();
74 
75    if ((state == gpt_valid) && (mbrState == mbr)) {
76       cout << "Found valid MBR and GPT. Which do you want to use?\n";
77       answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
78       if (answer == 1) {
79          which = use_mbr;
80       } else if (answer == 2) {
81          which = use_gpt;
82          cout << "Using GPT and creating fresh protective MBR.\n";
83       } else which = use_new;
84    } // if
85 
86    // Nasty decisions here -- GPT is present, but corrupt (bad CRCs or other
87    // problems)
88    if (state == gpt_corrupt) {
89       if ((mbrState == mbr) || (mbrState == hybrid)) {
90          cout << "Found valid MBR and corrupt GPT. Which do you want to use? (Using the\n"
91               << "GPT MAY permit recovery of GPT data.)\n";
92          answer = GetNumber(1, 3, 2, " 1 - MBR\n 2 - GPT\n 3 - Create blank GPT\n\nYour answer: ");
93          if (answer == 1) {
94             which = use_mbr;
95          } else if (answer == 2) {
96             which = use_gpt;
97          } else which = use_new;
98       } else if (mbrState == invalid) {
99          cout << "Found invalid MBR and corrupt GPT. What do you want to do? (Using the\n"
100               << "GPT MAY permit recovery of GPT data.)\n";
101          answer = GetNumber(1, 2, 1, " 1 - Use current GPT\n 2 - Create blank GPT\n\nYour answer: ");
102          if (answer == 1) {
103             which = use_gpt;
104          } else which = use_new;
105       } // if/else/else
106    } // if (corrupt GPT)
107 
108    return which;
109 } // UseWhichPartitions()
110 
111 // Ask the user for a partition number; and prompt for verification
112 // if the requested partition isn't of a known BSD type.
113 // Lets the base-class function do the work, and returns its value (the
114 // number of converted partitions).
XFormDisklabel(void)115 int GPTDataTextUI::XFormDisklabel(void) {
116    uint32_t partNum;
117    uint16_t hexCode;
118    int goOn = 1, numDone = 0;
119    BSDData disklabel;
120 
121    partNum = GetPartNum();
122 
123    // Now see if the specified partition has a BSD type code....
124    hexCode = partitions[partNum].GetHexType();
125    if ((hexCode != 0xa500) && (hexCode != 0xa900)) {
126       cout << "Specified partition doesn't have a disklabel partition type "
127            << "code.\nContinue anyway? ";
128       goOn = (GetYN() == 'Y');
129    } // if
130 
131    if (goOn)
132       numDone = GPTData::XFormDisklabel(partNum);
133 
134    return numDone;
135 } // GPTDataTextUI::XFormDisklabel(void)
136 
137 
138 /*********************************************************************
139  *                                                                   *
140  * Begin functions that obtain information from the users, and often *
141  * do something with that information (call other functions)         *
142  *                                                                   *
143  *********************************************************************/
144 
145 // Prompts user for partition number and returns the result. Returns "0"
146 // (the first partition) if none are currently defined.
GetPartNum(void)147 uint32_t GPTDataTextUI::GetPartNum(void) {
148    uint32_t partNum;
149    uint32_t low, high;
150    ostringstream prompt;
151 
152    if (GetPartRange(&low, &high) > 0) {
153       prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
154       partNum = GetNumber(low + 1, high + 1, low, prompt.str());
155    } else partNum = 1;
156    return (partNum - 1);
157 } // GPTDataTextUI::GetPartNum()
158 
159 // What it says: Resize the partition table. (Default is 128 entries.)
ResizePartitionTable(void)160 void GPTDataTextUI::ResizePartitionTable(void) {
161    int newSize;
162    ostringstream prompt;
163    uint32_t curLow, curHigh;
164 
165    cout << "Current partition table size is " << numParts << ".\n";
166    GetPartRange(&curLow, &curHigh);
167    curHigh++; // since GetPartRange() returns numbers starting from 0...
168    // There's no point in having fewer than four partitions....
169    if (curHigh < (blockSize / GPT_SIZE))
170       curHigh = blockSize / GPT_SIZE;
171    prompt << "Enter new size (" << curHigh << " up, default " << NUM_GPT_ENTRIES << "): ";
172    newSize = GetNumber(4, 65535, 128, prompt.str());
173    if (newSize < 128) {
174       cout << "Caution: The partition table size should officially be 16KB or larger,\n"
175            << "which works out to 128 entries. In practice, smaller tables seem to\n"
176            << "work with most OSes, but this practice is risky. I'm proceeding with\n"
177            << "the resize, but you may want to reconsider this action and undo it.\n\n";
178    } // if
179    SetGPTSize(newSize);
180 } // GPTDataTextUI::ResizePartitionTable()
181 
182 // Move the main partition table (to enable some SoC boot loaders to place
183 // code at sector 2, for instance).
MoveMainTable(void)184 void GPTDataTextUI::MoveMainTable(void) {
185     uint64_t newStart, pteSize = GetTableSizeInSectors();
186     uint64_t maxValue = FindFirstUsedLBA() - pteSize;
187     ostringstream prompt;
188 
189     cout << "Currently, main partition table begins at sector " << mainHeader.partitionEntriesLBA
190          << " and ends at sector " << mainHeader.partitionEntriesLBA + pteSize - 1 << "\n";
191     prompt << "Enter new starting location (2 to " << maxValue << "; default is 2; 1 to abort): ";
192     newStart = GetNumber(1, maxValue, 2, prompt.str());
193     if (newStart != 1) {
194         GPTData::MoveMainTable(newStart);
195     } else {
196         cout << "Aborting change!\n";
197     } // if
198 } // GPTDataTextUI::MoveMainTable()
199 
200 // Interactively create a partition
CreatePartition(void)201 void GPTDataTextUI::CreatePartition(void) {
202    uint64_t firstBlock, firstInLargest, lastBlock, sector, origSector, lastAligned;
203    uint32_t firstFreePart = 0;
204    ostringstream prompt1, prompt2, prompt3;
205    int partNum;
206 
207    // Find first free partition...
208    while (partitions[firstFreePart].GetFirstLBA() != 0) {
209       firstFreePart++;
210    } // while
211 
212    if (((firstBlock = FindFirstAvailable()) != 0) &&
213        (firstFreePart < numParts)) {
214       lastBlock = FindLastAvailable();
215       firstInLargest = FindFirstInLargest();
216       Align(&firstInLargest);
217 
218       // Get partition number....
219       prompt1 << "Partition number (" << firstFreePart + 1 << "-" << numParts
220               << ", default " << firstFreePart + 1 << "): ";
221       do {
222          partNum = GetNumber(firstFreePart + 1, numParts,
223                              firstFreePart + 1, prompt1.str()) - 1;
224          if (partitions[partNum].GetFirstLBA() != 0)
225             cout << "partition " << partNum + 1 << " is in use.\n";
226       } while (partitions[partNum].GetFirstLBA() != 0);
227 
228       // Get first block for new partition...
229       prompt2 << "First sector (" << firstBlock << "-" << lastBlock << ", default = "
230               << firstInLargest << ") or {+-}size{KMGTP}: ";
231       do {
232          sector = GetSectorNum(firstBlock, lastBlock, firstInLargest, prompt2.str());
233       } while (IsFree(sector) == 0);
234       origSector = sector;
235       if (Align(&sector)) {
236          cout << "Information: Moved requested sector from " << origSector << " to "
237               << sector << " in\norder to align on " << sectorAlignment
238               << "-sector boundaries.\n";
239          if (!beQuiet)
240             cout << "Use 'l' on the experts' menu to adjust alignment\n";
241       } // if
242       firstBlock = sector;
243 
244       // Get last block for new partitions...
245       lastBlock = FindLastInFree(firstBlock, false);
246       lastAligned = FindLastInFree(firstBlock, true);
247       prompt3 << "Last sector (" << firstBlock << "-" << lastBlock << ", default = "
248               << lastAligned << ") or {+-}size{KMGTP}: ";
249       do {
250          sector = GetSectorNum(firstBlock, lastBlock, lastAligned, prompt3.str());
251       } while (IsFree(sector) == 0);
252       lastBlock = sector;
253 
254       GPTData::CreatePartition(partNum, firstBlock, lastBlock);
255       partitions[partNum].ChangeType();
256       partitions[partNum].SetDefaultDescription();
257    } else {
258       if (firstFreePart >= numParts)
259          cout << "No table partition entries left\n";
260       else
261          cout << "No free sectors available\n";
262    } // if/else
263 } // GPTDataTextUI::CreatePartition()
264 
265 // Interactively delete a partition (duh!)
DeletePartition(void)266 void GPTDataTextUI::DeletePartition(void) {
267    int partNum;
268    uint32_t low, high;
269    ostringstream prompt;
270 
271    if (GetPartRange(&low, &high) > 0) {
272       prompt << "Partition number (" << low + 1 << "-" << high + 1 << "): ";
273       partNum = GetNumber(low + 1, high + 1, low, prompt.str());
274       GPTData::DeletePartition(partNum - 1);
275    } else {
276       cout << "No partitions\n";
277    } // if/else
278 } // GPTDataTextUI::DeletePartition()
279 
280 // Prompt user for a partition number, then change its type code
ChangePartType(void)281 void GPTDataTextUI::ChangePartType(void) {
282    int partNum;
283    uint32_t low, high;
284 
285    if (GetPartRange(&low, &high) > 0) {
286       partNum = GetPartNum();
287       partitions[partNum].ChangeType();
288    } else {
289       cout << "No partitions\n";
290    } // if/else
291 } // GPTDataTextUI::ChangePartType()
292 
293 // Prompt user for a partition number, then change its unique
294 // GUID.
ChangeUniqueGuid(void)295 void GPTDataTextUI::ChangeUniqueGuid(void) {
296    int partNum;
297    uint32_t low, high;
298    string guidStr;
299 
300    if (GetPartRange(&low, &high) > 0) {
301       partNum = GetPartNum();
302       cout << "Enter the partition's new unique GUID ('R' to randomize): ";
303       guidStr = ReadString();
304       if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
305          SetPartitionGUID(partNum, (GUIDData) guidStr);
306          cout << "New GUID is " << partitions[partNum].GetUniqueGUID() << "\n";
307       } else {
308          cout << "GUID is too short!\n";
309       } // if/else
310    } else
311       cout << "No partitions\n";
312 } // GPTDataTextUI::ChangeUniqueGuid()
313 
314 // Partition attributes seem to be rarely used, but I want a way to
315 // adjust them for completeness....
SetAttributes(uint32_t partNum)316 void GPTDataTextUI::SetAttributes(uint32_t partNum) {
317    partitions[partNum].SetAttributes();
318 } // GPTDataTextUI::SetAttributes()
319 
320 // Prompts the user for a partition name and sets the partition's
321 // name. Returns 1 on success, 0 on failure (invalid partition
322 // number). (Note that the function skips prompting when an
323 // invalid partition number is detected.)
SetName(uint32_t partNum)324 int GPTDataTextUI::SetName(uint32_t partNum) {
325    UnicodeString theName = "";
326    int retval = 1;
327 
328    if (IsUsedPartNum(partNum)) {
329       cout << "Enter name: ";
330 #ifdef USE_UTF16
331       theName = ReadUString();
332 #else
333       theName = ReadString();
334 #endif
335       partitions[partNum].SetName(theName);
336    } else {
337       cerr << "Invalid partition number (" << partNum << ")\n";
338       retval = 0;
339    } // if/else
340 
341    return retval;
342 } // GPTDataTextUI::SetName()
343 
344 // Enable the user to byte-swap the name of the partition. Used to correct
345 // partition names damaged by incorrect byte order, as could be created by
346 // GPT fdisk 1.0.7 and earlier on big-endian systems, and perhaps other tools.
ReverseName(uint32_t partNum)347 void GPTDataTextUI::ReverseName(uint32_t partNum) {
348    int swapBytes;
349 
350    cout << "Current name is: " << partitions[partNum].GetDescription() << "\n";
351    partitions[partNum].ReverseNameBytes();
352    cout << "Byte-swapped name is: " << partitions[partNum].GetDescription() << "\n";
353    cout << "Do you want to byte-swap the name? ";
354    swapBytes = (GetYN() == 'Y');
355    // Already swapped for display, so undo if necessary....
356    if (!swapBytes)
357       partitions[partNum].ReverseNameBytes();
358 } // GPTDataTextUI::ReverseName()
359 
360 // Ask user for two partition numbers and swap them in the table. Note that
361 // this just reorders table entries; it doesn't adjust partition layout on
362 // the disk.
363 // Returns 1 if successful, 0 if not. (If user enters identical numbers, it
364 // counts as successful.)
SwapPartitions(void)365 int GPTDataTextUI::SwapPartitions(void) {
366    int partNum1, partNum2, didIt = 0;
367    uint32_t low, high;
368    ostringstream prompt;
369    GPTPart temp;
370 
371    if (GetPartRange(&low, &high) > 0) {
372       partNum1 = GetPartNum();
373       if (high >= numParts - 1)
374          high = 0;
375       prompt << "New partition number (1-" << numParts
376              << ", default " << high + 2 << "): ";
377       partNum2 = GetNumber(1, numParts, high + 2, prompt.str()) - 1;
378       didIt = GPTData::SwapPartitions(partNum1, partNum2);
379    } else {
380       cout << "No partitions\n";
381    } // if/else
382    return didIt;
383 } // GPTDataTextUI::SwapPartitionNumbers()
384 
385 // This function destroys the on-disk GPT structures. Returns 1 if the user
386 // confirms destruction, 0 if the user aborts or if there's a disk error.
DestroyGPTwPrompt(void)387 int GPTDataTextUI::DestroyGPTwPrompt(void) {
388    int allOK = 1;
389 
390    if ((apmFound) || (bsdFound)) {
391       cout << "WARNING: APM or BSD disklabel structures detected! This operation could\n"
392            << "damage any APM or BSD partitions on this disk!\n";
393    } // if APM or BSD
394    cout << "\a\aAbout to wipe out GPT on " << device << ". Proceed? ";
395    if (GetYN() == 'Y') {
396       if (DestroyGPT()) {
397          // Note on below: Touch the MBR only if the user wants it completely
398          // blanked out. Version 0.4.2 deleted the 0xEE partition and re-wrote
399          // the MBR, but this could wipe out a valid MBR that the program
400          // had subsequently discarded (say, if it conflicted with older GPT
401          // structures).
402          cout << "Blank out MBR? ";
403          if (GetYN() == 'Y') {
404             DestroyMBR();
405          } else {
406             cout << "MBR is unchanged. You may need to delete an EFI GPT (0xEE) partition\n"
407                  << "with fdisk or another tool.\n";
408          } // if/else
409       } else allOK = 0; // if GPT structures destroyed
410    } else allOK = 0; // if user confirms destruction
411    return (allOK);
412 } // GPTDataTextUI::DestroyGPTwPrompt()
413 
414 // Get partition number from user and then call ShowPartDetails(partNum)
415 // to show its detailed information
ShowDetails(void)416 void GPTDataTextUI::ShowDetails(void) {
417    int partNum;
418    uint32_t low, high;
419 
420    if (GetPartRange(&low, &high) > 0) {
421       partNum = GetPartNum();
422       ShowPartDetails(partNum);
423    } else {
424       cout << "No partitions\n";
425    } // if/else
426 } // GPTDataTextUI::ShowDetails()
427 
428 // Create a hybrid MBR -- an ugly, funky thing that helps GPT work with
429 // OSes that don't understand GPT.
MakeHybrid(void)430 void GPTDataTextUI::MakeHybrid(void) {
431    uint32_t partNums[3] = {0, 0, 0};
432    string line;
433    int numPartsToCvt = 0, numConverted = 0, i, j, mbrNum = 0;
434    unsigned int hexCode = 0;
435    MBRPart hybridPart;
436    MBRData hybridMBR;
437    char eeFirst = 'Y'; // Whether EFI GPT (0xEE) partition comes first in table
438 
439    cout << "\nWARNING! Hybrid MBRs are flaky and dangerous! If you decide not to use one,\n"
440         << "just hit the Enter key at the below prompt and your MBR partition table will\n"
441         << "be untouched.\n\n\a";
442 
443    // Use a local MBR structure, copying from protectiveMBR to keep its
444    // boot loader code intact....
445    hybridMBR = protectiveMBR;
446    hybridMBR.EmptyMBR(0);
447 
448    // Now get the numbers of up to three partitions to add to the
449    // hybrid MBR....
450    cout << "Type from one to three GPT partition numbers, separated by spaces, to be\n"
451         << "added to the hybrid MBR, in sequence: ";
452    line = ReadString();
453    istringstream inLine(line);
454    do {
455       inLine >> partNums[numPartsToCvt];
456       if (partNums[numPartsToCvt] > 0)
457          numPartsToCvt++;
458    } while (!inLine.eof() && (numPartsToCvt < 3));
459 
460    if (numPartsToCvt > 0) {
461       cout << "Place EFI GPT (0xEE) partition first in MBR (good for GRUB)? ";
462       eeFirst = GetYN();
463    } // if
464 
465    for (i = 0; i < numPartsToCvt; i++) {
466       j = partNums[i] - 1;
467       if (partitions[j].IsUsed() && (partitions[j].IsSizedForMBR() != MBR_SIZED_BAD)) {
468          mbrNum = i + (eeFirst == 'Y');
469          cout << "\nCreating entry for GPT partition #" << j + 1
470               << " (MBR partition #" << mbrNum + 1 << ")\n";
471          hybridPart.SetType(GetMBRTypeCode(partitions[j].GetHexType() / 256));
472          hybridPart.SetLocation(partitions[j].GetFirstLBA(), partitions[j].GetLengthLBA());
473          hybridPart.SetInclusion(PRIMARY);
474          cout << "Set the bootable flag? ";
475          if (GetYN() == 'Y')
476             hybridPart.SetStatus(0x80);
477          else
478             hybridPart.SetStatus(0x00);
479          hybridPart.SetInclusion(PRIMARY);
480          if (partitions[j].IsSizedForMBR() == MBR_SIZED_IFFY)
481             WarnAboutIffyMBRPart(j + 1);
482          numConverted++;
483       } else {
484          cerr << "\nGPT partition #" << j + 1 << " does not exist or is too big; skipping.\n";
485       } // if/else
486       hybridMBR.AddPart(mbrNum, hybridPart);
487    } // for
488 
489    if (numConverted > 0) { // User opted to create a hybrid MBR....
490       // Create EFI protective partition that covers the start of the disk.
491       // If this location (covering the main GPT data structures) is omitted,
492       // Linux won't find any partitions on the disk.
493       hybridPart.SetLocation(1, hybridMBR.FindLastInFree(1));
494       hybridPart.SetStatus(0);
495       hybridPart.SetType(0xEE);
496       hybridPart.SetInclusion(PRIMARY);
497       // newNote firstLBA and lastLBA are computed later...
498       if (eeFirst == 'Y') {
499          hybridMBR.AddPart(0, hybridPart);
500       } else {
501          hybridMBR.AddPart(numConverted, hybridPart);
502       } // else
503       hybridMBR.SetHybrid();
504 
505       // ... and for good measure, if there are any partition spaces left,
506       // optionally create another protective EFI partition to cover as much
507       // space as possible....
508       if (hybridMBR.CountParts() < 4) { // unused entry....
509          cout << "\nUnused partition space(s) found. Use one to protect more partitions? ";
510          if (GetYN() == 'Y') {
511             cout << "Note: Default is 0xEE, but this may confuse Mac OS X.\n";
512             // Comment on above: Mac OS treats disks with more than one
513             // 0xEE MBR partition as MBR disks, not as GPT disks.
514             hexCode = GetMBRTypeCode(0xEE);
515             hybridMBR.MakeBiggestPart(3, hexCode);
516          } // if (GetYN() == 'Y')
517       } // if unused entry
518       protectiveMBR = hybridMBR;
519    } else {
520       cout << "\nNo partitions converted; original protective/hybrid MBR is unmodified!\n";
521    } // if/else (numConverted > 0)
522 } // GPTDataTextUI::MakeHybrid()
523 
524 // Convert the GPT to MBR form, storing partitions in the protectiveMBR
525 // variable. This function is necessarily limited; it may not be able to
526 // convert all partitions, depending on the disk size and available space
527 // before each partition (one free sector is required to create a logical
528 // partition, which are necessary to convert more than four partitions).
529 // Returns the number of converted partitions; if this value
530 // is over 0, the calling function should call DestroyGPT() to destroy
531 // the GPT data, call SaveMBR() to save the MBR, and then exit.
XFormToMBR(void)532 int GPTDataTextUI::XFormToMBR(void) {
533    uint32_t i;
534 
535    protectiveMBR.EmptyMBR(0);
536    for (i = 0; i < numParts; i++) {
537       if (partitions[i].IsUsed()) {
538          if (partitions[i].IsSizedForMBR() == MBR_SIZED_IFFY)
539             WarnAboutIffyMBRPart(i + 1);
540          // Note: MakePart() checks for oversized partitions, so don't
541          // bother checking other IsSizedForMBR() return values....
542          protectiveMBR.MakePart(i, partitions[i].GetFirstLBA(),
543                                 partitions[i].GetLengthLBA(),
544                                 partitions[i].GetHexType() / 0x0100, 0);
545       } // if
546    } // for
547    protectiveMBR.MakeItLegal();
548    return protectiveMBR.DoMenu();
549 } // GPTDataTextUI::XFormToMBR()
550 
551 // Obtains a sector number, between low and high, from the
552 // user, accepting values prefixed by "+" to add sectors to low,
553 // or the same with "K", "M", "G", "T", or "P" as suffixes to add
554 // kibibytes, mebibytes, gibibytes, tebibytes, or pebibytes,
555 // respectively. If a "-" prefix is used, use the high value minus
556 // the user-specified number of sectors (or KiB, MiB, etc.). Use the
557 // def value as the default if the user just hits Enter.
GetSectorNum(uint64_t low,uint64_t high,uint64_t def,const string & prompt)558 uint64_t GPTDataTextUI::GetSectorNum(uint64_t low, uint64_t high, uint64_t def,
559                                      const string & prompt) {
560    uint64_t response;
561    char line[255];
562 
563    do {
564       cout << prompt;
565       cin.getline(line, 255);
566       if (!cin.good())
567          exit(5);
568       response = IeeeToInt(line, blockSize, low, high, sectorAlignment, def);
569    } while ((response < low) || (response > high));
570    return response;
571 } // GPTDataTextUI::GetSectorNum()
572 
573 /******************************************************
574  *                                                    *
575  * Display informational messages for the user....    *
576  *                                                    *
577  ******************************************************/
578 
579 // Although an MBR partition that begins below sector 2^32 and is less than 2^32 sectors in
580 // length is technically legal even if it ends above the 2^32-sector mark, such a partition
581 // tends to confuse a lot of OSes, so warn the user about such partitions. This function is
582 // called by XFormToMBR() and MakeHybrid(); it's a separate function just to consolidate the
583 // lengthy message in one place.
WarnAboutIffyMBRPart(int partNum)584 void GPTDataTextUI::WarnAboutIffyMBRPart(int partNum) {
585    cout << "\a\nWarning! GPT partition " << partNum << " ends after the 2^32 sector mark! The partition\n"
586         << "begins before this point, and is smaller than 2^32 sectors. This is technically\n"
587         << "legal, but will confuse some OSes. The partition IS being added to the MBR, but\n"
588         << "if your OS misbehaves or can't see the partition, the partition may simply be\n"
589         << "unusable in that OS and may need to be resized or omitted from the MBR.\n\n";
590 } // GPTDataTextUI::WarnAboutIffyMBRPart()
591 
592 /*********************************************************************
593  *                                                                   *
594  * The following functions provide the main menus for the gdisk      *
595  * program....                                                       *
596  *                                                                   *
597  *********************************************************************/
598 
599 // Accept a command and execute it. Returns only when the user
600 // wants to exit (such as after a 'w' or 'q' command).
MainMenu(string filename)601 void GPTDataTextUI::MainMenu(string filename) {
602    int goOn = 1;
603    PartType typeHelper;
604    uint32_t temp1, temp2;
605 
606    do {
607       cout << "\nCommand (? for help): ";
608       switch (ReadString()[0]) {
609          case '\0':
610             goOn = cin.good();
611             break;
612          case 'b': case 'B':
613             cout << "Enter backup filename to save: ";
614             SaveGPTBackup(ReadString());
615             break;
616          case 'c': case 'C':
617             if (GetPartRange(&temp1, &temp2) > 0)
618                SetName(GetPartNum());
619             else
620                cout << "No partitions\n";
621             break;
622          case 'd': case 'D':
623             DeletePartition();
624             break;
625          case 'i': case 'I':
626             ShowDetails();
627             break;
628          case 'l': case 'L':
629             typeHelper.ShowAllTypes();
630             break;
631          case 'n': case 'N':
632             CreatePartition();
633             break;
634          case 'o': case 'O':
635             cout << "This option deletes all partitions and creates a new protective MBR.\n"
636                  << "Proceed? ";
637             if (GetYN() == 'Y') {
638                ClearGPTData();
639                MakeProtectiveMBR();
640             } // if
641             break;
642          case 'p': case 'P':
643             DisplayGPTData();
644             break;
645          case 'q': case 'Q':
646             goOn = 0;
647             break;
648          case 'r': case 'R':
649             RecoveryMenu(filename);
650             goOn = 0;
651             break;
652          case 's': case 'S':
653             SortGPT();
654             cout << "You may need to edit /etc/fstab and/or your boot loader configuration!\n";
655             break;
656          case 't': case 'T':
657             ChangePartType();
658             break;
659          case 'v': case 'V':
660             Verify();
661             break;
662          case 'w': case 'W':
663             if (SaveGPTData() == 1)
664                goOn = 0;
665             break;
666          case 'x': case 'X':
667             ExpertsMenu(filename);
668             goOn = 0;
669             break;
670          default:
671             ShowCommands();
672             break;
673       } // switch
674    } while (goOn);
675 } // GPTDataTextUI::MainMenu()
676 
ShowCommands(void)677 void GPTDataTextUI::ShowCommands(void) {
678    cout << "b\tback up GPT data to a file\n";
679    cout << "c\tchange a partition's name\n";
680    cout << "d\tdelete a partition\n";
681    cout << "i\tshow detailed information on a partition\n";
682    cout << "l\tlist known partition types\n";
683    cout << "n\tadd a new partition\n";
684    cout << "o\tcreate a new empty GUID partition table (GPT)\n";
685    cout << "p\tprint the partition table\n";
686    cout << "q\tquit without saving changes\n";
687    cout << "r\trecovery and transformation options (experts only)\n";
688    cout << "s\tsort partitions\n";
689    cout << "t\tchange a partition's type code\n";
690    cout << "v\tverify disk\n";
691    cout << "w\twrite table to disk and exit\n";
692    cout << "x\textra functionality (experts only)\n";
693    cout << "?\tprint this menu\n";
694 } // GPTDataTextUI::ShowCommands()
695 
696 // Accept a recovery & transformation menu command. Returns only when the user
697 // issues an exit command, such as 'w' or 'q'.
RecoveryMenu(string filename)698 void GPTDataTextUI::RecoveryMenu(string filename) {
699    uint32_t numParts;
700    int goOn = 1, temp1;
701 
702    do {
703       cout << "\nRecovery/transformation command (? for help): ";
704       switch (ReadString()[0]) {
705          case '\0':
706             goOn = cin.good();
707             break;
708          case 'b': case 'B':
709             RebuildMainHeader();
710             break;
711          case 'c': case 'C':
712             cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
713             << "GPT form and haven't yet saved the GPT! Proceed? ";
714             if (GetYN() == 'Y')
715                LoadSecondTableAsMain();
716             break;
717          case 'd': case 'D':
718             RebuildSecondHeader();
719             break;
720          case 'e': case 'E':
721             cout << "Warning! This will probably do weird things if you've converted an MBR to\n"
722             << "GPT form and haven't yet saved the GPT! Proceed? ";
723             if (GetYN() == 'Y')
724                LoadMainTable();
725             break;
726          case 'f': case 'F':
727             cout << "Warning! This will destroy the currently defined partitions! Proceed? ";
728             if (GetYN() == 'Y') {
729                if (LoadMBR(filename) == 1) { // successful load
730                   XFormPartitions();
731                } else {
732                   cout << "Problem loading MBR! GPT is untouched; regenerating protective MBR!\n";
733                   MakeProtectiveMBR();
734                } // if/else
735             } // if
736             break;
737          case 'g': case 'G':
738             numParts = GetNumParts();
739             temp1 = XFormToMBR();
740             if (temp1 > 0)
741                cout << "\nConverted " << temp1 << " partitions. Finalize and exit? ";
742             if ((temp1 > 0) && (GetYN() == 'Y')) {
743                if ((DestroyGPT() > 0) && (SaveMBR())) {
744                   goOn = 0;
745                } // if
746             } else {
747                MakeProtectiveMBR();
748                SetGPTSize(numParts, 0);
749                cout << "Note: New protective MBR created\n\n";
750             } // if/else
751             break;
752          case 'h': case 'H':
753             MakeHybrid();
754             break;
755          case 'i': case 'I':
756             ShowDetails();
757             break;
758          case 'l': case 'L':
759             cout << "Enter backup filename to load: ";
760             LoadGPTBackup(ReadString());
761             break;
762          case 'm': case 'M':
763             MainMenu(filename);
764             goOn = 0;
765             break;
766          case 'o': case 'O':
767             DisplayMBRData();
768             break;
769          case 'p': case 'P':
770             DisplayGPTData();
771             break;
772          case 'q': case 'Q':
773             goOn = 0;
774             break;
775          case 't': case 'T':
776             XFormDisklabel();
777             break;
778          case 'v': case 'V':
779             Verify();
780             break;
781          case 'w': case 'W':
782             if (SaveGPTData() == 1) {
783                goOn = 0;
784             } // if
785             break;
786          case 'x': case 'X':
787             ExpertsMenu(filename);
788             goOn = 0;
789             break;
790          default:
791             ShowRecoveryCommands();
792             break;
793       } // switch
794    } while (goOn);
795 } // GPTDataTextUI::RecoveryMenu()
796 
ShowRecoveryCommands(void)797 void GPTDataTextUI::ShowRecoveryCommands(void) {
798    cout << "b\tuse backup GPT header (rebuilding main)\n";
799    cout << "c\tload backup partition table from disk (rebuilding main)\n";
800    cout << "d\tuse main GPT header (rebuilding backup)\n";
801    cout << "e\tload main partition table from disk (rebuilding backup)\n";
802    cout << "f\tload MBR and build fresh GPT from it\n";
803    cout << "g\tconvert GPT into MBR and exit\n";
804    cout << "h\tmake hybrid MBR\n";
805    cout << "i\tshow detailed information on a partition\n";
806    cout << "l\tload partition data from a backup file\n";
807    cout << "m\treturn to main menu\n";
808    cout << "o\tprint protective MBR data\n";
809    cout << "p\tprint the partition table\n";
810    cout << "q\tquit without saving changes\n";
811    cout << "t\ttransform BSD disklabel partition\n";
812    cout << "v\tverify disk\n";
813    cout << "w\twrite table to disk and exit\n";
814    cout << "x\textra functionality (experts only)\n";
815    cout << "?\tprint this menu\n";
816 } // GPTDataTextUI::ShowRecoveryCommands()
817 
818 // Accept an experts' menu command. Returns only after the user
819 // selects an exit command, such as 'w' or 'q'.
ExpertsMenu(string filename)820 void GPTDataTextUI::ExpertsMenu(string filename) {
821    GPTData secondDevice;
822    uint32_t temp1, temp2;
823    int goOn = 1;
824    string guidStr, device;
825    GUIDData aGUID;
826    ostringstream prompt;
827 
828    do {
829       cout << "\nExpert command (? for help): ";
830       switch (ReadString()[0]) {
831          case '\0':
832             goOn = cin.good();
833             break;
834          case 'a': case 'A':
835             if (GetPartRange(&temp1, &temp2) > 0)
836                SetAttributes(GetPartNum());
837             else
838                cout << "No partitions\n";
839             break;
840          case 'b': case 'B':
841             ReverseName(GetPartNum());
842             break;
843          case 'c': case 'C':
844             ChangeUniqueGuid();
845             break;
846          case 'd': case 'D':
847             cout << "Partitions will begin on " << GetAlignment()
848             << "-sector boundaries.\n";
849             break;
850          case 'e': case 'E':
851             cout << "Relocating backup data structures to the end of the disk\n";
852             MoveSecondHeaderToEnd();
853             break;
854          case 'f': case 'F':
855             RandomizeGUIDs();
856             break;
857          case 'g': case 'G':
858             cout << "Enter the disk's unique GUID ('R' to randomize): ";
859             guidStr = ReadString();
860             if ((guidStr.length() >= 32) || (guidStr[0] == 'R') || (guidStr[0] == 'r')) {
861                SetDiskGUID((GUIDData) guidStr);
862                cout << "The new disk GUID is " << GetDiskGUID() << "\n";
863             } else {
864                cout << "GUID is too short!\n";
865             } // if/else
866             break;
867          case 'h': case 'H':
868             RecomputeCHS();
869             break;
870          case 'i': case 'I':
871             ShowDetails();
872             break;
873          case 'j': case 'J':
874              MoveMainTable();
875              break;
876          case 'l': case 'L':
877             prompt.seekp(0);
878             prompt << "Enter the sector alignment value (1-" << MAX_ALIGNMENT << ", default = "
879                    << DEFAULT_ALIGNMENT << "): ";
880             temp1 = GetNumber(1, MAX_ALIGNMENT, DEFAULT_ALIGNMENT, prompt.str());
881             SetAlignment(temp1);
882             break;
883          case 'm': case 'M':
884             MainMenu(filename);
885             goOn = 0;
886             break;
887          case 'n': case 'N':
888             MakeProtectiveMBR();
889             break;
890          case 'o': case 'O':
891             DisplayMBRData();
892             break;
893          case 'p': case 'P':
894             DisplayGPTData();
895             break;
896          case 'q': case 'Q':
897             goOn = 0;
898             break;
899          case 'r': case 'R':
900             RecoveryMenu(filename);
901             goOn = 0;
902             break;
903          case 's': case 'S':
904             ResizePartitionTable();
905             break;
906          case 't': case 'T':
907             SwapPartitions();
908             break;
909          case 'u': case 'U':
910             cout << "Type device filename, or press <Enter> to exit: ";
911             device = ReadString();
912             if (device.length() > 0) {
913                secondDevice = *this;
914                secondDevice.SetDisk(device);
915                secondDevice.SaveGPTData(0);
916             } // if
917             break;
918          case 'v': case 'V':
919             Verify();
920             break;
921          case 'w': case 'W':
922             if (SaveGPTData() == 1) {
923                goOn = 0;
924             } // if
925             break;
926          case 'z': case 'Z':
927             if (DestroyGPTwPrompt() == 1) {
928                goOn = 0;
929             }
930             break;
931          default:
932             ShowExpertCommands();
933             break;
934       } // switch
935    } while (goOn);
936 } // GPTDataTextUI::ExpertsMenu()
937 
ShowExpertCommands(void)938 void GPTDataTextUI::ShowExpertCommands(void) {
939    cout << "a\tset attributes\n";
940    cout << "b\tbyte-swap a partition's name\n";
941    cout << "c\tchange partition GUID\n";
942    cout << "d\tdisplay the sector alignment value\n";
943    cout << "e\trelocate backup data structures to the end of the disk\n";
944    cout << "f\trandomize disk and partition unique GUIDs\n";
945    cout << "g\tchange disk GUID\n";
946    cout << "h\trecompute CHS values in protective/hybrid MBR\n";
947    cout << "i\tshow detailed information on a partition\n";
948    cout << "j\tmove the main partition table\n";
949    cout << "l\tset the sector alignment value\n";
950    cout << "m\treturn to main menu\n";
951    cout << "n\tcreate a new protective MBR\n";
952    cout << "o\tprint protective MBR data\n";
953    cout << "p\tprint the partition table\n";
954    cout << "q\tquit without saving changes\n";
955    cout << "r\trecovery and transformation options (experts only)\n";
956    cout << "s\tresize partition table\n";
957    cout << "t\ttranspose two partition table entries\n";
958    cout << "u\treplicate partition table on new device\n";
959    cout << "v\tverify disk\n";
960    cout << "w\twrite table to disk and exit\n";
961    cout << "z\tzap (destroy) GPT data structures and exit\n";
962    cout << "?\tprint this menu\n";
963 } // GPTDataTextUI::ShowExpertCommands()
964 
965 
966 
967 /********************************
968  *                              *
969  * Non-class support functions. *
970  *                              *
971  ********************************/
972 
973 // GetMBRTypeCode() doesn't really belong in the class, since it's MBR-
974 // specific, but it's also user I/O-related, so I want to keep it in
975 // this file....
976 
977 // Get an MBR type code from the user and return it
GetMBRTypeCode(int defType)978 int GetMBRTypeCode(int defType) {
979    string line;
980    int typeCode;
981 
982    cout.setf(ios::uppercase);
983    cout.fill('0');
984    do {
985       cout << "Enter an MBR hex code (default " << hex;
986       cout.width(2);
987       cout << defType << "): " << dec;
988       line = ReadString();
989       if (line[0] == '\0')
990          typeCode = defType;
991       else
992          typeCode = StrToHex(line, 0);
993    } while ((typeCode <= 0) || (typeCode > 255));
994    cout.fill(' ');
995    return typeCode;
996 } // GetMBRTypeCode
997 
998 #ifdef USE_UTF16
999 // Note: ReadUString() is here rather than in support.cc so that the ICU
1000 // libraries need not be linked to fixparts.
1001 
1002 // Reads a Unicode string from stdin, returning it as an ICU-style string.
1003 // Note that the returned string will NOT include the carriage return
1004 // entered by the user. Relies on the ICU constructor from a string
1005 // encoded in the current codepage to work.
ReadUString(void)1006 UnicodeString ReadUString(void) {
1007    return ReadString().c_str();
1008 } // ReadUString()
1009 #endif
1010 
1011