xref: /aosp_15_r20/external/gptfdisk/support.cc (revision 57696d54d05c64fd1b1787f8371dbcf104911cfb)
1 // support.cc
2 // Non-class support functions for gdisk program.
3 // Primarily by Rod Smith, February 2009, but with a few functions
4 // copied from other sources (see attributions below).
5 
6 /* This program is copyright (c) 2009-2022 by Roderick W. Smith. It is distributed
7   under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8 
9 #define __STDC_LIMIT_MACROS
10 #define __STDC_CONSTANT_MACROS
11 #define __STDC_FORMAT_MACROS
12 
13 #include <inttypes.h>
14 #include <stdio.h>
15 #include <stdint.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <string.h>
19 #include <sys/stat.h>
20 #include <string>
21 #include <cctype>
22 #include <algorithm>
23 #include <iostream>
24 #include <sstream>
25 #include "support.h"
26 
27 #include <sys/types.h>
28 
29 // As of 1/2010, BLKPBSZGET is very new, so I'm explicitly defining it if
30 // it's not already defined. This should become unnecessary in the future.
31 // Note that this is a Linux-only ioctl....
32 #ifndef BLKPBSZGET
33 #define BLKPBSZGET _IO(0x12,123)
34 #endif
35 
36 using namespace std;
37 
38 // Reads a string from stdin, returning it as a C++-style string.
39 // Note that the returned string will NOT include the carriage return
40 // entered by the user.
41 #ifdef EFI
42 extern int __sscanf( const char * str , const char * format , ... ) ;
ReadString(void)43 string ReadString(void) {
44    string inString;
45    char efiString[256];
46    int stringLength;
47 
48    if (fgets(efiString, 255, stdin) != NULL) {
49       stringLength = strlen(efiString);
50       if ((stringLength > 0) && (efiString[stringLength - 1] == '\n'))
51           efiString[stringLength - 1] = '\0';
52       inString = efiString;
53    } else {
54       inString = "";
55    }
56    return inString;
57 } // ReadString()
58 #else
ReadString(void)59 string ReadString(void) {
60    string inString;
61 
62    cout << flush;
63    getline(cin, inString);
64    if (!cin.good())
65       exit(5);
66    return inString;
67 } // ReadString()
68 #endif
69 
70 // Get a numeric value from the user, between low and high (inclusive).
71 // Keeps looping until the user enters a value within that range.
72 // If user provides no input, def (default value) is returned.
73 // (If def is outside of the low-high range, an explicit response
74 // is required.)
GetNumber(uint64_t low,uint64_t high,uint64_t def,const string & prompt)75 uint64_t GetNumber(uint64_t low, uint64_t high, uint64_t def, const string & prompt) {
76    uint64_t response, num;
77    char line[255];
78 
79    if (low != high) { // bother only if low and high differ...
80       do {
81          cout << prompt << flush;
82          cin.getline(line, 255);
83          if (!cin.good())
84             exit(5);
85          num = sscanf(line, "%" PRIu64, &response);
86          if (num == 1) { // user provided a response
87             if ((response < low) || (response > high))
88                cout << "Value out of range\n";
89          } else { // user hit enter; return default
90             response = def;
91          } // if/else
92       } while ((response < low) || (response > high));
93    } else { // low == high, so return this value
94       cout << "Using " << low << "\n";
95       response = low;
96    } // else
97    return (response);
98 } // GetNumber()
99 
100 // Gets a Y/N response (and converts lowercase to uppercase)
GetYN(void)101 char GetYN(void) {
102    char response;
103    string line;
104    bool again = 0 ;
105 
106    do {
107       if ( again ) { cout << "Your option? " ; }
108       again = 1 ;
109       cout << "(Y/N): " << flush;
110       line = ReadString();
111       response = toupper(line[0]);
112    } while ((response != 'Y') && (response != 'N'));
113    return response;
114 } // GetYN(void)
115 
116 // Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
117 // number of sectors. If no units are appended, interprets as the number
118 // of sectors; otherwise, interprets as number of specified units and
119 // converts to sectors. For instance, with 512-byte sectors, "1K" converts
120 // to 2. If value includes a "+", adds low and subtracts 1; if inValue
121 // inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
122 // Returns final sector value. In case inValue is invalid, returns 0 (a
123 // sector value that's always in use on GPT and therefore invalid); and if
124 // inValue works out to something outside the range low-high, returns the
125 // computed value; the calling function is responsible for checking the
126 // validity of this value.
127 // If inValue contains a decimal number (e.g., "9.5G"), quietly truncate it
128 // (to "9G" in this example).
129 // NOTE: There's a difference in how GCC and VC++ treat oversized values
130 // (say, "999999999999999999999") read via the ">>" operator; GCC turns
131 // them into the maximum value for the type, whereas VC++ turns them into
132 // 0 values. The result is that IeeeToInt() returns UINT64_MAX when
133 // compiled with GCC (and so the value is rejected), whereas when VC++
134 // is used, the default value is returned.
IeeeToInt(string inValue,uint64_t sSize,uint64_t low,uint64_t high,uint32_t sectorAlignment,uint64_t def)135 uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint32_t sectorAlignment, uint64_t def) {
136    uint64_t response = def, bytesPerUnit, mult = 1, divide = 1;
137    size_t foundAt = 0;
138    char suffix = ' ', plusFlag = ' ';
139    string suffixes = "KMGTPE";
140    int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
141 
142    if (sSize == 0) {
143       sSize = SECTOR_SIZE;
144       cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
145    } // if
146 
147    // Remove leading spaces, if present
148    while (inValue[0] == ' ')
149       inValue.erase(0, 1);
150 
151    // If present, flag and remove leading plus or minus sign
152    if ((inValue[0] == '+') || (inValue[0] == '-')) {
153       plusFlag = inValue[0];
154       inValue.erase(0, 1);
155    } // if
156 
157    // Extract numeric response and, if present, suffix
158    istringstream inString(inValue);
159    if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
160       badInput = 1;
161    inString >> response >> suffix;
162    suffix = toupper(suffix);
163    foundAt = suffixes.find(suffix);
164    // If suffix is invalid, try to find a valid one. Done because users
165    // sometimes enter decimal numbers; when they do, suffix becomes
166    // '.', and we need to truncate the number and find the real suffix.
167    while (foundAt > (suffixes.length() - 1) && inString.peek() != -1) {
168       inString >> suffix;
169       foundAt = suffixes.find(suffix);
170       suffix = toupper(suffix);
171    }
172 
173    // If no response, or if response == 0, use default (def)
174    if ((inValue.length() == 0) || (response == 0)) {
175       response = def;
176       suffix = ' ';
177       plusFlag = ' ';
178    } // if
179 
180    // Find multiplication and division factors for the suffix
181    if (foundAt != string::npos) {
182       bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
183       mult = bytesPerUnit / sSize;
184       divide = sSize / bytesPerUnit;
185    } // if
186 
187    // Adjust response based on multiplier and plus flag, if present
188    if (mult > 1) {
189       if (response > (UINT64_MAX / mult))
190          badInput = 1;
191       else
192          response *= mult;
193    } else if (divide > 1) {
194          response /= divide;
195    } // if/elseif
196 
197    if (plusFlag == '+') {
198       // Recompute response based on low part of range (if default is within
199       // sectorAlignment sectors of high, which should be the case when
200       // prompting for the end of a range) or the defaut value (if default is
201       // further away from the high value, which should be the case for the
202       // first sector of a partition).
203       if ((high - def) < sectorAlignment) {
204          if (response > 0)
205             response--;
206          if (response > (UINT64_MAX - low))
207             badInput = 1;
208          else
209             response = response + low;
210       } else {
211          if (response > (UINT64_MAX - def))
212             badInput = 1;
213          else
214             response = response + def;
215       } // if/else
216    } else if (plusFlag == '-') {
217       if (response > high)
218          badInput = 1;
219       else
220          response = high - response;
221    } // if
222 
223    if (badInput)
224       response = UINT64_C(0);
225 
226    return response;
227 } // IeeeToInt()
228 
229 // Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
230 // GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
231 // units of the sector size or, if that parameter is omitted, in bytes.
232 // (sectorSize defaults to 1). Note that this function uses peculiar
233 // manual computation of decimal value rather than simply setting
234 // theValue.precision() because this isn't possible using the available
235 // EFI library.
BytesToIeee(uint64_t size,uint32_t sectorSize)236 string BytesToIeee(uint64_t size, uint32_t sectorSize) {
237    uint64_t sizeInIeee;
238    uint64_t previousIeee;
239    float decimalIeee;
240    uint64_t index = 0;
241    string units, prefixes = " KMGTPEZ";
242    ostringstream theValue;
243 
244    sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
245    while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
246       index++;
247       previousIeee = sizeInIeee;
248       sizeInIeee /= 1024;
249    } // while
250    if (prefixes[index] == ' ') {
251       theValue << sizeInIeee << " bytes";
252    } else {
253       units = "  iB";
254       units[1] = prefixes[index];
255       decimalIeee = ((float) previousIeee -
256                      ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
257       if (decimalIeee >= 10.0) {
258          decimalIeee = 0.0;
259          sizeInIeee++;
260       }
261       theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
262    } // if/else
263    return theValue.str();
264 } // BytesToIeee()
265 
266 // Converts two consecutive characters in the input string into a
267 // number, interpreting the string as a hexadecimal number, starting
268 // at the specified position.
StrToHex(const string & input,unsigned int position)269 unsigned char StrToHex(const string & input, unsigned int position) {
270    unsigned char retval = 0x00;
271    unsigned int temp;
272 
273    if (input.length() > position) {
274       sscanf(input.substr(position, 2).c_str(), "%x", &temp);
275       retval = (unsigned char) temp;
276    } // if
277    return retval;
278 } // StrToHex()
279 
280 // Returns 1 if input can be interpreted as a hexadecimal number --
281 // all characters must be spaces, digits, or letters A-F (upper- or
282 // lower-case), with at least one valid hexadecimal digit; with the
283 // exception of the first two characters, which may be "0x"; otherwise
284 // returns 0.
IsHex(string input)285 int IsHex(string input) {
286    int isHex = 1, foundHex = 0, i;
287 
288    if (input.substr(0, 2) == "0x")
289       input.erase(0, 2);
290    for (i = 0; i < (int) input.length(); i++) {
291       if ((input[i] < '0') || (input[i] > '9')) {
292          if ((input[i] < 'A') || (input[i] > 'F')) {
293             if ((input[i] < 'a') || (input[i] > 'f')) {
294                if ((input[i] != ' ') && (input[i] != '\n')) {
295                   isHex = 0;
296                }
297             } else foundHex = 1;
298          } else foundHex = 1;
299       } else foundHex = 1;
300    } // for
301    if (!foundHex)
302       isHex = 0;
303    return isHex;
304 } // IsHex()
305 
306 // Return 1 if the CPU architecture is little endian, 0 if it's big endian....
IsLittleEndian(void)307 int IsLittleEndian(void) {
308    int littleE = 1; // assume little-endian (Intel-style)
309    union {
310       uint32_t num;
311       unsigned char uc[sizeof(uint32_t)];
312    } endian;
313 
314    endian.num = 1;
315    if (endian.uc[0] != (unsigned char) 1) {
316       littleE = 0;
317    } // if
318    return (littleE);
319 } // IsLittleEndian()
320 
321 // Reverse the byte order of theValue; numBytes is number of bytes
ReverseBytes(void * theValue,int numBytes)322 void ReverseBytes(void* theValue, int numBytes) {
323    char* tempValue = NULL;
324    int i;
325 
326    tempValue = new char [numBytes];
327    if (tempValue != NULL) {
328       memcpy(tempValue, theValue, numBytes);
329       for (i = 0; i < numBytes; i++)
330          ((char*) theValue)[i] = tempValue[numBytes - i - 1];
331       delete[] tempValue;
332    } else {
333       cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
334       exit(1);
335    } // if/else
336 } // ReverseBytes()
337 
338 // On Windows, display a warning and ask whether to continue. If the user elects
339 // not to continue, exit immediately.
WinWarning(void)340 void WinWarning(void) {
341    #ifdef _WIN32
342    cout << "\a************************************************************************\n"
343         << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
344         << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
345         << "you should exit now unless you understand the implications of converting MBR\n"
346         << "to GPT or creating a new GPT disk layout!\n"
347         << "************************************************************************\n\n";
348    cout << "Are you SURE you want to continue? ";
349    if (GetYN() != 'Y')
350       exit(0);
351    #endif
352 } // WinWarning()
353 
354 // Returns the input string in lower case
ToLower(const string & input)355 string ToLower(const string& input) {
356    string lower = input; // allocate correct size through copy
357 
358    transform(input.begin(), input.end(), lower.begin(), ::tolower);
359    return lower;
360 } // ToLower()
361