Does Android Studio have an NDK memory viewer? - android

I am porting a C library code for windows into android
When I create a dynamically allocated array in the NDK C code, the variables viewer window only shows me the address of the first element, and the value of the first element
I would like to see all the array's members in the phone's memory
Is there a memory viewer or something similar for NDK in android studio?
Or as an alternative, can I do some kind of memory dump in the lldb console?

You can print a dynamically allocated int array using LLDB print (in short p) command like below:(modify the size and type according to your own case)
(lldb) print *(int (*)[5])foo2
It will give output all the elements of the int array. See below screenshot:
For a GUI style, you can select Variables tab and add a new watch using similar statement as command line said above, see below screenshot:
And then:
Unfold the watched statement, you will see all the elements as below:
Edit #1
Using parray command is simpler:
(lldb) parray 5 foo2
(int *) $5 = 0x000072e200e2da70 {
(int) [0] = 20
(int) [1] = 8
(int) [2] = 55
(int) [3] = 6
(int) [4] = 52
}

Related

Understanding how rootadb finds method call in ELF binary

The android debug bridge daemon adbd that runs on Android devices may be compiled without root support (ALLOW_ADBD_ROOT=0).
There is a tool called rootadb which is able to patch an existing adbd binary by (as I understood it) replacing the calls to setuid() and setgid() with NOP instructions, effectively preventing it from dropping its privileges.
I don't understand how the code finds the place of the syscalls inside the binary.
As far as I see, it iterates over the all the bytes and checks if the bytes match something:
u32 *sgid = (u32*)&setgid;
int fd = open( "/sbin/adbd", O_RDWR );
fstat( fd, &st );
buf = memalign( 32, st.st_size );
read( fd, buf, st.st_size );
lseek64( fd, 0, SEEK_SET );
for( start = buf, end = start + st.st_size - 0x20; start < end; start++ )
if( !memcmp( &start[1], &sgid[1], sizeof( u32 ) * 2 ) )
memcpy( &start[1], patch, sizeof( patch ) );
How does this work?
With what kind of data are sgid and __setuid actually filled?
I'm not 100% sure, but I have a reasonable idea.
The first line of code loads a pointer to the address of setgid, and treats it as a 32 bit pointer.
The loop iterates over the binary, and looks for occurrences of 8 bytes that equal address of the setgid function. If it finds one, it applies the patch, starting at the first byte of that location.
With what kind of data are sgid and __setuid actually filled?
'u32 *sgid' contains the address of the function 'setgid' and 'u32 *cap' contains the address of 'capset'. __setuid is the function itself but written without the parenthesis '()' we can retrieve the function's address.
I am confident that 0xe3a00000 is not an address to any function's stack frame. And it doesn't point to any location in memory.
With the information given I think 0xe3a00000 in 'patch' is used in the program to restore the state after the sub-routine call and prevent operations that happens after the call,
u32 patch[] =
{
0xe3a00000,
0
};
Below is the snippet that searches and replaces instructions following the call,
for( start = buf, end = start + st.st_size - 0x20; start < end; start++ )
if( !memcmp( &start[1], &sgid[1], sizeof( u32 ) * 2 ) )
memcpy( &start[1], patch, sizeof( patch ) );
Here the next 8 bytes from &sgid[1] should have state information along with the jump instructions to setgid function which is replaced by instruction in patch.
This effectively results in no-op. This is my understanding.
Please check how stack and frame tends to grow in android architecture also about the prologue and epilogue of the functions in this architecture. It will point you in the right direction as to why &sgid[1] (or sgid + 4 bytes) was used.
You could also refer,
https://softwareengineering.stackexchange.com/questions/195385/understanding-stack-frame-of-function-call-in-c-c
https://en.wikipedia.org/wiki/Call_stack#Stack_and_frame_pointers

Print strings on Apex3 using printer command language

How to print strings on Apex3 using printer command language or SDK?
I created a library for android application to print Bitmap images on mobile thermal printers:
Apex3, 3nStar, PR3, Bixolon, Sewoo LK P30 using appropriate SDKs.
It works fine but pretty slow, every ticket of 30 cm length takes 20-40 secs to print (it depends on type of printer).
For 3nStar and Apex3 I started to do improvements to speed up a printing.
For 3nStar I developed a class which prints a header logo and formatted text with spanish characters.
(different alignments and different fonts for different parts of a ticket)
so, the ticket looks very similar as Bitmap image but a printing time is only 6 secs.
Now I have to do the same but with Apex3. And here I got stuck.
How I do it on 3nStar for strings:
I send in outputStream bytes which are commands for printer what to do.
outputStream.write(some_bytes)
First command always is
{0x1b, 0x74, 40} //Esc t ( -- [ISO8859-15 (Latin9)]
to print spanish characters.
Then, in a loop, for n strings:
I choose a font
{0x1B, 0x21, 0x00}//Esc ! 0 -- 0 is normal, 8 is bold etc.
where changing last byte I print different fonts: normal, bold, two height, two width and combined fonts.
Next I choose an alignment
{0x1b, 0x61, 48} //Esc a 48 for left, 49 for center, 50 for right
Then I convert a string in bytes using ISO_8859_1 to print spanish characters and also write in outputStream.
outputStream.write(messageString.getBytes(StandardCharsets.ISO_8859_1))
And last byte to send is
{0x0a} // Move on next line
And the above approach doesn't work with Apex3, also I failed using
http://www.old.adtech.pl/upload/Extech_Printer_Command_Language%20Rev_H_05062009.pdf
even though on page 1 of that book is written that is fit for Apex3.
I think I miss something, I start to see how to do it using some SDK feature of Android_SDK_ESC_V1.01.17.01PRO.jar
but I would prefer to do that using direct writing of bytes.
Answers I found from this
manual
Shortly differences with the approach that I described for 3nStar are:
1)Before printing set a char set
ESC F 1 //Esc t - for 3nStar
2)Set a font for text, for example
ESC K 1 3 CR //ESC F 1 - for 3nStar
3)Send a line of text with alignment
For 3nStar I can use an alignment command before sending a text, like
ESC 1 49 //Centering
But for Apex3 I have to know a line length which depends on type of font, also a length of printing string,
then I get
freeSpace = (lineLength - printingString)
and set spaces at the begining of a line (right alignment),
at the end (left alignment) or devide them (centering).
So, for both types of printers I use the same logic which differs only in 3 places.
It is simplified explanation as a real code includes several classes with hundreds lines of code.

DACR read/write on ARM

I am trying to read and write the DACR on an ARM device running Linux (Android on nexus 5 :)). I have a kernel module. The relevant instructions are as follows:
MRC p15, 0, <Rd>, c3, c0, 0 ; Read DACR
MCR p15, 0, <Rd>, c3, c0, 0 ; Write DACR
I am using C code in the module with assembly inside. I wrote the following to read the current DACR value:
unsigned int x = 0;
__asm__("MRC p15, 0, r1, c3, c0, 0;" : "=r" (x));
printk(KERN_INFO "DACR read - value = %u", x);
The above didn't crash the kernel, and the value read out was 3920437248.
I am not able to write the instruction for DACR write correctly. I was trying to follow from this question and did the following (to write all 1's to DACR to test), but the device crashed and rebooted:
__asm__("MVN r1, #0;");
__asm__("MCR p15, 0, r1, c3, c0, 0;");
Can anyone advice how to write to DACR correctly ?
Also how to parameterize the above instruction - e.g. for using value of x to initialize DACR, would the following be correct:
__asm__("MCR p15, 0, %0, c3, c0, 0;" :: "r" (x));
Oh, you're writing the register correctly alright.
The trouble is, the question is like this:
I am trying to engage reverse gear on my car driving on the motorway. I was trying to follow the directions in the handbook and moved the gear lever firmly into the "R" position, but my gearbox is now in bits all over the road. Can anyone advise how to engage reverse gear correctly?
You're on a live system. The kernel is already using domains. It needs access permissions to work correctly. If you declare open season by marking everything as Manager and removing all permission checks, copy-on-write no longer works; every process starts trashing the zero page via their initial mappings instead of triggering the allocation of real backing pages; cats and dogs live together; chaos.

android NDK: Is optimizing array copy worth it?

For a school project I am creating an android app that involves streaming image data. I've finished all the requirements about a month and a half early, and am looking for ways to improve my app. One thing I heard of is using the android NDK to optimize heavily used pieces of code.
What my app does is simulate a live video coming in over a socket. I am simultaneously reading the pixel data from a UDP packet, and writing it to an int array, which I then use to update the image on the screen.
I'm trying to decide if trying to increase my frame rate (which is about 1 fps now, which is sufficient for my project) is the right path to follow for my remaining time, or if I should instead focus on adding new features.
Anyway, here is the code I am looking at:
public void updateBitmap(byte[] buf, int thisPacketLength, int standardOffset, int thisPacketOffset) {
int pixelCoord = thisPacketOffset / 3 - 1;
for (int bufCoord = standardOffset; bufCoord < thisPacketLength; bufCoord += 3) {
pixelCoord++;
pixelData[pixelCoord] = 0xFF << 24 | (buf[bufCoord + 2] << 16) & 0xFFFFFF | (buf[bufCoord + 1] << 8) & 0xFFFF | buf[bufCoord] & 0xFF;
}
}
I call this function about 2000 times per second, so it definitely is the most used piece of code in my app. Any feedback on if this is worth optimizing?
Why not just give it a try? There are many guides to creating functions using NDK, you seem to have a good grasp of the reasoning to do so and understand the implications so it should be easy to translate this small function.
Compare the two approaches, you will no doubt learn something which is always good, and it will give you something to write about if you need to write a report to go with the project.

No refrence for instructions strneh, lsreq, streqb

I was looking at strcpy.S file in android platform at path libc/arch-arm/bionic, in this file there are many arm instructions which i am not able to understand, i am also referring ARM System Developers Guide.
Here except "tst" and "tstne" i am not able to find any refrence for others in any book or ARM refrence manual.
tst r2, #0xff00
iteet ne
strneh r2, [ip], #2
lsreq r2, r2, #8
r2, [ip]
tstne r2, #0xff
Not only these instructions there are many others in different files also.
Does anyone have any idea what these instructions are ?
The first instructions it the it-instruction from the thumb instructions set.
iteet ne
This instruction marks the next three instructions to be conditional executable. The last three characters of the instruction make a pattern consisting of e (else) or t (then). The operand 'ne' specifies the condition to be evaluated.
The other three instructions are ordinary ARM instructions with conditionals:
strneh r2, [ip], #2 ; store halfword if not equal
lsreq r2, r2, #8 ; logical shift right if equal
tstne r2, #0xff ; test if not equal
These are the three instructions affected by the it-instruction. They come with ne/eq conditional flags as well.
As you can see the conditions of the it-instructions and the conditions of the other three instructions are in conflict to each other. This is a bug in the code. Most likely it hasn't been discovered before because the code-snippet is from the ARM-big-endian code, and I know of no android phone that uses ARM in big endian.
Btw, it's worthwhile to know why the conditions are given in the it-instruction and in the instructions itself. This is part of the unified arm assembly standard. On the ARM you have two modes of operation: Thumb mode (uses It-instruction, less powerful) and ARM-mode (more powerful, uses condition-flags in the instructions itself).
If you limit yourself to the capabilities of the thumb-mode it is possible to write code that would compile in thumb and ARM-mode. This is done here.
If you assemble for Thumb-mode the It-instruction will be used to control the conditions of the next three instruction, and the conditions within the instructions gets ignored. If you assemble to ARM-instruction set the It-instruction gets ignored and the conditions from the instruction itself will become active.
This works well as long as the it-instruction and the conditions in the arm-instructions match. As I said before this is not the case here, so it will either not work in thumb-mode, arm-mode or both :-)
strneh is a store command with some conditional execution/size specifier suffixes. The ARM docs are a good place to start: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/Chdehgih.html
If you google "arm conditional execution", you'll find a number of blogs/articles that may also help: http://blogs.arm.com/software-enablement/258-condition-codes-2-conditional-execution/
As for your *strneh" instruction:
str = store
ne = execute if not equal (Z flag clear)
h = perform a half-word operation

Categories

Resources