I am trying to add a native service written in C++ to the AOSP build.
The first thing I did was to create a native service and client to the AOSP build.
This worked as expected. I could start the service within an adb shell and call it via binder on a adb shell.
The trouble started when I wanted to start my service with init.
I added a .rc file to my build
service myp /system/bin/myp_service
class main
This did the the trick so that init tried to start it but it failed because of SELinux policies.
So I added a file_contexts to my device tree and added:
/system/bin/myp_service u:object_r:myp_exec:s0
Next I added a myp.te file and added:
type myp, domain;
type myp_exec, exec_type, file_type;
type myp_service, service_manager_type;
init_daemon_domain(myp)
net_domain(myp)
binder_use(myp)
binder_service(myp)
add_service(myp, myp_service)
binder_call(myp, binderservicedomain)
binder_call(myp, appdomain)
allow myp myp_service:service_manager add;
And finally I added a service_contexts file with:
myp u:object_r:myp_service:s0
This finally made my service successfully start at boot time.
Unfortunalty I cannot use binder against this service. When I try to connect to the service with my client the call
defaultServiceManager()->getService(String16("Demo"))
returns a null pointer.
I cannot find any hints in the dmesg.
So I assume I am still missing something for the SElinux but I have no clue what I am missing.
If I shutdown the SELinux with setenforce and restart the service then it works fine.
Can anyone give me a hint what I am missing for SELinux or where I can get more information about which policy blocked something?
You could see the denials like this:
adb logcat | grep "SELinux : avc" > /tmp/logs
Get sepolicy current file. (Can be taken from device this way adb pull sepolicy.
Using audit2allow (located in AOSP source code: external/selinux/prebuilts/bin/audit2allow or in SDK tools. Do this: cat /tmp/logs | .external/selinux/prebuilts/bin/audit2allow -p sepolicy
The audit2allow tool will tell you what permission you are missing for the logcat extracted and the current sepolicy file, watch-out because you could need to do this several times since fixing some permissions will show the next ones required.
If you have a userdebug kind of build you could get setenforce 0, logcat with it and all the denials will be in logcat even if you will be permited to do the operation desired. This will leave the audit2allow iterations required in 1.
For anyone who came across this problem, please make sure your service_contexts file is successfully merged with stock service_contexts file. If you're building your service for Android O or later, please put this file inside a folder and refer to it in your Makefile by BOARD_PLAT_PRIVATE_SEPOLICY_DIR1. And you don't need to add allow myp default_android_service:service_manager add if the build system does pick up your service_contexts.
Also, about the domain.te violation problem, you probably want to attach one of the coredomain or appdomain attribute to your domain 2 with typeattribute <your_domain> <attribute>;.
Finally, please double check the following built files to make sure you don't leave any sepolicy configurations out in the final build:
$(AOSP_ROOT)/out/target/product//obj/ETC/file_contexts.bin_intermediates/file_contexts.*
$(AOSP_ROOT)/out/target/product/potter/obj/ETC/plat_service_contexts_intermediates/service_contexts.*
$(AOSP_ROOT)/out/target/product/potter/obj/ETC/sepolicy_neverallows_intermediates/policy.conf
Related
I'm trying to run valgrind on an android OS but it couldn't start and it shows this errors that i couldn't find how to solve:
valgrind: Startup or configuration error:
Can't create client cmdline file in /tmp/valgrind_proc_87_cmdline_876a7612
valgrind: Unable to start up properly. Giving up.
Thanks in advance !
I tried to change the default path that valgrind use and which is shown on the error log but i couldn't make it
The problem is happening in the code where the Valgrind host is creating a fake /proc/<pid>/cmdline.
This file should be created in the location given by the first valid item in the following list:
The TMPDIR environment variable
The constant VG_TMPDIR that gets baked into the binary via a configure time option. This defaults to /tmp but can be overriden using configure --with-tmpdir=/your/tmp/dir. That would require that you get the Valgrind source and configure and build it. It is possible that you are using a package that was built using this option and is not compatible with your system.
Last resort, "/tmp"
All of the above checks just test that the string is non-null and not empty. They do not test for the existance and accessibility of the directory. That gets determined by the Valgrind version of mkstemp and the error message comes from 'valgrind_main'.
Valgrind needs to create a file TMPDIR/valgrind_proc_PID_cmdline_RAND where TMPDIR is described above, PID is the pid of the Valgrind process and RAND is a random number.
There is at least one other similar files that get created, for auxv.
There are no Valgrind command line options to turn off the creation of these files.
I am getting my android's logcat spammed with these warnings.(rooted with magisk)
10-15 22:02:29.039 12944 12944 W kworker/0:4: type=1400 audit(0.0:87190): avc: denied { read write } for name="sde73" dev="tmpfs" ino=28978 scontext=u:r:kernel:s0 tcontext=u:object_r:oem_device:s0 tclass=blk_file permissive=0
I was looking into the following doc to see how could i fix this issue, but cannot figure it out.
https://source.android.com/security/selinux/device-policy
https://source.android.com/security/selinux/validate
https://source.android.com/security/selinux/concepts
https://source.android.com/security/selinux/implement
https://gist.github.com/msfjarvis/ec52b48eb2df1688b7cbe32bcd39ee5f
https://android.stackexchange.com/questions/207484/how-to-fix-selinux-avc-denied-errors-when-launching-dnscrypt-as-init-d-script
https://source.android.com/security/selinux/customize#android-o
https://android.stackexchange.com/questions/218911/how-to-add-selinux-policy-on-a-user-debug-rom-that-has-split-policy-scheme
https://android.stackexchange.com/questions/214839/how-to-run-an-android-init-service-with-superuser-selinux-context
https://topjohnwu.github.io/Magisk/tools.html#magiskpolicy
https://topjohnwu.github.io/Magisk/details.html#magisk-booting-process
https://topjohnwu.github.io/Magisk/guides.html#boot-scripts
I looked in /dev, but i do not have anything similar.
android# ls -l /dev/ | grep sd
#returns nothing
The inode resolves to this file:
find /sys -xdev -inum 28978
/sys/firmware/devicetree/base/__symbols__/sb_7_tx
However on next reboot resolves to other file but the errors are always related to one single inode.
I suppose i should add this rule in a .te file
allow kernel oem_device:blk_file {read write};
adb pull /sys/fs/selinux/policy
adb logcat -b all -d | audit2allow -p policy
#this confirms the rule
I found some related files to selinux in this dump:
https://git.rip/dumps/oneplus/oneplus7tpro/-/find_file/hotdog-user-10-QKQ1.190716.003-2009281542-release-keys
but i am not very sure where should i add the rule..possibly somewhere in /vendor/etc/selinux..
Does anyone know which are the steps to fix these warnings and maybe further dig into the investigation why they occur in the first place?
Thanks
The reason why it shows is straightforward from the error. kernel is trying to read/write a blk_file labeled with oem_device type.
At this point you have couple of options:
Add allow rule if you want to allow the access to happen.
Add dontaudit rule, if you want to just suppres the log. See
here
The rule should be added into kernel.te.
Usually these custom things go into device/XXXXXX, depending on the vendor. For example in my tree, for a rockchip device, I'd modify /device/rockchip/common/sepolicy/vendor/kernel.te
To rebuild policies you would:
source build/envsetup.sh
lunch-yourTarget
mmm system/sepolicy
And to flash them into the system ( if you're userdebug and can remount it ):
adb root
adb remount
adb push out/target/product/YOUR_DEVICE/vendor/etc/selinux /vendor/etc/
adb push out/target/product/YOUR_DEVICE/system/etc/selinux /system/etc/
adb shell sync
adb reboot
If you can't push them, you'll need to rebuild and flash the system
I managed to fix the warnings with this command:
magiskpolicy --live 'allow kernel oem_device blk_file {read write open}'
'open' right was also granted because another warning related to it would appear after allowing only read/write.
Still I cannot understand:
why is kernel trying to access this
what exactly is trying to access
shouldn't magisk take care of the selinux policies related to such low level grants such as kernel
not sure how can i make this fix permanent (to persist upon reboot). From my research it looks like i have to modify a certain file in boot.img, repack it and push it back to android.
On this page:
https://topjohnwu.github.io/Magisk/tools.html
it's specified a tool magiskboot which should be used for such patching but I do not have it.
A tool to unpack / repack boot images, parse / patch / extract cpio, patch dtb, hex patch binaries, and compress / decompress files with multiple algorithms.
I will come back with any findings..
UPDATE:
I managed to permanently add the fixes at boottime with a post-fs-data script that runs during booting process. It might not be 100% fix because, the boot image should be patched instead so that magiskinit loads the policies even before init is executed, but it still however fixes the warnings in logcat after the boot process ended
REF:
https://topjohnwu.github.io/Magisk/details.html#magisk-booting-process
https://topjohnwu.github.io/Magisk/guides.html#boot-scripts
su -
cd /data/adb/post-fs-data.d
touch fix_selinux.sh
chmod +x fix_selinux.sh
vi fix_selinux.sh #add this line (and any other rules you need):
/sbin/magiskpolicy --live 'allow kernel oem_device blk_file {read write open}'
I am currently trying to insmod a kernel module during the end of the boot process, and so I've created the following entries in init.rc:
on post_late_start
start myscript
on nonencrypted
class_start late_start
trigger post_late_start
on property:void.decrypt=trigger_restart_framework
class_start main
class_start late_start
trigger post_late_start
service myscript /data/my_sh.sh
disabled
oneshot
Then in my /data directory my_sh.sh has the following:
#!/system/bin/sh
log -t mytag -p V "Hello World!"
insmod mymodule.ko mod_parameter=arg
But when I run -- sometimes I do not see the "Hello World" tag when I logcat -s "mytag" and of course, the insmodded module is not installed either.
What is the proper way of late-inserting a kernel module (it needs to go in after network is up and /data is mounted). And further -- how do I get the output of insmod into the log so that I can debug? Any help is appreciated and I can post more details if necessary.
At least since Froyo and still in Lollipop, Android init implements insmod in system/core/init/buildin.c. It is supposed to work directly in an init*.rc file:
on boot
insmod /system/lib/modules/your-module.ko.
However, at least in Lollipop 5.1, it no longer works, as SELinux rules are enforced. init does not have the required sys_module permission. Therefore the underlying init_module system call returns EPERM. This is never reported to anywhere. The only symptom is that insmod commands now fail to load the module, always.
I opened an AOSP issue on this. According to Google, this works as intended. If you want to use kernel modules when SELinux is enforced (which they strongly advice against), you must yourself add the required SELinux permission to init.
I am not sure about your log, but to insmod you need to give the exact path to the module, because I dont think you will be having mymodule.ko residing in the same place as init.rc is there. So try to give the full path of your ko file.
Generally it resides in /lib/modules/youdrivername.ko
so check it here first.
I am getting the above error:
error opening trace file: No such file or directory (2)
when I run my android application on the emulator. Can someone tell me what could be the possible reason for this?
I am using android-sdk-20 and below lines are added to AndroidManifest.xml
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" />
I have also added the line:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
since I thought that there may be some issue with writing to the sd card.
It happens because you have not installed the minSdkVersion or targetSdkVersion in you’re computer. I've tested it right now.
For example, if you have those lines in your Manifest.xml:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
And you have installed only the API17 in your computer, it will report you an error. If you want to test it, try installing the other API version (in this case, API 8).
Even so, it's not an important error. It doesn't mean that your app is wrong.
Sorry about my expression. English is not my language.
Bye!
I think this is the problem
A little background
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.
It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application
How do I enable it:
There are two ways to generate trace logs:
Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop
logging of trace information to disk. This option is very precise
because you can specify exactly where to start and stop logging trace
data in your code.
Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather
specify when to start and stop logging with DDMS. Although you have
less control on exactly where logging starts and stops, this option is
useful if you don't have access to the application's code, or if you
do not need precise log timing.
But the following restrictions exist for the above
If you are using the Debug class, your application must have
permission to write to external storage (WRITE_EXTERNAL_STORAGE).
If you are using DDMS: Android 2.1 and earlier devices must have an SD
card present and your application must have permission to write to the
SD card. Android 2.2 and later devices do not need an SD card. The
trace log files are streamed directly to your development machine.
So in essence the traceFile access requires two things
1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure
2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.
What do I do with this error:
Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on.
But in general this doesn't affect you directly, you should check direct application logs/errors.
Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.
Additional information on Traceview:
Copying Trace Files to a Host Machine
After your application has run
and the system has created your trace files .trace on
a device or emulator, you must copy those files to your development
computer. You can use adb pull to copy the files. Here's an example
that shows how to copy an example file, calc.trace, from the default
location on the emulator to the /tmp directory on the emulator host
machine:
adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To
run Traceview and view the trace files, enter traceview
. For example, to run Traceview on the example files
copied in the previous section, use:
traceview /tmp/calc Note: If you are trying to view the trace logs of
an application that is built with ProGuard enabled (release mode
build), some method and member names might be obfuscated. You can use
the Proguard mapping.txt file to figure out the original unobfuscated
names. For more information on this file, see the Proguard
documentation.
I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug
More in the docs
Try removing the uses-sdk part form AndroidManifest.xml file. it worked for me!
Don't use the Android Virtual Device with too low configuration. Let it be medium.
Write all your code below this 2 lines:-
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
It worked for me without re-installing again.
I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.
What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).
Additional information:
while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:
"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none
WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img
I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
Actually, the problem is that either /sys/kernel/debug is not mounted, or that the running kernel has no ftrace tracers compiled in so that /sys/kernel/debug/tracing is unavailable. This is the code throwing the error (platform_frameworks_native/libs/utils/Trace.cpp):
void Tracer::init() {
Mutex::Autolock lock(sMutex);
if (!sIsReady) {
add_sysprop_change_callback(changeCallback, 0);
const char* const traceFileName =
"/sys/kernel/debug/tracing/trace_marker";
sTraceFD = open(traceFileName, O_WRONLY);
if (sTraceFD == -1) {
ALOGE("error opening trace file: %s (%d)", strerror(errno), errno);
sEnabledTags = 0; // no tracing can occur
} else {
loadSystemProperty();
}
android_atomic_release_store(1, &sIsReady);
}
}
The log message could definitely be a bit more informative.
I am getting the above error:
error opening trace file: No such file or directory (2)
when I run my android application on the emulator. Can someone tell me what could be the possible reason for this?
I am using android-sdk-20 and below lines are added to AndroidManifest.xml
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" />
I have also added the line:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
since I thought that there may be some issue with writing to the sd card.
It happens because you have not installed the minSdkVersion or targetSdkVersion in you’re computer. I've tested it right now.
For example, if you have those lines in your Manifest.xml:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
And you have installed only the API17 in your computer, it will report you an error. If you want to test it, try installing the other API version (in this case, API 8).
Even so, it's not an important error. It doesn't mean that your app is wrong.
Sorry about my expression. English is not my language.
Bye!
I think this is the problem
A little background
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.
It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application
How do I enable it:
There are two ways to generate trace logs:
Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop
logging of trace information to disk. This option is very precise
because you can specify exactly where to start and stop logging trace
data in your code.
Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather
specify when to start and stop logging with DDMS. Although you have
less control on exactly where logging starts and stops, this option is
useful if you don't have access to the application's code, or if you
do not need precise log timing.
But the following restrictions exist for the above
If you are using the Debug class, your application must have
permission to write to external storage (WRITE_EXTERNAL_STORAGE).
If you are using DDMS: Android 2.1 and earlier devices must have an SD
card present and your application must have permission to write to the
SD card. Android 2.2 and later devices do not need an SD card. The
trace log files are streamed directly to your development machine.
So in essence the traceFile access requires two things
1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure
2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.
What do I do with this error:
Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on.
But in general this doesn't affect you directly, you should check direct application logs/errors.
Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.
Additional information on Traceview:
Copying Trace Files to a Host Machine
After your application has run
and the system has created your trace files .trace on
a device or emulator, you must copy those files to your development
computer. You can use adb pull to copy the files. Here's an example
that shows how to copy an example file, calc.trace, from the default
location on the emulator to the /tmp directory on the emulator host
machine:
adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To
run Traceview and view the trace files, enter traceview
. For example, to run Traceview on the example files
copied in the previous section, use:
traceview /tmp/calc Note: If you are trying to view the trace logs of
an application that is built with ProGuard enabled (release mode
build), some method and member names might be obfuscated. You can use
the Proguard mapping.txt file to figure out the original unobfuscated
names. For more information on this file, see the Proguard
documentation.
I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug
More in the docs
Try removing the uses-sdk part form AndroidManifest.xml file. it worked for me!
Don't use the Android Virtual Device with too low configuration. Let it be medium.
Write all your code below this 2 lines:-
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
It worked for me without re-installing again.
I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.
What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).
Additional information:
while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:
"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none
WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img
I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
Actually, the problem is that either /sys/kernel/debug is not mounted, or that the running kernel has no ftrace tracers compiled in so that /sys/kernel/debug/tracing is unavailable. This is the code throwing the error (platform_frameworks_native/libs/utils/Trace.cpp):
void Tracer::init() {
Mutex::Autolock lock(sMutex);
if (!sIsReady) {
add_sysprop_change_callback(changeCallback, 0);
const char* const traceFileName =
"/sys/kernel/debug/tracing/trace_marker";
sTraceFD = open(traceFileName, O_WRONLY);
if (sTraceFD == -1) {
ALOGE("error opening trace file: %s (%d)", strerror(errno), errno);
sEnabledTags = 0; // no tracing can occur
} else {
loadSystemProperty();
}
android_atomic_release_store(1, &sIsReady);
}
}
The log message could definitely be a bit more informative.