blob: 92bfd77c4c471cbae95f100672f5fb29309c327e [file] [log] [blame]
srs5694e7b4ff92009-08-18 13:16:10 -04001// 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
Rod Smith44cda472018-07-05 09:07:58 -04006/* This program is copyright (c) 2009-2018 by Roderick W. Smith. It is distributed
srs5694221e0872009-08-29 15:00:31 -04007 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
8
srs5694e7b4ff92009-08-18 13:16:10 -04009#define __STDC_LIMIT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070010#ifndef __STDC_CONSTANT_MACROS
srs5694e7b4ff92009-08-18 13:16:10 -040011#define __STDC_CONSTANT_MACROS
Aurimas Liutikasfcad0602016-05-10 19:16:10 -070012#endif
srs5694e7b4ff92009-08-18 13:16:10 -040013
srs5694e7b4ff92009-08-18 13:16:10 -040014#include <stdio.h>
srs5694e7b4ff92009-08-18 13:16:10 -040015#include <stdint.h>
16#include <errno.h>
srs5694e4ac11e2009-08-31 10:13:04 -040017#include <fcntl.h>
srs5694fed16d02010-01-27 23:03:40 -050018#include <string.h>
srs5694e35eb1b2009-09-14 00:29:34 -040019#include <sys/stat.h>
srs5694fed16d02010-01-27 23:03:40 -050020#include <string>
21#include <iostream>
Haibo Huangc83113b2020-02-10 11:00:14 -080022#include <inttypes.h>
srs569408bb0da2010-02-19 17:19:55 -050023#include <sstream>
srs5694e7b4ff92009-08-18 13:16:10 -040024#include "support.h"
25
26#include <sys/types.h>
27
srs56945d58fe02010-01-03 20:57:08 -050028// As of 1/2010, BLKPBSZGET is very new, so I'm explicitly defining it if
29// it's not already defined. This should become unnecessary in the future.
30// Note that this is a Linux-only ioctl....
31#ifndef BLKPBSZGET
32#define BLKPBSZGET _IO(0x12,123)
33#endif
34
srs5694e7b4ff92009-08-18 13:16:10 -040035using namespace std;
36
srs56945a608532011-03-17 13:53:01 -040037// Reads a string from stdin, returning it as a C++-style string.
38// Note that the returned string will NOT include the carriage return
39// entered by the user.
Roderick W. Smith54f8fb12015-03-17 19:46:05 -040040#ifdef EFI
41extern int __sscanf( const char * str , const char * format , ... ) ;
42string ReadString(void) {
43 string inString;
44 char efiString[256];
Roderick W. Smith080ff552015-10-18 13:43:03 -040045 int stringLength;
Roderick W. Smith54f8fb12015-03-17 19:46:05 -040046
Roderick W. Smith080ff552015-10-18 13:43:03 -040047 if (fgets(efiString, 255, stdin) != NULL) {
48 stringLength = strlen(efiString);
49 if ((stringLength > 0) && (efiString[stringLength - 1] == '\n'))
50 efiString[stringLength - 1] = '\0';
51 inString = efiString;
52 } else {
53 inString = "";
54 }
Roderick W. Smith54f8fb12015-03-17 19:46:05 -040055 return inString;
56} // ReadString()
57#else
srs56945a608532011-03-17 13:53:01 -040058string ReadString(void) {
59 string inString;
60
Rosen Penev185f73b2019-10-07 15:41:53 -070061 cout << flush;
srs56945a608532011-03-17 13:53:01 -040062 getline(cin, inString);
srs5694a6297b82012-03-25 16:13:16 -040063 if (!cin.good())
64 exit(5);
srs56945a608532011-03-17 13:53:01 -040065 return inString;
66} // ReadString()
Roderick W. Smith54f8fb12015-03-17 19:46:05 -040067#endif
srs5694bf8950c2011-03-12 01:23:12 -050068
srs5694e7b4ff92009-08-18 13:16:10 -040069// Get a numeric value from the user, between low and high (inclusive).
70// Keeps looping until the user enters a value within that range.
71// If user provides no input, def (default value) is returned.
72// (If def is outside of the low-high range, an explicit response
73// is required.)
Rod Smith503e9ad2017-07-21 21:48:13 -040074uint64_t GetNumber(uint64_t low, uint64_t high, uint64_t def, const string & prompt) {
75 uint64_t response, num;
srs5694e7b4ff92009-08-18 13:16:10 -040076 char line[255];
77
78 if (low != high) { // bother only if low and high differ...
srs56940873e9d2010-10-07 13:00:45 -040079 do {
Rosen Penev31d1f452019-10-07 15:39:14 -070080 cout << prompt << flush;
srs5694fed16d02010-01-27 23:03:40 -050081 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -040082 if (!cin.good())
83 exit(5);
Haibo Huangc83113b2020-02-10 11:00:14 -080084 num = sscanf(line, "%" SCNu64, &response);
srs5694e7b4ff92009-08-18 13:16:10 -040085 if (num == 1) { // user provided a response
86 if ((response < low) || (response > high))
srs5694fed16d02010-01-27 23:03:40 -050087 cout << "Value out of range\n";
srs5694e7b4ff92009-08-18 13:16:10 -040088 } else { // user hit enter; return default
89 response = def;
90 } // if/else
srs56940873e9d2010-10-07 13:00:45 -040091 } while ((response < low) || (response > high));
srs5694e7b4ff92009-08-18 13:16:10 -040092 } else { // low == high, so return this value
srs5694fed16d02010-01-27 23:03:40 -050093 cout << "Using " << low << "\n";
srs5694e7b4ff92009-08-18 13:16:10 -040094 response = low;
95 } // else
96 return (response);
97} // GetNumber()
98
99// Gets a Y/N response (and converts lowercase to uppercase)
100char GetYN(void) {
srs56940873e9d2010-10-07 13:00:45 -0400101 char response;
srs56945a608532011-03-17 13:53:01 -0400102 string line;
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500103 bool again = 0 ;
srs5694e7b4ff92009-08-18 13:16:10 -0400104
srs56940873e9d2010-10-07 13:00:45 -0400105 do {
Roderick W. Smith84aaff62014-02-17 16:17:11 -0500106 if ( again ) { cout << "Your option? " ; }
107 again = 1 ;
Rosen Penev5542b162019-10-07 15:36:31 -0700108 cout << "(Y/N): " << flush;
srs56945a608532011-03-17 13:53:01 -0400109 line = ReadString();
srs569401f7f082011-03-15 23:53:31 -0400110 response = toupper(line[0]);
srs56940873e9d2010-10-07 13:00:45 -0400111 } while ((response != 'Y') && (response != 'N'));
srs5694e7b4ff92009-08-18 13:16:10 -0400112 return response;
113} // GetYN(void)
114
srs5694e4ac11e2009-08-31 10:13:04 -0400115// Obtains a sector number, between low and high, from the
srs5694e7b4ff92009-08-18 13:16:10 -0400116// user, accepting values prefixed by "+" to add sectors to low,
srs56940873e9d2010-10-07 13:00:45 -0400117// or the same with "K", "M", "G", "T", or "P" as suffixes to add
118// kilobytes, megabytes, gigabytes, terabytes, or petabytes,
119// respectively. If a "-" prefix is used, use the high value minus
120// the user-specified number of sectors (or KiB, MiB, etc.). Use the
121// def value as the default if the user just hits Enter. The sSize is
122// the sector size of the device.
srs5694df9d3632011-01-08 18:33:24 -0500123uint64_t GetSectorNum(uint64_t low, uint64_t high, uint64_t def, uint64_t sSize,
124 const string & prompt) {
125 uint64_t response;
126 char line[255];
srs56940873e9d2010-10-07 13:00:45 -0400127
128 do {
srs5694fed16d02010-01-27 23:03:40 -0500129 cout << prompt;
130 cin.getline(line, 255);
srs5694a6297b82012-03-25 16:13:16 -0400131 if (!cin.good())
132 exit(5);
srs569401f7f082011-03-15 23:53:31 -0400133 response = IeeeToInt(line, sSize, low, high, def);
srs56940873e9d2010-10-07 13:00:45 -0400134 } while ((response < low) || (response > high));
srs569455d92612010-03-07 22:16:07 -0500135 return response;
srs5694e4ac11e2009-08-31 10:13:04 -0400136} // GetSectorNum()
srs5694e7b4ff92009-08-18 13:16:10 -0400137
srs569401f7f082011-03-15 23:53:31 -0400138// Convert an IEEE-1541-2002 value (K, M, G, T, P, or E) to its equivalent in
srs5694df9d3632011-01-08 18:33:24 -0500139// number of sectors. If no units are appended, interprets as the number
140// of sectors; otherwise, interprets as number of specified units and
141// converts to sectors. For instance, with 512-byte sectors, "1K" converts
142// to 2. If value includes a "+", adds low and subtracts 1; if SIValue
srs569401f7f082011-03-15 23:53:31 -0400143// inclues a "-", subtracts from high. If IeeeValue is empty, returns def.
srs56946aae2a92011-06-10 01:16:51 -0400144// Returns final sector value. In case inValue is invalid, returns 0 (a
srs5694a17fe692011-09-10 20:30:20 -0400145// sector value that's always in use on GPT and therefore invalid); and if
srs56946aae2a92011-06-10 01:16:51 -0400146// inValue works out to something outside the range low-high, returns the
147// computed value; the calling function is responsible for checking the
148// validity of this value.
149// NOTE: There's a difference in how GCC and VC++ treat oversized values
150// (say, "999999999999999999999") read via the ">>" operator; GCC turns
151// them into the maximum value for the type, whereas VC++ turns them into
152// 0 values. The result is that IeeeToInt() returns UINT64_MAX when
153// compiled with GCC (and so the value is rejected), whereas when VC++
154// is used, the default value is returned.
srs569401f7f082011-03-15 23:53:31 -0400155uint64_t IeeeToInt(string inValue, uint64_t sSize, uint64_t low, uint64_t high, uint64_t def) {
156 uint64_t response = def, bytesPerUnit = 1, mult = 1, divide = 1;
157 size_t foundAt = 0;
William Grant5b2c6c82015-06-19 19:55:27 +1000158 char suffix = ' ', plusFlag = ' ';
srs569401f7f082011-03-15 23:53:31 -0400159 string suffixes = "KMGTPE";
srs56946aae2a92011-06-10 01:16:51 -0400160 int badInput = 0; // flag bad input; once this goes to 1, other values are irrelevant
srs5694df9d3632011-01-08 18:33:24 -0500161
162 if (sSize == 0) {
163 sSize = SECTOR_SIZE;
Roderick W. Smithf6948032014-03-29 00:27:33 -0400164 cerr << "Bug: Sector size invalid in IeeeToInt()!\n";
srs5694df9d3632011-01-08 18:33:24 -0500165 } // if
166
167 // Remove leading spaces, if present
srs569401f7f082011-03-15 23:53:31 -0400168 while (inValue[0] == ' ')
169 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500170
srs569401f7f082011-03-15 23:53:31 -0400171 // If present, flag and remove leading plus or minus sign
172 if ((inValue[0] == '+') || (inValue[0] == '-')) {
173 plusFlag = inValue[0];
174 inValue.erase(0, 1);
srs5694df9d3632011-01-08 18:33:24 -0500175 } // if
176
177 // Extract numeric response and, if present, suffix
srs569401f7f082011-03-15 23:53:31 -0400178 istringstream inString(inValue);
srs56946aae2a92011-06-10 01:16:51 -0400179 if (((inString.peek() < '0') || (inString.peek() > '9')) && (inString.peek() != -1))
180 badInput = 1;
181 inString >> response >> suffix;
182 suffix = toupper(suffix);
183
184 // If no response, or if response == 0, use default (def)
185 if ((inValue.length() == 0) || (response == 0)) {
186 response = def;
187 suffix = ' ';
188 plusFlag = ' ';
189 } // if
190
191 // Find multiplication and division factors for the suffix
192 foundAt = suffixes.find(suffix);
193 if (foundAt != string::npos) {
194 bytesPerUnit = UINT64_C(1) << (10 * (foundAt + 1));
195 mult = bytesPerUnit / sSize;
196 divide = sSize / bytesPerUnit;
197 } // if
198
199 // Adjust response based on multiplier and plus flag, if present
200 if (mult > 1) {
201 if (response > (UINT64_MAX / mult))
202 badInput = 1;
203 else
srs569401f7f082011-03-15 23:53:31 -0400204 response *= mult;
srs56946aae2a92011-06-10 01:16:51 -0400205 } else if (divide > 1) {
srs569401f7f082011-03-15 23:53:31 -0400206 response /= divide;
srs56946aae2a92011-06-10 01:16:51 -0400207 } // if/elseif
208
209 if (plusFlag == '+') {
210 // Recompute response based on low part of range (if default == high
211 // value, which should be the case when prompting for the end of a
212 // range) or the defaut value (if default != high, which should be
213 // the case for the first sector of a partition).
214 if (def == high) {
215 if (response > 0)
216 response--;
217 if (response > (UINT64_MAX - low))
218 badInput = 1;
219 else
220 response = response + low;
221 } else {
222 if (response > (UINT64_MAX - def))
223 badInput = 1;
srs569401f7f082011-03-15 23:53:31 -0400224 else
225 response = response + def;
srs56946aae2a92011-06-10 01:16:51 -0400226 } // if/else
227 } else if (plusFlag == '-') {
228 if (response > high)
229 badInput = 1;
230 else
srs569401f7f082011-03-15 23:53:31 -0400231 response = high - response;
srs56946aae2a92011-06-10 01:16:51 -0400232 } // if
233
234 if (badInput)
235 response = UINT64_C(0);
srs5694df9d3632011-01-08 18:33:24 -0500236
237 return response;
srs569401f7f082011-03-15 23:53:31 -0400238} // IeeeToInt()
srs5694df9d3632011-01-08 18:33:24 -0500239
srs569401f7f082011-03-15 23:53:31 -0400240// Takes a size and converts this to a size in IEEE-1541-2002 units (KiB, MiB,
241// GiB, TiB, PiB, or EiB), returned in C++ string form. The size is either in
242// units of the sector size or, if that parameter is omitted, in bytes.
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400243// (sectorSize defaults to 1). Note that this function uses peculiar
244// manual computation of decimal value rather than simply setting
245// theValue.precision() because this isn't possible using the available
246// EFI library.
srs569401f7f082011-03-15 23:53:31 -0400247string BytesToIeee(uint64_t size, uint32_t sectorSize) {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400248 uint64_t sizeInIeee;
249 uint64_t previousIeee;
250 float decimalIeee;
Roderick W. Smith54f8fb12015-03-17 19:46:05 -0400251 uint64_t index = 0;
srs56946aae2a92011-06-10 01:16:51 -0400252 string units, prefixes = " KMGTPEZ";
srs569408bb0da2010-02-19 17:19:55 -0500253 ostringstream theValue;
srs5694e7b4ff92009-08-18 13:16:10 -0400254
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400255 sizeInIeee = previousIeee = size * (uint64_t) sectorSize;
256 while ((sizeInIeee > 1024) && (index < (prefixes.length() - 1))) {
srs569401f7f082011-03-15 23:53:31 -0400257 index++;
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400258 previousIeee = sizeInIeee;
259 sizeInIeee /= 1024;
srs569401f7f082011-03-15 23:53:31 -0400260 } // while
srs569401f7f082011-03-15 23:53:31 -0400261 if (prefixes[index] == ' ') {
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400262 theValue << sizeInIeee << " bytes";
srs5694fed16d02010-01-27 23:03:40 -0500263 } else {
srs569401f7f082011-03-15 23:53:31 -0400264 units = " iB";
265 units[1] = prefixes[index];
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400266 decimalIeee = ((float) previousIeee -
267 ((float) sizeInIeee * 1024.0) + 51.2) / 102.4;
268 if (decimalIeee >= 10.0) {
269 decimalIeee = 0.0;
270 sizeInIeee++;
271 }
272 theValue << sizeInIeee << "." << (uint32_t) decimalIeee << units;
srs5694fed16d02010-01-27 23:03:40 -0500273 } // if/else
srs569408bb0da2010-02-19 17:19:55 -0500274 return theValue.str();
Roderick W. Smith1f7822e2014-03-28 23:54:21 -0400275} // BytesToIeee()
srs5694e7b4ff92009-08-18 13:16:10 -0400276
srs56946699b012010-02-04 00:55:30 -0500277// Converts two consecutive characters in the input string into a
278// number, interpreting the string as a hexadecimal number, starting
279// at the specified position.
280unsigned char StrToHex(const string & input, unsigned int position) {
281 unsigned char retval = 0x00;
282 unsigned int temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400283
srs56945a608532011-03-17 13:53:01 -0400284 if (input.length() > position) {
srs56946699b012010-02-04 00:55:30 -0500285 sscanf(input.substr(position, 2).c_str(), "%x", &temp);
286 retval = (unsigned char) temp;
srs5694e7b4ff92009-08-18 13:16:10 -0400287 } // if
srs56946699b012010-02-04 00:55:30 -0500288 return retval;
289} // StrToHex()
srs5694e7b4ff92009-08-18 13:16:10 -0400290
srs56940873e9d2010-10-07 13:00:45 -0400291// Returns 1 if input can be interpreted as a hexadecimal number --
292// all characters must be spaces, digits, or letters A-F (upper- or
srs56946aae2a92011-06-10 01:16:51 -0400293// lower-case), with at least one valid hexadecimal digit; with the
294// exception of the first two characters, which may be "0x"; otherwise
srs56940873e9d2010-10-07 13:00:45 -0400295// returns 0.
srs56946aae2a92011-06-10 01:16:51 -0400296int IsHex(string input) {
srs56940873e9d2010-10-07 13:00:45 -0400297 int isHex = 1, foundHex = 0, i;
298
srs56946aae2a92011-06-10 01:16:51 -0400299 if (input.substr(0, 2) == "0x")
300 input.erase(0, 2);
srs56940873e9d2010-10-07 13:00:45 -0400301 for (i = 0; i < (int) input.length(); i++) {
302 if ((input[i] < '0') || (input[i] > '9')) {
303 if ((input[i] < 'A') || (input[i] > 'F')) {
304 if ((input[i] < 'a') || (input[i] > 'f')) {
305 if ((input[i] != ' ') && (input[i] != '\n')) {
306 isHex = 0;
307 }
308 } else foundHex = 1;
309 } else foundHex = 1;
310 } else foundHex = 1;
311 } // for
312 if (!foundHex)
313 isHex = 0;
314 return isHex;
315} // IsHex()
316
srs56942a9f5da2009-08-26 00:48:01 -0400317// Return 1 if the CPU architecture is little endian, 0 if it's big endian....
318int IsLittleEndian(void) {
319 int littleE = 1; // assume little-endian (Intel-style)
320 union {
321 uint32_t num;
322 unsigned char uc[sizeof(uint32_t)];
323 } endian;
324
325 endian.num = 1;
326 if (endian.uc[0] != (unsigned char) 1) {
327 littleE = 0;
328 } // if
329 return (littleE);
330} // IsLittleEndian()
331
332// Reverse the byte order of theValue; numBytes is number of bytes
srs5694221e0872009-08-29 15:00:31 -0400333void ReverseBytes(void* theValue, int numBytes) {
srs5694fed16d02010-01-27 23:03:40 -0500334 char* tempValue = NULL;
srs56942a9f5da2009-08-26 00:48:01 -0400335 int i;
336
srs5694cb76c672010-02-11 22:22:22 -0500337 tempValue = new char [numBytes];
srs5694fed16d02010-01-27 23:03:40 -0500338 if (tempValue != NULL) {
339 memcpy(tempValue, theValue, numBytes);
340 for (i = 0; i < numBytes; i++)
341 ((char*) theValue)[i] = tempValue[numBytes - i - 1];
srs5694cb76c672010-02-11 22:22:22 -0500342 delete[] tempValue;
srs56946aae2a92011-06-10 01:16:51 -0400343 } else {
344 cerr << "Could not allocate memory in ReverseBytes()! Terminating\n";
345 exit(1);
346 } // if/else
srs56942a9f5da2009-08-26 00:48:01 -0400347} // ReverseBytes()
srs5694a17fe692011-09-10 20:30:20 -0400348
349// On Windows, display a warning and ask whether to continue. If the user elects
350// not to continue, exit immediately.
351void WinWarning(void) {
352 #ifdef _WIN32
353 cout << "\a************************************************************************\n"
Roderick W. Smitha9203982014-03-29 00:45:59 -0400354 << "Most versions of Windows cannot boot from a GPT disk except on a UEFI-based\n"
355 << "computer, and most varieties prior to Vista cannot read GPT disks. Therefore,\n"
356 << "you should exit now unless you understand the implications of converting MBR\n"
357 << "to GPT or creating a new GPT disk layout!\n"
358 << "************************************************************************\n\n";
srs5694a17fe692011-09-10 20:30:20 -0400359 cout << "Are you SURE you want to continue? ";
360 if (GetYN() != 'Y')
361 exit(0);
362 #endif
363} // WinWarning()