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