forked from rugarciap/Turbo-Boost-Switcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSystemCommands.m
583 lines (443 loc) · 17 KB
/
SystemCommands.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//
// SystemCommands.m
// Turbo Boost Switcher
//
// Created by Rubén García Pérez on 20/07/13.
// Copyright (c) 2013 Rubén García Pérez.
// rugarciap.com
//
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#import "SystemCommands.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <IOKit/IOKitLib.h>
#include "smc.h"
#import <ServiceManagement/ServiceManagement.h>
#import <Security/Authorization.h>
static io_connect_t conn;
#define KEY_INFO_CACHE_SIZE 100
struct {
UInt32 key;
SMCKeyData_keyInfo_t keyInfo;
} g_keyInfoCache[KEY_INFO_CACHE_SIZE];
int g_keyInfoCacheCount = 0;
OSSpinLock g_keyInfoSpinLock = 0;
static NSArray *allSensors = nil;
static NSString *currentSensor = nil;
kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure, io_connect_t conn);
UInt32 _strtoul(char *str, int size, int base)
{
UInt32 total = 0;
int i;
for (i = 0; i < size; i++)
{
if (base == 16)
total += str[i] << (size - 1 - i) * 8;
else
total += ((unsigned char) (str[i]) << (size - 1 - i) * 8);
}
return total;
}
void _ultostr(char *str, UInt32 val)
{
str[0] = '\0';
sprintf(str, "%c%c%c%c",
(unsigned int) val >> 24,
(unsigned int) val >> 16,
(unsigned int) val >> 8,
(unsigned int) val);
}
kern_return_t SMCOpen(io_connect_t *conn)
{
kern_return_t result;
mach_port_t masterPort;
io_iterator_t iterator;
io_object_t device;
IOMasterPort(MACH_PORT_NULL, &masterPort);
CFMutableDictionaryRef matchingDictionary = IOServiceMatching("AppleSMC");
result = IOServiceGetMatchingServices(masterPort, matchingDictionary, &iterator);
if (result != kIOReturnSuccess)
{
printf("Error: IOServiceGetMatchingServices() = %08x\n", result);
return 1;
}
device = IOIteratorNext(iterator);
IOObjectRelease(iterator);
if (device == 0)
{
printf("Error: no SMC found\n");
return 1;
}
result = IOServiceOpen(device, mach_task_self(), 0, conn);
IOObjectRelease(device);
if (result != kIOReturnSuccess)
{
printf("Error: IOServiceOpen() = %08x\n", result);
return 1;
}
return kIOReturnSuccess;
}
kern_return_t SMCClose(io_connect_t conn)
{
return IOServiceClose(conn);
}
kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure,io_connect_t conn)
{
size_t structureInputSize;
size_t structureOutputSize;
structureInputSize = sizeof(SMCKeyData_t);
structureOutputSize = sizeof(SMCKeyData_t);
return IOConnectCallStructMethod(conn, index, inputStructure, structureInputSize, outputStructure, &structureOutputSize);
}
// Provides key info, using a cache to dramatically improve the energy impact of smcFanControl
kern_return_t SMCGetKeyInfo(UInt32 key, SMCKeyData_keyInfo_t* keyInfo, io_connect_t conn)
{
SMCKeyData_t inputStructure;
SMCKeyData_t outputStructure;
kern_return_t result = kIOReturnSuccess;
int i = 0;
OSSpinLockLock(&g_keyInfoSpinLock);
for (; i < g_keyInfoCacheCount; ++i)
{
if (key == g_keyInfoCache[i].key)
{
*keyInfo = g_keyInfoCache[i].keyInfo;
break;
}
}
if (i == g_keyInfoCacheCount)
{
// Not in cache, must look it up.
memset(&inputStructure, 0, sizeof(inputStructure));
memset(&outputStructure, 0, sizeof(outputStructure));
inputStructure.key = key;
inputStructure.data8 = SMC_CMD_READ_KEYINFO;
result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure, conn);
if (result == kIOReturnSuccess)
{
*keyInfo = outputStructure.keyInfo;
if (g_keyInfoCacheCount < KEY_INFO_CACHE_SIZE)
{
g_keyInfoCache[g_keyInfoCacheCount].key = key;
g_keyInfoCache[g_keyInfoCacheCount].keyInfo = outputStructure.keyInfo;
++g_keyInfoCacheCount;
}
}
}
OSSpinLockUnlock(&g_keyInfoSpinLock);
return result;
}
kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn)
{
kern_return_t result;
SMCKeyData_t inputStructure;
SMCKeyData_t outputStructure;
memset(&inputStructure, 0, sizeof(SMCKeyData_t));
memset(&outputStructure, 0, sizeof(SMCKeyData_t));
memset(val, 0, sizeof(SMCVal_t));
inputStructure.key = _strtoul(key, 4, 16);
sprintf(val->key, key);
result = SMCGetKeyInfo(inputStructure.key, &outputStructure.keyInfo, conn);
if (result != kIOReturnSuccess)
{
return result;
}
val->dataSize = outputStructure.keyInfo.dataSize;
_ultostr(val->dataType, outputStructure.keyInfo.dataType);
inputStructure.keyInfo.dataSize = val->dataSize;
inputStructure.data8 = SMC_CMD_READ_BYTES;
result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure,conn);
if (result != kIOReturnSuccess)
{
return result;
}
memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes));
return kIOReturnSuccess;
}
double SMCGetTemperature()
{
float c_temp;
if (allSensors == nil) {
allSensors = [[NSArray alloc] initWithObjects:@"TC0D",@"TCAH",@"TC0F",@"TC0H",@"TCBH",@"TC0P",nil];
}
SMCVal_t val;
if (currentSensor != nil) {
SMCReadKey2((char*)[currentSensor UTF8String], &val,conn);
c_temp= ((val.bytes[0] * 256 + val.bytes[1]) >> 2)/64;
if (c_temp>0) {
return c_temp;
}
}
for (NSString *sensor in allSensors) {
SMCReadKey2((char*)[sensor UTF8String], &val,conn);
c_temp= ((val.bytes[0] * 256 + val.bytes[1]) >> 2)/64;
if (c_temp>0) {
currentSensor = sensor;
break;
}
}
return c_temp;
}
int SMCGetFanSpeed(char *key)
{
SMCVal_t val;
kern_return_t result;
result = SMCReadKey2(key, &val, conn);
if (result == kIOReturnSuccess) {
// read succeeded - check returned value
if (val.dataSize > 0) {
if (strcmp(val.dataType, DATATYPE_FPE2) == 0) {
int intValue = (val.bytes[0] * 256 + val.bytes[1]) >> 2;
return intValue;
// New Macbooks 2018 uses float values
} else if (strcmp(val.dataType, DATATYPE_FLOAT) == 0) {
float floatValue;
memcpy(&floatValue, val.bytes, sizeof(float));
return (int) floatValue;
}
}
}
// read failed
return 0;
}
@implementation SystemCommands
// New method to run task as root. Authref stored on appdelegate, created once and reused each time this
// method is called
+ (BOOL) runTaskAsAdmin:(NSString *) path withAuthRef:(AuthorizationRef) authRef andArgs:(NSArray *) args {
FILE *myCommunicationsPipe = NULL;
int count = (int)[args count];
char *myArguments[count+1];
for (int i=0; i<[args count]; i++) {
myArguments[i] = (char *)[(NSString *)[args objectAtIndex:i] UTF8String];
}
myArguments[count] = NULL;
OSStatus resultStatus = AuthorizationExecuteWithPrivileges (authRef,
[path UTF8String], kAuthorizationFlagDefaults, myArguments,
&myCommunicationsPipe);
if (resultStatus != errAuthorizationSuccess)
NSLog(@"Error: %d", resultStatus);
return YES;
}
// Deprecated. TODO: To be removed on next version.
+ (BOOL) runProcess:(NSString*)scriptPath
withArguments:(NSArray *)arguments
output:(NSString **)output
errorDescription:(NSString **)errorDescription
asAdministrator:(BOOL) isAdministrator{
NSString * allArgs = [arguments componentsJoinedByString:@" "];
NSString * fullScript = [NSString stringWithFormat:@"%@ %@", scriptPath, allArgs];
NSDictionary *errorInfo = [NSDictionary new];
NSString *script;
if (isAdministrator) {
script = [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];
} else {
script = [NSString stringWithFormat:@"do shell script \"%@\"", fullScript];
}
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];
// Check errorInfo
if (! eventResult)
{
// Describe common errors
*errorDescription = nil;
if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
{
NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
if ([errorNumber intValue] == -128)
*errorDescription = @"The administrator password is required to do this.";
}
// Set error message from provided message
if (*errorDescription == nil)
{
if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
*errorDescription = (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
}
return NO;
}
else
{
// Set output to the AppleScript's output
*output = [eventResult stringValue];
return YES;
}
}
+ (BOOL) is32bits {
NSString *osVersion = [SystemCommands getOSVersion];
if ([osVersion rangeOfString:@"10.10"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else if ([osVersion rangeOfString:@"10.11"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else if ([osVersion rangeOfString:@"10.12"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else if ([osVersion rangeOfString:@"10.13"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else if ([osVersion rangeOfString:@"10.14"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else if ([osVersion rangeOfString:@"10.15"].location != NSNotFound) {
return [SystemCommands is32bitsNewOS];
} else {
return [SystemCommands is32bitsOldOS];
}
}
+ (BOOL) isModuleLoaded {
NSString *osVersion = [SystemCommands getOSVersion];
if ([osVersion rangeOfString:@"10.10"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else if ([osVersion rangeOfString:@"10.11"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else if ([osVersion rangeOfString:@"10.12"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else if ([osVersion rangeOfString:@"10.13"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else if ([osVersion rangeOfString:@"10.14"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else if ([osVersion rangeOfString:@"10.15"].location != NSNotFound) {
return [SystemCommands isModuleLoadedNewOS];
} else {
return [SystemCommands isModuleLoadedOldOS];
}
}
// Gets OSX Version
+ (NSString *) getOSVersion {
NSProcessInfo *pInfo = [NSProcessInfo processInfo];
NSString *version = [pInfo operatingSystemVersionString];
return version;
}
// Check if is 32 bits or not
+ (BOOL) is32bitsNewOS {
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/sh";
task.arguments = @[@"-c", @"uname -m"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if ([output rangeOfString:@"x86_64"].location != NSNotFound) {
return NO;
}
return YES;
}
// Check if is 32 bits or not
+ (BOOL) is32bitsOldOS {
NSString * output = nil;
NSString * processErrorDescription = nil;
// kextstat |grep com.rugarciap.DisableTurboBoost
[self runProcess:@"uname -m"
withArguments:[NSArray arrayWithObjects:@"", nil]
output:&output
errorDescription:&processErrorDescription asAdministrator:NO];
if ([output isEqualToString:@"x86_64"]) {
return NO;
}
return YES;
}
// Check if the module is loaded (TBS disabled) or not (TBS Enabled)
+ (BOOL) isModuleLoadedNewOS {
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/sh";
task.arguments = @[@"-c", @"kextstat | grep com.rugarciap.DisableTurboBoost"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if ((grepOutput == nil) || ([grepOutput length] == 0)){
return NO;
}
return YES;
}
// Check if the module is loaded (TBS disabled) or not (TBS Enabled)
+ (BOOL) isModuleLoadedOldOS {
NSString * output = nil;
NSString * processErrorDescription = nil;
// kextstat |grep com.rugarciap.DisableTurboBoost
[self runProcess:@"kextstat | grep com.rugarciap.DisableTurboBoost"
withArguments:[NSArray arrayWithObjects:@"", nil]
output:&output
errorDescription:&processErrorDescription asAdministrator:NO];
NSLog(@"kextstat output: %@", output);
if (output == nil) {
return NO;
} else {
return YES;
}
}
// Get the module path depending on arch
+ (NSString *) getModulePath:(BOOL) is32bits {
NSString *modulePath;
// Cargamos el módulo de 32 bits o no dependiendo de la ruta
if (is32bits) {
modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.32bits" ofType:@"kext"];
} else {
modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.64bits" ofType:@"kext"];
}
return modulePath;
//return [modulePath stringByReplacingOccurrencesOfString:@" " withString:@"\\ "];
}
+ (BOOL) loadModuleWithAuthRef:(AuthorizationRef) authRef {
BOOL is32bits = [self is32bits];
NSString *modulePath = [self getModulePath:is32bits];
return [self loadModuleWithPath:modulePath andAuthRef:authRef];
}
+ (BOOL) unLoadModuleWithAuthRef:(AuthorizationRef) authRef {
BOOL is32bits = [self is32bits];
NSString *modulePath = [self getModulePath:is32bits];
return [self unloadModuleWithPath:modulePath andAuthRef:authRef];
}
+ (BOOL) loadModuleWithPath:(NSString *) pathToModule andAuthRef:(AuthorizationRef) authRef {
NSString * processErrorDescription = nil;
// sudo chown -R root:wheel %pathToModule; sudo kextutil -v %pathToModule
[self runTaskAsAdmin:@"/usr/sbin/chown" withAuthRef:authRef andArgs:[NSArray arrayWithObjects:@"-R", @"root:wheel",[NSString stringWithFormat:@"%@", pathToModule], nil]];
[self runTaskAsAdmin:@"/usr/bin/kextutil" withAuthRef:authRef andArgs:[NSArray arrayWithObjects:@"-v", [NSString stringWithFormat:@"%@", pathToModule], nil]];
if (processErrorDescription != nil) {
NSLog(@"Error loading module: %@", processErrorDescription);
}
return YES;
}
+ (BOOL) unloadModuleWithPath:(NSString *) pathToModule andAuthRef:(AuthorizationRef) authRef {
NSString * processErrorDescription = nil;
// sudo kextunload -v path
[self runTaskAsAdmin:@"/sbin/kextunload" withAuthRef:authRef andArgs:[NSArray arrayWithObjects:@"-v",[NSString stringWithFormat:@"%@", pathToModule], nil]];
if (processErrorDescription != nil) {
NSLog(@"Error unloading module: %@", processErrorDescription);
}
return YES;
}
+ (float) readCurrentCpuTemp {
SMCOpen(&conn);
float temp = 0;
temp = SMCGetTemperature();
SMCClose(conn);
return temp;
}
+ (int) readCurrentFanSpeed {
SMCOpen(&conn);
int fanSpeed = SMCGetFanSpeed(SMC_KEY_FAN0_RPM_CUR);
if (fanSpeed < 1) {
fanSpeed = SMCGetFanSpeed(SMC_KEY_FAN1_RPM_CUR);
}
if (fanSpeed < 1) {
fanSpeed = -1;
}
SMCClose(conn);
return fanSpeed;
}
@end