SoFunction
Updated on 2025-04-04

Android Miscellaneous Notes: Share the method of adding log to C++ files

1. Add header file
Copy the codeThe code is as follows:

#include <utils/>  
//or
#include <cutils/> 

At this time, you can use ALOGE/ALOGI/ALOGW and other methods to print out the log
However, some places cannot be used in this way because they rely on the libutils libctuils library
In mk file, please add the following dependency compilation
Copy the codeThe code is as follows:

#LOCAL_MODULE := ... ...  
#base_intermediates := $(call local-intermediates-dir) //Add under this line, this seems to be looking for dependency files.
LOCAL_SHARED_LIBRARIES += \ 
        libutils libcutils 
    ... ... 
include $(BUILD_SHARED_LIBRARY) //Above this line, the compilation starts

2. The usual stack
Copy the codeThe code is as follows:

android::CallStack stack; 
(1); 
(""); 

This requires adding a header file, but one thing to pay special attention to is that this header must be added at the end of all headers, otherwise it will not be used, especially when looking at webkit in the Android source code. The header files that need to be added are as follows:
Copy the codeThe code is as follows:

#include <utils/> 

If you have something to do today, please make up for it later. If you have a better or special situation, please recommend it.
++Alternative stack
This method is file-controllable. By reading and writing files in Android devices, and then assigning null pointers, the purpose of file control can be achieved.
The advantage of this method is that you can add this log as long as you are C and C++ files, which is dependable and convenient! There is also a disadvantage. The log can only run to the place you added, because the library crashes and the subsequent ones cannot run.
The implementation code is as follows:
Copy the codeThe code is as follows:

FILE *fp = NULL; //Notes to be paid
fp = fopen("data/test", "r"); 
if(NULL == fp) 

return false; //Use when the return value is required
} esle { 
    fclose(fp); 
    int *fp = NULL; 
*fp = 100;  //The null pointer assignment error occurs, and the sample is just wrong.
return false; //Use when the return value is required


Generally, if the library crashes, you cannot see the stack. We can view the specific stack through disassembly.
There are two sets of libraries compiled in android: one set is unsigned and cannot be viewed, and the other set is signed. This is what we are looking at.
After the signed compile is compiled, it is under the path (\out\target\product\generic\symbols\system\lib)
The disassembly tool with arm is included in Android. After setting up the environment, it can be used normally. The commands are as follows:
Copy the codeThe code is as follows:

arm-eabi-addr2line -f -e **.so Address 1 Address 2 ... ...