1 // sgdisk.cc
2 // Command-line-based version of gdisk. This program is named after sfdisk,
3 // and it can serve a similar role (easily scripted, etc.), but it's used
4 // strictly via command-line arguments, and it doesn't bear much resemblance
5 // to sfdisk in actual use.
6 //
7 // by Rod Smith, project began February 2009; sgdisk begun January 2010.
8
9 /* This program is copyright (c) 2009-2011 by Roderick W. Smith. It is distributed
10 under the terms of the GNU GPL version 2, as detailed in the COPYING file. */
11
12 #include <iostream>
13 #include <sstream>
14 #include <unistd.h>
15 #include <fcntl.h>
16
17 #include "gptcl.h"
18
19 using namespace std;
20
21 #define MAX_OPTIONS 50
22
23 /*
24 * Dump partition details in a machine readable format:
25 *
26 * DISK[mbr|gpt][guid]
27 * PART[n][type][guid]
28 */
ohos_dump(char * device)29 static int ohos_dump(char* device) {
30 BasicMBRData mbrData;
31 GPTData gptData;
32 GPTPart partData;
33 int numParts = 0;
34 stringstream res;
35
36 /* Silence noisy underlying library */
37 int stdout = dup(STDOUT_FILENO);
38 int silence = open("/dev/null", 0);
39 dup2(silence, STDOUT_FILENO);
40 dup2(silence, STDERR_FILENO);
41
42 if (!mbrData.ReadMBRData((string)device)) {
43 cerr << "Failed to read MBR" << endl;
44 return 8;
45 }
46
47 switch(mbrData.GetValidity()) {
48 case mbr:
49 res << "DISK mbr" << endl;
50 for (int i = 0; i < MAX_MBR_PARTS; i++) {
51 if(mbrData.GetLength(i) > 0) {
52 res << "PART " << (i + 1) << " " << hex << (int)mbrData.GetType(i) << dec << endl;
53 }
54 }
55 break;
56 case gpt:
57 gptData.JustLooking();
58 if(!gptData.LoadPartitions((string)device)) {
59 cerr << "Failed to read GPT" << endl;
60 return 9;
61 }
62
63 res << "DISK gpt " << gptData.GetDiskGUID() << endl;
64 numParts = gptData.GetNumParts();
65 for (int i = 0; i < numParts; i++) {
66 partData = gptData[i];
67 if (partData.GetFirstLBA() > 0) {
68 res << "PART " << (i + 1) << " " << partData.GetType() << " " << partData.GetUniqueGUID() << " "
69 << partData.GetDescription() << endl;
70 }
71 }
72 break;
73 default:
74 cerr << "Unknown partition table" << endl;
75 return 10;
76 }
77
78 /* Write our actual output */
79 string resString = res.str();
80 write(stdout, resString.c_str(), resString.length());
81 return 0;
82 }
83
main(int argc,char * argv[])84 int main(int argc, char *argv[]) {
85 for (int i = 0; i < argc; i++) {
86 if (!strcmp("--ohos-dump", argv[i])) {
87 return ohos_dump(argv[i + 1]);
88 }
89 }
90 GPTDataCL theGPT;
91 return theGPT.DoOptions(argc, argv);
92 } // main
93
94