2 * Copyright (c) 2000-2005 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
23 cc -o nvram nvram.c -framework CoreFoundation -framework IOKit -Wall
27 #include <IOKit/IOKitLib.h>
28 #include <IOKit/IOKitKeys.h>
29 #include <CoreFoundation/CoreFoundation.h>
31 #include <mach/mach_error.h>
34 static void UsageMessage(char *message
);
35 static void ParseFile(char *fileName
);
36 static void ParseXMLFile(char *fileName
);
37 static void SetOrGetOFVariable(char *str
);
38 static kern_return_t
GetOFVariable(char *name
, CFStringRef
*nameRef
,
40 static kern_return_t
SetOFVariable(char *name
, char *value
);
41 static void DeleteOFVariable(char *name
);
42 static void PrintOFVariables(void);
43 static void PrintOFVariable(const void *key
,const void *value
,void *context
);
44 static void SetOFVariableFromFile(const void *key
, const void *value
, void *context
);
45 static void ClearOFVariables(void);
46 static void ClearOFVariable(const void *key
,const void *value
,void *context
);
47 static CFTypeRef
ConvertValueToCFTypeRef(CFTypeID typeID
, char *value
);
50 static char *gToolName
;
51 static io_registry_entry_t gOptionsRef
;
55 int main(int argc
, char **argv
)
58 char *str
, errorMessage
[256];
60 mach_port_t masterPort
;
62 // Get the name of the command.
63 gToolName
= strrchr(argv
[0], '/');
64 if (gToolName
!= 0) gToolName
++;
65 else gToolName
= argv
[0];
67 result
= IOMasterPort(bootstrap_port
, &masterPort
);
68 if (result
!= KERN_SUCCESS
) {
69 errx(1, "Error getting the IOMaster port: %s",
70 mach_error_string(result
));
73 gOptionsRef
= IORegistryEntryFromPath(masterPort
, "IODeviceTree:/options");
74 if (gOptionsRef
== 0) {
75 errx(1, "nvram is not supported on this system");
78 for (cnt
= 1; cnt
< argc
; cnt
++) {
80 if (str
[0] == '-' && str
[1] != 0) {
82 for (str
+= 1 ; *str
; str
++) {
94 if (cnt
< argc
&& *argv
[cnt
] != '-') {
97 UsageMessage("missing filename");
103 if (cnt
< argc
&& *argv
[cnt
] != '-') {
104 DeleteOFVariable(argv
[cnt
]);
106 UsageMessage("missing name");
115 strcpy(errorMessage
, "no such option as --");
116 errorMessage
[strlen(errorMessage
)-1] = *str
;
117 UsageMessage(errorMessage
);
121 // Other arguments will be firmware variable requests.
122 SetOrGetOFVariable(str
);
126 IOObjectRelease(gOptionsRef
);
131 // UsageMessage(message)
133 // Print the usage information and exit.
135 static void UsageMessage(char *message
)
137 warnx("(usage: %s)", message
);
139 printf("%s [-x] [-p] [-f filename] [-d name] name[=value] ...\n", gToolName
);
140 printf("\t-x use XML format for printing or reading variables\n");
141 printf("\t (must appear before -p or -f)\n");
142 printf("\t-p print all firmware variables\n");
143 printf("\t-f set firmware variables from a text file\n");
144 printf("\t-d delete the named variable\n");
145 printf("\t-c delete all variables\n");
146 printf("\tname=value set named variable\n");
147 printf("\tname print variable\n");
148 printf("Note that arguments and options are executed in order.\n");
154 // States for ParseFile.
165 kMaxStringSize
= 0x800,
170 // ParseFile(fileName)
172 // Open and parse the specified file.
174 static void ParseFile(char *fileName
)
176 long state
, tc
, ni
= 0, vi
= 0;
177 char name
[kMaxNameSize
];
178 char value
[kMaxStringSize
];
183 ParseXMLFile(fileName
);
187 patches
= fopen(fileName
, "r");
189 err(1, "Couldn't open patch file - '%s'", fileName
);
192 state
= kFirstColumn
;
193 while ((tc
= getc(patches
)) != EOF
) {
194 if(ni
==(kMaxNameSize
-1))
195 errx(1, "Name exceeded max length of %d", kMaxNameSize
);
196 if(vi
==(kMaxStringSize
-1))
197 errx(1, "Value exceeded max length of %d", kMaxStringSize
);
203 state
= kScanComment
;
204 } else if (tc
== '\n') {
205 // state stays kFirstColumn.
206 } else if (isspace(tc
)) {
209 state
= kCollectName
;
216 state
= kFirstColumn
;
218 // state stays kScanComment.
224 state
= kFirstColumn
;
225 } else if (isspace(tc
)) {
226 // state stays kFindName.
228 state
= kCollectName
;
236 warnx("Name must be followed by white space - '%s'", name
);
237 state
= kFirstColumn
;
238 } else if (isspace(tc
)) {
242 // state staus kCollectName.
247 case kContinueValue
:
250 } else if (isspace(tc
)) {
251 // state stays kFindValue or kContinueValue.
253 state
= kCollectValue
;
260 if (value
[vi
-1] == '\\') {
262 state
= kContinueValue
;
267 // state stays kCollectValue.
273 if (state
== kSetenv
) {
276 if ((kret
= SetOFVariable(name
, value
)) != KERN_SUCCESS
) {
277 errx(1, "Error setting variable - '%s': %s", name
,
278 mach_error_string(kret
));
280 state
= kFirstColumn
;
284 if (state
!= kFirstColumn
) {
285 errx(1, "Last line ended abruptly");
290 // ParseXMLFile(fileName)
292 // Open and parse the specified file in XML format,
293 // and set variables appropriately.
295 static void ParseXMLFile(char *fileName
)
297 CFPropertyListRef plist
;
298 CFURLRef fileURL
= NULL
;
299 CFStringRef filePath
= NULL
;
300 CFStringRef errorString
= NULL
;
301 CFDataRef data
= NULL
;
302 SInt32 errorCode
= 0;
304 filePath
= CFStringCreateWithCString(kCFAllocatorDefault
, fileName
, kCFStringEncodingUTF8
);
305 if (filePath
== NULL
) {
306 errx(1, "Could not create file path string");
309 // Create a URL that specifies the file we will create to
310 // hold the XML data.
311 fileURL
= CFURLCreateWithFileSystemPath( kCFAllocatorDefault
,
313 kCFURLPOSIXPathStyle
,
314 false /* not a directory */ );
315 if (fileURL
== NULL
) {
316 errx(1, "Could not create file path URL");
321 if (! CFURLCreateDataAndPropertiesFromResource(
327 &errorCode
) || data
== NULL
) {
328 errx(1, "Error reading XML file (%d)", errorCode
);
333 plist
= CFPropertyListCreateFromXMLData(kCFAllocatorDefault
,
335 kCFPropertyListImmutable
,
341 errx(1, "Error parsing XML file");
344 if (errorString
!= NULL
) {
345 errx(1, "Error parsing XML file: %s", CFStringGetCStringPtr(errorString
, kCFStringEncodingUTF8
));
348 CFDictionaryApplyFunction(plist
, &SetOFVariableFromFile
, 0);
353 // SetOrGetOFVariable(str)
355 // Parse the input string, then set or get the specified
356 // firmware variable.
358 static void SetOrGetOFVariable(char *str
)
365 kern_return_t result
;
367 // OF variable name is first.
370 // Find the equal sign for set
381 // On sets, the OF variable's value follows the equal sign.
384 result
= SetOFVariable(name
, value
);
385 if (result
!= KERN_SUCCESS
) {
386 errx(1, "Error setting variable - '%s': %s", name
,
387 mach_error_string(result
));
390 result
= GetOFVariable(name
, &nameRef
, &valueRef
);
391 if (result
!= KERN_SUCCESS
) {
392 errx(1, "Error getting variable - '%s': %s", name
,
393 mach_error_string(result
));
396 PrintOFVariable(nameRef
, valueRef
, 0);
403 // GetOFVariable(name, nameRef, valueRef)
405 // Get the named firmware variable.
406 // Return it and it's symbol in valueRef and nameRef.
408 static kern_return_t
GetOFVariable(char *name
, CFStringRef
*nameRef
,
411 *nameRef
= CFStringCreateWithCString(kCFAllocatorDefault
, name
,
412 kCFStringEncodingUTF8
);
414 errx(1, "Error creating CFString for key %s", name
);
417 *valueRef
= IORegistryEntryCreateCFProperty(gOptionsRef
, *nameRef
, 0, 0);
418 if (*valueRef
== 0) return kIOReturnNotFound
;
424 // SetOFVariable(name, value)
426 // Set or create an firmware variable with name and value.
428 static kern_return_t
SetOFVariable(char *name
, char *value
)
433 kern_return_t result
= KERN_SUCCESS
;
435 nameRef
= CFStringCreateWithCString(kCFAllocatorDefault
, name
,
436 kCFStringEncodingUTF8
);
438 errx(1, "Error creating CFString for key %s", name
);
441 valueRef
= IORegistryEntryCreateCFProperty(gOptionsRef
, nameRef
, 0, 0);
443 typeID
= CFGetTypeID(valueRef
);
446 valueRef
= ConvertValueToCFTypeRef(typeID
, value
);
448 errx(1, "Error creating CFTypeRef for value %s", value
);
449 } result
= IORegistryEntrySetCFProperty(gOptionsRef
, nameRef
, valueRef
);
452 // In the default case, try data, string, number, then boolean.
454 valueRef
= ConvertValueToCFTypeRef(CFDataGetTypeID(), value
);
456 result
= IORegistryEntrySetCFProperty(gOptionsRef
, nameRef
, valueRef
);
457 if (result
== KERN_SUCCESS
) break;
460 valueRef
= ConvertValueToCFTypeRef(CFStringGetTypeID(), value
);
462 result
= IORegistryEntrySetCFProperty(gOptionsRef
, nameRef
, valueRef
);
463 if (result
== KERN_SUCCESS
) break;
466 valueRef
= ConvertValueToCFTypeRef(CFNumberGetTypeID(), value
);
468 result
= IORegistryEntrySetCFProperty(gOptionsRef
, nameRef
, valueRef
);
469 if (result
== KERN_SUCCESS
) break;
472 valueRef
= ConvertValueToCFTypeRef(CFBooleanGetTypeID(), value
);
474 result
= IORegistryEntrySetCFProperty(gOptionsRef
, nameRef
, valueRef
);
475 if (result
== KERN_SUCCESS
) break;
488 // DeleteOFVariable(name)
490 // Delete the named firmware variable.
493 static void DeleteOFVariable(char *name
)
495 SetOFVariable(kIONVRAMDeletePropertyKey
, name
);
499 // PrintOFVariables()
501 // Print all of the firmware variables.
503 static void PrintOFVariables()
505 kern_return_t result
;
506 CFMutableDictionaryRef dict
;
508 result
= IORegistryEntryCreateCFProperties(gOptionsRef
, &dict
, 0, 0);
509 if (result
!= KERN_SUCCESS
) {
510 errx(1, "Error getting the firmware variables: %s", mach_error_string(result
));
516 data
= CFPropertyListCreateXMLData( kCFAllocatorDefault
, dict
);
518 errx(1, "Error converting variables to xml");
521 fwrite(CFDataGetBytePtr(data
), sizeof(UInt8
), CFDataGetLength(data
), stdout
);
527 CFDictionaryApplyFunction(dict
, &PrintOFVariable
, 0);
534 // PrintOFVariable(key, value, context)
536 // Print the given firmware variable.
538 static void PrintOFVariable(const void *key
, const void *value
, void *context
)
542 char *nameBuffer
= 0;
543 const char *nameString
;
544 char numberBuffer
[10];
545 const uint8_t *dataPtr
;
547 char *dataBuffer
= 0;
549 char *valueBuffer
= 0;
550 const char *valueString
= 0;
551 uint32_t number
, length
;
554 // Get the OF variable's name.
555 nameLen
= CFStringGetLength(key
) + 1;
556 nameBuffer
= malloc(nameLen
);
557 if( nameBuffer
&& CFStringGetCString(key
, nameBuffer
, nameLen
, kCFStringEncodingUTF8
) )
558 nameString
= nameBuffer
;
560 warnx("Unable to convert property name to C string");
561 nameString
= "<UNPRINTABLE>";
564 // Get the OF variable's type.
565 typeID
= CFGetTypeID(value
);
567 if (typeID
== CFBooleanGetTypeID()) {
568 if (CFBooleanGetValue(value
)) valueString
= "true";
569 else valueString
= "false";
570 } else if (typeID
== CFNumberGetTypeID()) {
571 CFNumberGetValue(value
, kCFNumberSInt32Type
, &number
);
572 if (number
== 0xFFFFFFFF) sprintf(numberBuffer
, "-1");
573 else if (number
< 1000) sprintf(numberBuffer
, "%d", number
);
574 else sprintf(numberBuffer
, "0x%x", number
);
575 valueString
= numberBuffer
;
576 } else if (typeID
== CFStringGetTypeID()) {
577 valueLen
= CFStringGetLength(value
) + 1;
578 valueBuffer
= malloc(valueLen
+ 1);
579 if ( valueBuffer
&& CFStringGetCString(value
, valueBuffer
, valueLen
, kCFStringEncodingUTF8
) )
580 valueString
= valueBuffer
;
582 warnx("Unable to convert value to C string");
583 valueString
= "<UNPRINTABLE>";
585 } else if (typeID
== CFDataGetTypeID()) {
586 length
= CFDataGetLength(value
);
587 if (length
== 0) valueString
= "";
589 dataBuffer
= malloc(length
* 3 + 1);
590 if (dataBuffer
!= 0) {
591 dataPtr
= CFDataGetBytePtr(value
);
592 for (cnt
= cnt2
= 0; cnt
< length
; cnt
++) {
593 dataChar
= dataPtr
[cnt
];
594 if (isprint(dataChar
)) dataBuffer
[cnt2
++] = dataChar
;
596 sprintf(dataBuffer
+ cnt2
, "%%%02x", dataChar
);
600 dataBuffer
[cnt2
] = '\0';
601 valueString
= dataBuffer
;
605 valueString
="<INVALID>";
608 if ((nameString
!= 0) && (valueString
!= 0))
609 printf("%s\t%s\n", nameString
, valueString
);
611 if (dataBuffer
!= 0) free(dataBuffer
);
612 if (nameBuffer
!= 0) free(nameBuffer
);
613 if (valueBuffer
!= 0) free(valueBuffer
);
616 // ClearOFVariables()
618 // Deletes all OF variables
620 static void ClearOFVariables(void)
622 kern_return_t result
;
623 CFMutableDictionaryRef dict
;
625 result
= IORegistryEntryCreateCFProperties(gOptionsRef
, &dict
, 0, 0);
626 if (result
!= KERN_SUCCESS
) {
627 errx(1, "Error getting the firmware variables: %s", mach_error_string(result
));
629 CFDictionaryApplyFunction(dict
, &ClearOFVariable
, 0);
634 static void ClearOFVariable(const void *key
, const void *value
, void *context
)
636 kern_return_t result
;
637 result
= IORegistryEntrySetCFProperty(gOptionsRef
,
638 CFSTR(kIONVRAMDeletePropertyKey
), key
);
639 if (result
!= KERN_SUCCESS
) {
640 errx(1, "Error clearing firmware variables: %s", mach_error_string(result
));
644 // ConvertValueToCFTypeRef(typeID, value)
646 // Convert the value into a CFType given the typeID.
648 static CFTypeRef
ConvertValueToCFTypeRef(CFTypeID typeID
, char *value
)
650 CFTypeRef valueRef
= 0;
651 long cnt
, cnt2
, length
;
652 unsigned long number
, tmp
;
654 if (typeID
== CFBooleanGetTypeID()) {
655 if (!strcmp("true", value
)) valueRef
= kCFBooleanTrue
;
656 else if (!strcmp("false", value
)) valueRef
= kCFBooleanFalse
;
657 } else if (typeID
== CFNumberGetTypeID()) {
658 number
= strtol(value
, 0, 0);
659 valueRef
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberSInt32Type
,
661 } else if (typeID
== CFStringGetTypeID()) {
662 valueRef
= CFStringCreateWithCString(kCFAllocatorDefault
, value
,
663 kCFStringEncodingUTF8
);
664 } else if (typeID
== CFDataGetTypeID()) {
665 length
= strlen(value
);
666 for (cnt
= cnt2
= 0; cnt
< length
; cnt
++, cnt2
++) {
667 if (value
[cnt
] == '%') {
668 if (!ishexnumber(value
[cnt
+ 1]) ||
669 !ishexnumber(value
[cnt
+ 2])) return 0;
670 number
= toupper(value
[++cnt
]) - '0';
671 if (number
> 9) number
-= 7;
672 tmp
= toupper(value
[++cnt
]) - '0';
673 if (tmp
> 9) tmp
-= 7;
674 number
= (number
<< 4) + tmp
;
675 value
[cnt2
] = number
;
676 } else value
[cnt2
] = value
[cnt
];
678 valueRef
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, (const UInt8
*)value
,
679 cnt2
, kCFAllocatorDefault
);
685 static void SetOFVariableFromFile(const void *key
, const void *value
, void *context
)
687 kern_return_t result
;
689 result
= IORegistryEntrySetCFProperty(gOptionsRef
, key
, value
);
690 if ( result
!= KERN_SUCCESS
) {
695 // Get the variable's name.
696 nameLen
= CFStringGetLength(key
) + 1;
697 nameBuffer
= malloc(nameLen
);
698 if( nameBuffer
&& CFStringGetCString(key
, nameBuffer
, nameLen
, kCFStringEncodingUTF8
) )
699 nameString
= nameBuffer
;
701 warnx("Unable to convert property name to C string");
702 nameString
= "<UNPRINTABLE>";
704 errx(1, "Error setting variable - '%s': %s", nameString
,
705 mach_error_string(result
));