forked from rovo89/Xposed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xposed_service.cpp
973 lines (818 loc) · 29.3 KB
/
xposed_service.cpp
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
/**
* This file includes the Xposed services, which are especially used to work around SELinux restrictions.
*/
#define LOG_TAG "Xposed"
#include "xposed.h"
#include "xposed_service.h"
#include <binder/BpBinder.h>
#include <binder/IInterface.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <binder/ProcessState.h>
#include <errno.h>
#include <fcntl.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <sys/mman.h>
#define UID_SYSTEM 1000
using namespace android;
namespace xposed {
namespace service {
////////////////////////////////////////////////////////////
// Declarations
////////////////////////////////////////////////////////////
bool running = false;
////////////////////////////////////////////////////////////
// Memory-based communication (used by Zygote)
////////////////////////////////////////////////////////////
namespace membased {
enum State {
STATE_NOT_RUNNING,
STATE_IDLE,
STATE_SERVICE_ACTION,
STATE_SERVER_RESPONSE,
};
enum Action {
OP_NONE,
OP_ACCESS_FILE,
OP_STAT_FILE,
OP_READ_FILE,
};
struct AccessFileData {
// in
char path[PATH_MAX];
int mode;
// out
int result;
};
struct StatFileData {
// in
char path[PATH_MAX];
// inout
struct stat st;
// out
int result;
};
struct ReadFileData {
// in
char path[PATH_MAX];
int offset;
// out
int totalSize;
int bytesRead;
bool eof;
char content[32*1024];
};
struct MemBasedState {
pthread_mutex_t workerMutex;
pthread_cond_t workerCond;
State state;
Action action;
int error;
union {
AccessFileData accessFile;
StatFileData statFile;
ReadFileData readFile;
} data;
};
MemBasedState* shared = NULL;
pid_t zygotePid = 0;
bool canAlwaysAccessService = false;
inline static void initSharedMutex(pthread_mutex_t* mutex) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
inline static void initSharedCond(pthread_cond_t* cond) {
pthread_condattr_t cattr;
pthread_condattr_init(&cattr);
pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED);
pthread_cond_init(cond, &cattr);
pthread_condattr_destroy(&cattr);
}
static bool init() {
shared = (MemBasedState*) mmap(NULL, sizeof(MemBasedState), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared == MAP_FAILED) {
ALOGE("Could not allocate memory for Zygote service: %s", strerror(errno));
shared = NULL;
return false;
}
zygotePid = getpid();
canAlwaysAccessService = true;
initSharedMutex(&shared->workerMutex);
initSharedCond(&shared->workerCond);
shared->state = STATE_NOT_RUNNING;
shared->action = OP_NONE;
shared->error = 0;
return true;
}
static void restrictMemoryInheritance() {
madvise(shared, sizeof(MemBasedState), MADV_DONTFORK);
canAlwaysAccessService = false;
}
static inline bool isServiceAccessible() {
if (!canAlwaysAccessService && (shared == NULL || zygotePid != getpid())) {
ALOGE("Zygote service is not accessible from PID %d, UID %d", getpid(), getuid());
shared = NULL;
errno = EPERM;
return false;
}
return true;
}
// Server implementation
void* looper(void* unused __attribute__((unused))) {
pthread_mutex_lock(&shared->workerMutex);
shared->state = STATE_IDLE;
pthread_cond_signal(&shared->workerCond);
while (1) {
while (shared->state != STATE_SERVICE_ACTION) {
pthread_cond_wait(&shared->workerCond, &shared->workerMutex);
}
switch (shared->action) {
case OP_ACCESS_FILE: {
struct AccessFileData* data = &shared->data.accessFile;
data->result = TEMP_FAILURE_RETRY(access(data->path, data->mode));
if (data->result != 0) {
shared->error = errno;
}
} break;
case OP_STAT_FILE: {
struct StatFileData* data = &shared->data.statFile;
data->result = TEMP_FAILURE_RETRY(stat(data->path, &data->st));
if (data->result != 0) {
shared->error = errno;
}
} break;
case OP_READ_FILE: {
struct ReadFileData* data = &shared->data.readFile;
struct stat st;
if (stat(data->path, &st) != 0) {
shared->error = errno;
break;
}
data->totalSize = st.st_size;
FILE *f = fopen(data->path, "r");
if (f == NULL) {
shared->error = errno;
break;
}
if (data->offset > 0 && fseek(f, data->offset, SEEK_SET) != 0) {
shared->error = ferror(f);
fclose(f);
break;
}
data->bytesRead = fread(data->content, 1, sizeof(data->content), f);
shared->error = ferror(f);
data->eof = feof(f);
fclose(f);
} break;
case OP_NONE: {
ALOGE("No-op call to membased service");
break;
}
default: {
ALOGE("Invalid action in call to membased service");
break;
}
}
shared->state = STATE_SERVER_RESPONSE;
pthread_cond_signal(&shared->workerCond);
}
pthread_mutex_unlock(&shared->workerMutex);
return NULL;
}
// Client implementation
static inline bool waitForRunning(int timeout) {
if (shared == NULL || timeout < 0)
return false;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
int rc = 0;
pthread_mutex_lock(&shared->workerMutex);
while (shared->state == STATE_NOT_RUNNING && rc == 0) {
rc = pthread_cond_timedwait(&shared->workerCond, &shared->workerMutex, &ts);
}
pthread_mutex_unlock(&shared->workerMutex);
return rc == 0;
}
static inline void waitForIdle() {
pthread_mutex_lock(&shared->workerMutex);
while (shared->state != STATE_IDLE) {
pthread_cond_wait(&shared->workerCond, &shared->workerMutex);
}
}
static inline void callService(Action action) {
shared->action = action;
shared->state = STATE_SERVICE_ACTION;
shared->error = 0;
pthread_cond_signal(&shared->workerCond);
while (shared->state != STATE_SERVER_RESPONSE) {
pthread_cond_wait(&shared->workerCond, &shared->workerMutex);
}
}
static inline void makeIdle() {
shared->action = OP_NONE;
shared->state = STATE_IDLE;
pthread_cond_signal(&shared->workerCond);
pthread_mutex_unlock(&shared->workerMutex);
}
int accessFile(const char* path, int mode) {
if (!isServiceAccessible())
return -1;
if (strlen(path) > sizeof(AccessFileData::path) - 1) {
errno = ENAMETOOLONG;
return -1;
}
waitForIdle();
struct AccessFileData* data = &shared->data.accessFile;
strcpy(data->path, path);
data->mode = mode;
callService(OP_ACCESS_FILE);
bail:
makeIdle();
errno = shared->error;
return shared->error ? -1 : data->result;
}
int statFile(const char* path, struct stat* st) {
if (!isServiceAccessible())
return -1;
if (strlen(path) > sizeof(StatFileData::path) - 1) {
errno = ENAMETOOLONG;
return -1;
}
waitForIdle();
struct StatFileData* data = &shared->data.statFile;
strcpy(data->path, path);
callService(OP_STAT_FILE);
memcpy(st, &data->st, sizeof(struct stat));
bail:
makeIdle();
errno = shared->error;
return shared->error ? -1 : data->result;
}
char* readFile(const char* path, int* bytesRead) {
if (!isServiceAccessible())
return NULL;
char* result = NULL;
int offset = 0, totalSize = 0;
if (bytesRead)
*bytesRead = 0;
if (strlen(path) > sizeof(ReadFileData::path) - 1) {
errno = ENAMETOOLONG;
return NULL;
}
waitForIdle();
struct ReadFileData* data = &shared->data.readFile;
strcpy(data->path, path);
data->offset = 0;
callService(OP_READ_FILE);
if (shared->error)
goto bail;
totalSize = data->totalSize;
result = (char*) malloc(totalSize + 1);
result[totalSize] = 0;
memcpy(result, data->content, data->bytesRead);
while (!data->eof) {
offset += data->bytesRead;
data->offset = offset;
callService(OP_READ_FILE);
if (shared->error)
goto bail;
if (offset + data->bytesRead > totalSize) {
shared->error = EBUSY;
goto bail;
}
memcpy(result + offset, data->content, data->bytesRead);
}
if (bytesRead)
*bytesRead = offset + data->bytesRead;
bail:
makeIdle();
if (shared->error && result) {
free(result);
result = NULL;
}
errno = shared->error;
return result;
}
} // namespace membased
////////////////////////////////////////////////////////////
// Binder service
////////////////////////////////////////////////////////////
namespace binder {
#define XPOSED_BINDER_SYSTEM_SERVICE_NAME "user.xposed.system"
#define XPOSED_BINDER_APP_SERVICE_NAME "user.xposed.app"
class IXposedService: public IInterface {
public:
DECLARE_META_INTERFACE(XposedService);
virtual int test() const = 0;
virtual status_t addService(const String16& name,
const sp<IBinder>& service,
bool allowIsolated = false) const = 0;
virtual int accessFile(const String16& filename,
int32_t mode) const = 0;
virtual int statFile(const String16& filename,
int64_t* size,
int64_t* mtime) const = 0;
virtual status_t readFile(const String16& filename,
int32_t offset,
int32_t length,
int64_t* size,
int64_t* mtime,
uint8_t** buffer,
int32_t* bytesRead,
String16* errormsg) const = 0;
enum {
TEST_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
ADD_SERVICE_TRANSACTION,
ACCESS_FILE_TRANSACTION,
STAT_FILE_TRANSACTION,
READ_FILE_TRANSACTION,
};
};
class BnXposedService: public BnInterface<IXposedService> {
public:
virtual status_t onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0);
};
class BpXposedService: public BpInterface<IXposedService> {
public:
BpXposedService(const sp<IBinder>& impl) : BpInterface<IXposedService>(impl) {}
virtual int test() const {
Parcel data, reply;
data.writeInterfaceToken(IXposedService::getInterfaceDescriptor());
remote()->transact(TEST_TRANSACTION, data, &reply);
if (reply.readExceptionCode() != 0) return -1;
return reply.readInt32();
}
virtual status_t addService(const String16& name, const sp<IBinder>& service,
bool allowIsolated = false) const {
Parcel data, reply;
data.writeInterfaceToken(IXposedService::getInterfaceDescriptor());
data.writeString16(name);
data.writeStrongBinder(service);
data.writeInt32(allowIsolated ? 1 : 0);
status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
return err == NO_ERROR ? reply.readExceptionCode() : err;
}
virtual status_t accessFile(const String16& name, int32_t mode) const {
Parcel data, reply;
data.writeInterfaceToken(IXposedService::getInterfaceDescriptor());
data.writeString16(name);
data.writeInt32(mode);
remote()->transact(ACCESS_FILE_TRANSACTION, data, &reply);
if (reply.readExceptionCode() != 0) return -1;
errno = reply.readInt32();
return (errno == 0) ? 0 : -1;
}
virtual status_t statFile(const String16& name, int64_t* size, int64_t* mtime) const {
Parcel data, reply;
data.writeInterfaceToken(IXposedService::getInterfaceDescriptor());
data.writeString16(name);
remote()->transact(STAT_FILE_TRANSACTION, data, &reply);
if (reply.readExceptionCode() != 0) return -1;
errno = reply.readInt32();
if (errno != 0) return -1;
int64_t size1 = reply.readInt64();
int64_t mtime1 = reply.readInt64();
if (size != NULL) size1 = *size;
if (mtime != NULL) mtime1 = *mtime;
return 0;
}
virtual status_t readFile(const String16& filename, int32_t offset, int32_t length,
int64_t* size, int64_t* mtime, uint8_t** buffer, int32_t* bytesRead, String16* errormsg) const {
Parcel data, reply;
data.writeInterfaceToken(IXposedService::getInterfaceDescriptor());
data.writeString16(filename);
data.writeInt32(offset);
data.writeInt32(length);
int64_t size1 = 0;
int64_t mtime1 = 0;
if (size != NULL) size1 = *size;
if (mtime != NULL) mtime1 = *mtime;
data.writeInt64(size1);
data.writeInt64(mtime1);
remote()->transact(READ_FILE_TRANSACTION, data, &reply);
if (reply.readExceptionCode() != 0) return -1;
status_t err = reply.readInt32();
const String16& errormsg1(reply.readString16());
size1 = reply.readInt64();
mtime1 = reply.readInt64();
int32_t bytesRead1 = reply.readInt32();
if (size != NULL) *size = size1;
if (mtime != NULL) *mtime = mtime1;
if (bytesRead != NULL) *bytesRead = bytesRead1;
if (errormsg) *errormsg = errormsg1;
if (bytesRead1 > 0 && bytesRead1 <= (int32_t)reply.dataAvail()) {
*buffer = (uint8_t*) malloc(bytesRead1 + 1);
*buffer[bytesRead1] = 0;
reply.read(*buffer, bytesRead1);
} else {
*buffer = NULL;
}
errno = err;
return (errno == 0) ? 0 : -1;
}
};
IMPLEMENT_META_INTERFACE(XposedService, "de.robv.android.xposed.IXposedService");
status_t BnXposedService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
switch (code) {
case TEST_TRANSACTION: {
CHECK_INTERFACE(IXposedService, data, reply);
reply->writeNoException();
reply->writeInt32(test());
return NO_ERROR;
} break;
case ADD_SERVICE_TRANSACTION: {
CHECK_INTERFACE(IXposedService, data, reply);
String16 which = data.readString16();
sp<IBinder> b = data.readStrongBinder();
bool allowIsolated = (data.readInt32() != 0);
reply->writeInt32(addService(which, b, allowIsolated));
return NO_ERROR;
} break;
case ACCESS_FILE_TRANSACTION: {
CHECK_INTERFACE(IXposedService, data, reply);
String16 filename = data.readString16();
int32_t mode = data.readInt32();
status_t result = accessFile(filename, mode);
int err = errno;
reply->writeNoException();
reply->writeInt32(result == 0 ? 0 : err);
return NO_ERROR;
} break;
case STAT_FILE_TRANSACTION: {
CHECK_INTERFACE(IXposedService, data, reply);
String16 filename = data.readString16();
int32_t mode = data.readInt32();
int64_t size, time;
status_t result = statFile(filename, &size, &time);
int err = errno;
reply->writeNoException();
if (result == 0) {
reply->writeInt32(0);
reply->writeInt64(size);
reply->writeInt64(time);
} else {
reply->writeInt32(err);
}
return NO_ERROR;
} break;
case READ_FILE_TRANSACTION: {
CHECK_INTERFACE(IXposedService, data, reply);
String16 filename = data.readString16();
int32_t offset = data.readInt32();
int32_t length = data.readInt32();
int64_t size = data.readInt64();
int64_t mtime = data.readInt64();
uint8_t* buffer = NULL;
int32_t bytesRead = -1;
String16 errormsg;
status_t err = readFile(filename, offset, length, &size, &mtime, &buffer, &bytesRead, &errormsg);
reply->writeNoException();
reply->writeInt32(err);
reply->writeString16(errormsg);
reply->writeInt64(size);
reply->writeInt64(mtime);
if (bytesRead > 0) {
#if PLATFORM_SDK_VERSION >= 21
reply->writeByteArray(bytesRead, buffer);
#else
reply->writeInt32(bytesRead);
reply->write(buffer, bytesRead);
#endif
free(buffer);
} else {
reply->writeInt32(bytesRead); // empty array (0) or null (-1)
}
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
class XposedService : public BnXposedService {
public:
XposedService(bool system);
virtual int test() const;
virtual status_t addService(const String16& name,
const sp<IBinder>& service,
bool allowIsolated = false) const;
virtual status_t accessFile(const String16& filename16,
int32_t mode) const;
virtual status_t statFile(const String16& filename,
int64_t* size,
int64_t* mtime) const;
virtual status_t readFile(const String16& filename16,
int32_t offset,
int32_t length,
int64_t* size,
int64_t* mtime,
uint8_t** buffer,
int32_t* bytesRead,
String16* errormsg) const;
private:
bool isSystem;
};
static String16 formatToString16(const char* fmt, ...) {
char* message;
va_list args;
va_start(args, fmt);
int size = vasprintf(&message, fmt, args);
String16 result(message, size);
free(message);
va_end(args);
return result;
}
XposedService::XposedService(bool system)
: isSystem(system) {}
int XposedService::test() const {
pid_t pid = IPCThreadState::self()->getCallingPid();
ALOGD("This is PID %d, test method was called from PID %d", getpid(), pid);
return getpid();
}
status_t XposedService::addService(const String16& name, const sp<IBinder>& service,
bool allowIsolated) const {
uid_t uid = IPCThreadState::self()->getCallingUid();
if (!isSystem || (uid != 0)) {
ALOGE("Permission denied, not adding service %s", String8(name).string());
errno = EPERM;
return -1;
}
sp<IServiceManager> sm = defaultServiceManager();
#if PLATFORM_SDK_VERSION >= 16
return sm->addService(name, service, allowIsolated);
#else
return sm->addService(name, service);
#endif
}
status_t XposedService::accessFile(const String16& filename16, int32_t mode) const {
uid_t caller = IPCThreadState::self()->getCallingUid();
if (caller != UID_SYSTEM) {
ALOGE("UID %d is not allowed to use the Xposed service", caller);
errno = EPERM;
return -1;
}
const char* filename = String8(filename16).string();
return TEMP_FAILURE_RETRY(access(filename, mode));
}
status_t XposedService::statFile(const String16& filename16, int64_t* size, int64_t* time) const {
uid_t caller = IPCThreadState::self()->getCallingUid();
if (caller != UID_SYSTEM) {
ALOGE("UID %d is not allowed to use the Xposed service", caller);
errno = EPERM;
return -1;
}
const char* filename = String8(filename16).string();
struct stat st;
status_t result = TEMP_FAILURE_RETRY(stat(filename, &st));
if (result == 0) {
*size = st.st_size;
*time = st.st_mtime;
}
return result;
}
status_t XposedService::readFile(const String16& filename16, int32_t offset, int32_t length,
int64_t* size, int64_t* mtime, uint8_t** buffer, int32_t* bytesRead, String16* errormsg) const {
uid_t caller = IPCThreadState::self()->getCallingUid();
if (caller != UID_SYSTEM) {
ALOGE("UID %d is not allowed to use the Xposed service", caller);
return EPERM;
}
*buffer = NULL;
*bytesRead = -1;
// Get file metadata
const char* filename = String8(filename16).string();
struct stat st;
if (stat(filename, &st) != 0) {
status_t err = errno;
if (errormsg) *errormsg = formatToString16("%s during stat() on %s", strerror(err), filename);
return err;
}
if (S_ISDIR(st.st_mode)) {
if (errormsg) *errormsg = formatToString16("%s is a directory", filename);
return EISDIR;
}
// Don't load again if file is unchanged
if (*size == st.st_size && *mtime == (int32_t)st.st_mtime) {
return 0;
}
*size = st.st_size;
*mtime = st.st_mtime;
// Check range
if (offset > 0 && offset >= *size) {
if (errormsg) *errormsg = formatToString16("offset %d >= size %"PRId64" for %s", offset, *size, filename);
return EINVAL;
} else if (offset < 0) {
offset = 0;
}
if (length > 0 && (offset + length) > *size) {
if (errormsg) *errormsg = formatToString16("offset %d + length %d > size %"PRId64" for %s", offset, length, *size, filename);
return EINVAL;
} else if (*size == 0) {
*bytesRead = 0;
return 0;
} else if (length <= 0) {
length = *size - offset;
}
// Allocate buffer
*buffer = (uint8_t*) malloc(length + 1);
if (*buffer == NULL) {
if (errormsg) *errormsg = formatToString16("allocating buffer with %d bytes failed", length + 1);
return ENOMEM;
}
(*buffer)[length] = 0;
// Open file
FILE *f = fopen(filename, "r");
if (f == NULL) {
status_t err = errno;
free(*buffer);
*buffer = NULL;
if (errormsg) *errormsg = formatToString16("%s during fopen() on %s", strerror(err), filename);
return err;
}
// Seek to correct offset
if (offset > 0 && fseek(f, offset, SEEK_SET) != 0) {
free(*buffer);
*buffer = NULL;
status_t err = ferror(f);
fclose(f);
if (errormsg) *errormsg = formatToString16("%s during fseek() to offset %d for %s", strerror(err), offset, filename);
return err;
}
// Read the file
*bytesRead = fread(*buffer, 1, length, f);
status_t err = ferror(f);
if (err != 0) {
free(*buffer);
*buffer = NULL;
*bytesRead = -1;
if (errormsg) *errormsg = formatToString16("%s during fread(), read %d bytes for %s", strerror(err), *bytesRead, filename);
}
// Close the file
fclose(f);
return err;
}
} // namespace binder
////////////////////////////////////////////////////////////
// General
////////////////////////////////////////////////////////////
static void systemService() {
xposed::setProcessName("xposed_service_system");
xposed::dropCapabilities();
#if XPOSED_WITH_SELINUX
if (xposed->isSELinuxEnabled) {
if (setcon(ctx_system) != 0) {
ALOGE("Could not switch to %s context", ctx_system);
exit(EXIT_FAILURE);
}
}
#endif // XPOSED_WITH_SELINUX
// Initialize the system service
sp<IServiceManager> sm(defaultServiceManager());
#if PLATFORM_SDK_VERSION >= 16
status_t err = sm->addService(String16(XPOSED_BINDER_SYSTEM_SERVICE_NAME), new binder::XposedService(true), true);
#else
status_t err = sm->addService(String16(XPOSED_BINDER_SYSTEM_SERVICE_NAME), new binder::XposedService(true));
#endif
if (err != NO_ERROR) {
ALOGE("Error %d while adding system service %s", err, XPOSED_BINDER_SYSTEM_SERVICE_NAME);
exit(EXIT_FAILURE);
}
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
#if PLATFORM_SDK_VERSION >= 18
ps->giveThreadPoolName();
#endif
IPCThreadState::self()->joinThreadPool();
}
static void appService(bool useSingleProcess) {
xposed::setProcessName(useSingleProcess ? "xposed_service" : "xposed_service_app");
xposed::dropCapabilities();
#if XPOSED_WITH_SELINUX
if (xposed->isSELinuxEnabled) {
if (setcon(ctx_app) != 0) {
ALOGE("Could not switch to %s context", ctx_app);
exit(EXIT_FAILURE);
}
}
#endif // XPOSED_WITH_SELINUX
sp<IServiceManager> sm(defaultServiceManager());
status_t err;
if (useSingleProcess) {
// Initialize the system service here as this is the only service process
#if PLATFORM_SDK_VERSION >= 16
err = sm->addService(String16(XPOSED_BINDER_SYSTEM_SERVICE_NAME), new binder::XposedService(true), true);
#else
err = sm->addService(String16(XPOSED_BINDER_SYSTEM_SERVICE_NAME), new binder::XposedService(true));
#endif
if (err != NO_ERROR) {
ALOGE("Error %d while adding system service %s", err, XPOSED_BINDER_SYSTEM_SERVICE_NAME);
exit(EXIT_FAILURE);
}
// The app service can be registered directly
#if PLATFORM_SDK_VERSION >= 16
err = sm->addService(String16(XPOSED_BINDER_APP_SERVICE_NAME), new binder::XposedService(false), true);
#else
err = sm->addService(String16(XPOSED_BINDER_APP_SERVICE_NAME), new binder::XposedService(false));
#endif
} else {
// We have to register the app service by using the already running system service as a proxy
sp<IBinder> systemBinder = sm->getService(String16(XPOSED_BINDER_SYSTEM_SERVICE_NAME));
sp<binder::IXposedService> xposedSystemService = interface_cast<binder::IXposedService>(systemBinder);
err = xposedSystemService->addService(String16(XPOSED_BINDER_APP_SERVICE_NAME), new binder::XposedService(false), true);
}
// Check result for the app service registration
if (err != NO_ERROR) {
ALOGE("Error %d while adding app service %s", err, XPOSED_BINDER_APP_SERVICE_NAME);
exit(EXIT_FAILURE);
}
#if XPOSED_WITH_SELINUX
// Initialize the memory-based Zygote service
if (xposed->isSELinuxEnabled) {
pthread_t thMemBased;
if (pthread_create(&thMemBased, NULL, &membased::looper, NULL) != 0) {
ALOGE("Could not create thread for memory-based service: %s", strerror(errno));
exit(EXIT_FAILURE);
}
}
#endif // XPOSED_WITH_SELINUX
sp<ProcessState> ps(ProcessState::self());
ps->startThreadPool();
#if PLATFORM_SDK_VERSION >= 18
ps->giveThreadPoolName();
#endif
IPCThreadState::self()->joinThreadPool();
}
bool checkMembasedRunning() {
// Don't let any further forks inherit this mapping
membased::restrictMemoryInheritance();
// Ensure that the memory based service is running
if (!membased::waitForRunning(5)) {
ALOGE("Zygote service is not running, Xposed cannot work without it");
return false;
}
return true;
}
bool startAll() {
bool useSingleProcess = !xposed->isSELinuxEnabled;
if (xposed->isSELinuxEnabled && !membased::init()) {
return false;
}
// system context service
pid_t pid;
if (useSingleProcess) {
ALOGD("Using a single process for Xposed services");
} else if ((pid = fork()) < 0) {
ALOGE("Fork for Xposed service in system context failed: %s", strerror(errno));
return false;
} else if (pid == 0) {
systemService();
// Should never reach this point
exit(EXIT_FAILURE);
}
// app context service
if ((pid = fork()) < 0) {
ALOGE("Fork for Xposed service in app context failed: %s", strerror(errno));
return false;
} else if (pid == 0) {
appService(useSingleProcess);
// Should never reach this point
exit(EXIT_FAILURE);
}
if (xposed->isSELinuxEnabled && !checkMembasedRunning()) {
return false;
}
return true;
}
#if XPOSED_WITH_SELINUX
bool startMembased() {
if (!xposed->isSELinuxEnabled) {
return true;
}
if (!membased::init()) {
return false;
}
pid_t pid;
if ((pid = fork()) < 0) {
ALOGE("Fork for Xposed Zygote service failed: %s", strerror(errno));
return false;
} else if (pid == 0) {
xposed::setProcessName("xposed_zygote_service");
xposed::dropCapabilities();
if (setcon(ctx_app) != 0) {
ALOGE("Could not switch to %s context", ctx_app);
exit(EXIT_FAILURE);
}
membased::looper(NULL);
// Should never reach this point
exit(EXIT_FAILURE);
}
return checkMembasedRunning();
}
#endif // XPOSED_WITH_SELINUX
} // namespace service
} // namespace xposed