C Blocks indirection and misalignment - objective-c

The following code throws an EXC_BAD_ACCESS error (specifically a general protection fault error) and I would like to know why you cannot misalign a block pointer and execute it.
#include <stdio.h>
int main(int argc, const char * argv[])
{
void (^blocky)() = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
blocky = *(&blocky+1);
blocky = *(&blocky-1);
blocky();
return 0;
}
But the following works:
#include <stdio.h>
int main(int argc, const char * argv[])
{
void (^blocky)() = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
blocky = *(&blocky+1-1);
blocky();
return 0;
}
Edit (answer to misaligning code blocks):
If you treat a block like a structure, you can find that the value that points to the executable code in memory is offset 16 bytes from the start of the block and is 8 bytes long.
You are able to change this value effectively pointing execution to another place in memory. Generally, this will crash.
Assuming you know the specific address in memory for another piece of executable code, you may direct it there.
Why this is useful:
It isn't. Never do this. Really. Never.

The pointer manipulation in the first example is wrong. Try this:
#include <stdio.h>
typedef void (^blocky_t)();
int main(int argc, const char * argv[])
{
blocky_t blocky = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
printf("blocky=%p\n", blocky);
blocky = (blocky_t)((char *)blocky + 1);
printf("blocky=%p\n", blocky);
blocky = (blocky_t)((char *)blocky - 1);
printf("blocky=%p\n", blocky);
blocky();
return 0;
}
$ clang -o blocky blocky.c
$ ./blocky
blocky=0x10574d040
blocky=0x10574d041
blocky=0x10574d040
Hello!
Hello Again!
When I ran your code, I got:
blocky=0x10e0ba040
blocky=0x7fff51b46c10
blocky=0x1300000000
Where:
The first address is within the __TEXT segment of the program.
The second address is near the stack.
The third is who-knows-where.

Your question really has nothing to do with blocks. You're just manipulating pointers to local variables in a way that doesn't make sense.
First, you never use the block pointer that you assign to blocky. You take the address of the local variable blocky on the stack, and then add one word to it, and dereference it. Depending on the architecture, the stack probably grows down, which means this is before all the variables on the stack frame, and is probably the return address of the current stack frame. Or it may be something else. You then assign this value to blocky.
Then, you take the address of the local variable blocky on the stack again, and then subtract one word from it, and dereference it. Again, assuming the stack grows down, this might be past the end of the current stack frame, which would be garbage. You then assign this value to blocky. You then try to run this as a pointer to a block. Of course this doesn't work.
In the second piece of code, you take the address of the local variable blocky on the stack again, and then add and subtract one word from it (which of course is the pointer to the local variable blocky again), and dereference it (which is the value of blocky), and assign it to blocky. This operation does nothing.

Related

C++ Assigning a value to char *argv[] from inside a program

The customary way of passing values through argv in this declaration
int main(int argc, char* argv[]) {
is to pass it from your console through argv array into a program. I came across a situation where I wanted to achieve something different as follows. The program has the usual
int main(int argc, char* argv[]) {
declaration and inside my program I have a
function void foo(argv[1], 0).
Here is the layout and flow of my program's logic:
program ggg.cpp
:
void foo(char* x, int y) {
:
}//end foo
:
int main(int argc, char* argv[]) {
:
foo(argv[1], 0);
:
}//end main
(1) My normal method. Normally, when I compile the ggg.cpp program and my console input is:
ggg.exe . //the second input is a dot "."
the program runs fine (because argv[1] = '.' inside the program)
(2) However, I wanted to get innovative and execute the program as:
ggg.exe //here, the dot is not included
so that inside the program, I can assign the dot to argv[1] but I kept getting errors - no matter how I try other variations of the assignment statement.
By the way, I tried the assignment statement
argv[1]='.';
inside the main program (in method (2)) but it didn't work. I got an error message.
Background Information. I used to be very good in programming in my hay days but now I have forgotten a lot of things because I left coding for a very long time to do other things.

StringToCoTaskMemUni or StringToCoTaskMemAnsi methods can cause hang?

I have the below code in c++/CLI and observing hang while converting the .net string to char * using StringToCoTaskMemAnsi
const char* CDICashInStringStore::CDIGetStringVal( void )
{
unsigned int identifier = (unsigned int)_id;
debug(" cashincdistores--routing call to .Net for CDI String %d", identifier);
NCR::APTRA::INDCDataAccess::IStringValue^ stringValueProvider = (NCR::APTRA::INDCDataAccess::IStringValue^)GetStringProvider()->GetProvider();
String^ strValue = stringValueProvider->GetStringValue(identifier);
debug(" cashincdistores-- going to call StringToCoTaskMemAnsi);
IntPtr iPtr = Marshal::StringToCoTaskMemAnsi(strValue);
debug(" cashincdistores-- StringToCoTaskMemAnsi called);
// use a local (retVal is not needed)
const char * ansiStr = strdup((const char *) iPtr.ToPointer());
Marshal::FreeCoTaskMem(iPtr);
debug(" cashincdistores--got results %d %s",identifier,ansiStr);
// The returned memory will be free() 'ed by the user
return ansiStr;
}
In our logging I can see "cashincdistores-- going to call StringToCoTaskMemAnsi" and suspecting there is a hang after calling the 'StringToCoTaskMemAnsi' method.
Does there is a chance of hang in 'StringToCoTaskMemAnsi' marshalling method. what could cause the hang ?
Why are you using COM in the first place? You don't need any COM in that code.
Disclaimer: You should probably not be returning a const char * someone else will have to free from your function. That's a very easy way to produce memory leaks or multiple free errors.
Ignoring the disclaimer above, you have a couple possibilities:
First way:
#include <msclr/marshal.h>
msclr::interop::marshal_context context;
const char* strValueAsCString = context.marshal_as<const char*>(strValue);
// Probably bad
const char* ansiStr = strdup(strValueAsCString);
The strValueAsCString pointer will remain valid as long as context is in scope.
Another way:
#include <string>
#include <msclr/marshal_cppstd.h>
std::string strValueAsStdString = msclr::interop::marshal_as<std::string>(strValue);
// Probably bad
const char* ansiStr = strdup(strValueAsStdString.c_str());
Here, the std::string manages the lifetime of the string.
See Overview of Marshaling for reference.

Looping in OpenGL with glutTimerFunc(...)

I want to create a program that draws some objects to scene using OpenGL, where I am continually changing the position of those object manually. To achieve this, I need to run some kind of loop where on each loop, it changes the position of the objects, and then draws to the screen, before repeating.
Given that glutMainLoop() is a non-returning function, and is also compulsory to run an OpenGL program, I need to run my loop with some sort of timer.
Now my solution which works is similar to the following:
void Render()
{
// Draw some objects using OpenGL
// ......
// ......
}
void Loop
{
// Update the positions of the objects
// ......
// ......
glutPostRedisplay();
glutTimerFunc(1, Loop, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
GlutCreateWindow("Test");
glutDisplayFunc(Render);
glutMainLoop();
glutTimerFunc(1, Loop, 0);
}
However, I am not sure I understand why there is the need for the glutTimerFunc() call in main(). Why can I not just replace it with a direct call to Loop()?
For example:
int main(int argc, char** argv)
{
glutInit(&argc, argv);
GlutCreateWindow("Test");
glutDisplayFunc(Render);
glutMainLoop();
Loop();
}
This does not work. The objects do not move on the screen as expected, and furthermore, then OpenGL window is totally unresponsive; I cannot even close it by clocking the cross on the title bar.
Surely glutTimerFunc(1, Loop, 0); just calls Loop() in the same way I have done in the second example, so why does this not work...?
Basically, the glutTimerFunc waits for a number of milliseconds to pass before calling the callback (in your case, Loop()). In this way it acts like a refresh operation.
Check out →GLUT API for more detail
void glutTimerFunc(unsigned int numMilliseconds, functionCallback, value);
So, that means you can pass in something like this:
glutTimerFunc(1000 / SCREEN_FPS, Loop, 0);
For extra info on main loops
deWitter's Gameloop
However, as your project gets more complex, you might find that you want the objects in your scenes rendering at constant speed. In addition to the glutTmerFunc, you can make you animations work with elapsed time - found by calculating the difference between the current time and previously current time.
Hope this helps!
Here's a really simple glutTimerFunc() example from a real program.
I wanted to hi-jack the title bar for command input. When you typed stuff, it appeared in the title bar and when you pressed return, it executed the command. I wanted a blinking cursor.
char title[80]; // This is where our keystrokes go.
char * cursor = NULL; // This points to the cursor character.
void cursorBlink(int id) {
if (cursor) {
*cursor = (*cursor == ' ') ? '_' : ' ';
glutSetWindowTitle(title);
glutTimerFunc(1000.0, cursorBlink, 0);
}
}
This isn't quite the whole thing. The ESC key gets us into command line entry mode. This sets up the title string and the cursor pointer, and it also has to make the first call to cursorBlink() to get the loop started. When command entry is done, the cursor point gets set back to NULL, and the loop shuts itself down.
The cursorBlink argument is not used. This is common with simple animations. Don't worry about it.

Why can setting a Block variable inside an if statement cause a carsh?

I found an block example in the book "Effective Objective-C 2.0"
void (^block)();
if (/* some condition */) {
block = ^ {
NSLog(#"Block A");
};
} else {
block = ^ {
NSLog(#"Block B");
};
}
block();
The code is dangerous, and here is the explanation in the book:
The two blocks that are defined within the if and else statements are allocated within stack memory. When it allocates stack memory for each block, the compiler is free to overwrite this memory at the end of the scope in which that memory was allocated. So each block is guaranteed to be valid only within its respective if-statement section. The code would compile without error but at runtime may or may not function correctly. If it didn’t decide to produce code that overwrote the chosen block, the code would run without error, but if it did, a crash would certainly occur.
I don't understand the meaning of "If it didn’t decide to produce code that overwrote the chosen block, the code would run without error, but if it did, a crash would certainly occur."
Can someone explain and give examples?
The issue is similar to that of a C array being created locally to a function and then used after the function returns:
#import <Foundation/Foundation.h>
dispatch_block_t global_block;
int * global_arr;
void set_globals(void)
{
if( YES ){
global_block = ^{
NSLog(#"Summer is butter on your chin and corn mush between every tooth.");
};
int arr[5] = {1, 2, 3, 4, 5};
global_arr = arr;
}
}
void write_on_the_stack(int i)
{
int arr[5] = {64, 128, 256, 512, 1024};
int v = arr[3];
dispatch_block_t b = ^{
int j = i + 10;
j += v;
};
b();
}
int main(int argc, const char * argv[])
{
#autoreleasepool {
set_globals();
write_on_the_stack();
global_block();
NSLog(#"%d", global_arr[0]); // Prints garbage
}
return 0;
}
The space on the stack that was used to store the values of the array may be re-used for any purpose. I use the separate function here because it most reliably demonstrates the problem. For your exact case, with the if block and the access in the same function, the compiler is still free to re-use the stack space. It may not, but you can't rely on that. You're breaking the scope rules of the language (derived from C).
As Jesse Rusak and CrimsonChris pointed out in comments, though, with a Block-type variable compiled under ARC, the Block is created on the stack like the array, but copied off the stack (to the heap) when it's stored in a strong pointer. All object pointers, including your global, are strong by default.
If you were not compiling with ARC, this would be unreliable. I can't come up with a failing example with my current compiler, but again, it's breaking the rules and the compiler is under no obligation to do what you want.
Essentially what this is saying is that if there's code running on a separate thread, and something gets assigned to the area of memory currently used by block but before the block() call, then bad things will happen.
void (^block)();
if (/* some condition *)) {
block = ^ {
NSLog(#"Block A");
}
} else {
block = ^ {
NSLog(#"Block B");
}
}
<--- another thread overwrites the **block** block
block(); <--- runtime error since **block** has been dereferenced.

Is there a way to wrap an ObjectiveC block into function pointer?

I have to provide a C-style callback for a specific C library in an iOS app. The callback has no void *userData or something similar. So I am not able to loop in a context. I'd like to avoid introducing a global context to solve this. An ideal solution would be an Objective-C block.
My question: Is there a way to 'cast' a block into a function pointer or to wrap/cloak it somehow?
Technically, you could get access to a function pointer for the block. But it's totally unsafe to do so, so I certainly don't recommend it. To see how, consider the following example:
#import <Foundation/Foundation.h>
struct Block_layout {
void *isa;
int flags;
int reserved;
void (*invoke)(void *, ...);
struct Block_descriptor *descriptor;
};
int main(int argc, char *argv[]) {
#autoreleasepool {
// Block that doesn't take or return anything
void(^block)() = ^{
NSLog(#"Howdy %i", argc);
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr = (struct Block_layout *)(__bridge void *)block;
// Now do same as `block()':
blockStr->invoke(blockStr);
// Block that takes an int and returns an int
int(^returnBlock)(int) = ^int(int a){
return a;
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr2 = (struct Block_layout *)(__bridge void *)returnBlock;
// Now do same as `returnBlock(argc)':
int ret = ((int(*)(void*, int a, ...))(blockStr2->invoke))(blockStr2, argc);
NSLog(#"ret = %i", ret);
}
}
Running that yields:
Howdy 1
ret = 1
Which is what we'd expect from purely executing those blocks directly with block(). So, you could use invoke as your function pointer.
But as I say, this is totally unsafe. Don't actually use this!
If you want to see a write-up of a way to do what you're asking, then check this out:
http://www.mikeash.com/pyblog/friday-qa-2010-02-12-trampolining-blocks-with-mutable-code.html
It's just a great write-up of what you would need to do to get this to work. Sadly, it's never going to work on iOS though (since you need to mark a page as executable which you're not allowed to do within your app's sandbox). But nevertheless, a great article.
If your block needs context information, and the callback does not offer any context, I'm afraid the answer is a clear no. Blocks have to store context information somewhere, so you will never be able to cast such a block into a no-arguments function pointer.
A carefully designed global variable approach is probably the best solution in this case.
MABlockClosure can do exactly this. But it may be overkill for whatever you need.
I know this has been solved but, for interested parties, I have another solution.
Remap the entire function to a new address space. The new resulting address can be used as a key to the required data.
#import <mach/mach_init.h>
#import <mach/vm_map.h>
void *remap_address(void* address, int page_count)
{
vm_address_t source_address = (vm_address_t) address;
vm_address_t source_page = source_address & ~PAGE_MASK;
vm_address_t destination_page = 0;
vm_prot_t cur_prot;
vm_prot_t max_prot;
kern_return_t status = vm_remap(mach_task_self(),
&destination_page,
PAGE_SIZE*(page_count ? page_count : 4),
0,
VM_FLAGS_ANYWHERE,
mach_task_self(),
source_page,
FALSE,
&cur_prot,
&max_prot,
VM_INHERIT_NONE);
if (status != KERN_SUCCESS)
{
return NULL;
}
vm_address_t destination_address = destination_page | (source_address & PAGE_MASK);
return (void*) destination_address;
}
Remember to handle pages that aren't required anymore and note that it takes a lot more memory per invocation than MABlockClosure.
(Tested on iOS)