activeX control crash on alt+tab - delphi

I've implemented an Delphi acitveX control. Everything runs fine on html. After that, I embed that activeX in an MFC application. It's good, except that when I test it, if I alt+tab to another windows(Chrome, for example...) and alt+tab back to my application, it just crashed.
I know that this is a non-clear question, but I have no clues. Any clues to solve this situation? What may go wrong or what events I should take a look at?
Thanks.
Edit 1:
This is what I got when I use spy++ on it.
<04518> 00100B7C S WM_ACTIVATE fActive:WA_INACTIVE fMinimized:False hwndPrevious:(null)
<04519> 00100B7C S WM_ACTIVATETOPLEVEL fActive:False dwThreadID:0025F40C
<04520> 00100B7C R WM_ACTIVATETOPLEVEL
Edit 2:
This is what I got from call stack when I break all at the time it hangs
mfc100d.dll!CThreadSlotData::GetThreadValue(int nSlot) Line 248 C++
mfc100d.dll!CThreadLocalObject::GetData(CNoTrackObject * (void)* pfnCreateObject) Line 420 + 0x11 bytes C++
mfc100d.dll!CThreadLocal<AFX_MODULE_THREAD_STATE>::GetData() Line 179 + 0xd bytes C++
mfc100d.dll!AfxGetModuleThreadState() Line 477 + 0x11 bytes C++
mfc100d.dll!afxMapHWND(int bCreate) Line 289 + 0x5 bytes C++
mfc100d.dll!CWnd::FromHandlePermanent(HWND__ * hWnd) Line 324 + 0x7 bytes C++
mfc100d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 405 + 0x9 bytes C++
mfc100d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 420 + 0x15 bytes C++
Edit 3:
I'm using Visual studio 2010, the call stack tell that application hangs in this function, line 2, from afxtls.cpp. Please anyone shed some lights on how to solve this.
inline void* CThreadSlotData::GetThreadValue(int nSlot)
{
EnterCriticalSection(&m_sect);
ASSERT(nSlot != 0 && nSlot < m_nMax);
ASSERT(m_pSlotData != NULL);
ASSERT(m_pSlotData[nSlot].dwFlags & SLOT_USED);
ASSERT(m_tlsIndex != (DWORD)-1);
if( nSlot <= 0 || nSlot >= m_nMax ) // check for retail builds.
{
LeaveCriticalSection(&m_sect);
return NULL;
}
CThreadData* pData = (CThreadData*)TlsGetValue(m_tlsIndex);

Related

What lives above the last accessible address in the stack?

I've asked people before about why the stack doesn't start at 0x7fff...c before, and was told that typically 0x800... onwards is for the kernel, and the cli args and environment variables live at the top of the user's stack which is why it starts below 0x7fff...c. But I recently tried to examine all the strings with the following program
#include <stdio.h>
#include <string.h>
int main(int argc, const char **argv) {
const char *ptr = argv[0];
while (1) {
printf("%p: %s\n", ptr, ptr);
size_t len = strlen(ptr);
ptr = (void *)ptr + len + 1;
}
}
However, after displaying all my environment variables, I see the following (I compiled the program to an executable called ./t):
0x7ffc19f84fa0: <final env variable string>
0x7ffc19f84fee: _=./t
0x7ffc19f84ff4: ./t
0x7ffc19f84ff8:
0x7ffc19f84ff9:
0x7ffc19f84ffa:
0x7ffc19f84ffb:
0x7ffc19f84ffc:
0x7ffc19f84ffd:
0x7ffc19f84ffe:
0x7ffc19f84fff:
So it appears there's one extra empty byte after the null terminator for the ./t string at bytes 0x7ffc19f84ff4..0x7ffc19f84ff7, and after that I segfault so I guess that's the base of the stack. What actually lives in the remaining "empty" space before kernel memory starts?
Edit: I also tried the following:
global _start
extern print_hex, fgets, puts, print, exit
section .text
_start:
pop rdi
mov rcx, 0
_start_loop:
mov rdi, rsp
call print_hex
pop rdi
call puts
jmp _start_loop
mov rdi, 0
call exit
where print_hex is a routine I wrote elsewhere. It seems this is all I can get
0x00007ffcd272de28
./bin/main
0x00007ffcd272de30
abc
0x00007ffcd272de38
def
0x00007ffcd272de40
ghi
0x00007ffcd272de48
make: *** [Makefile:47: run] Segmentation fault
so it seems that even in _start we don't begin at 0x7fff...

SIGBUS crash on Solaris 8

Compiled with g++ 4.7.4 on Solaris 8. 32 bit application. Stack trace is
Core was generated by `./z3'.
Program terminated with signal 10, Bus error.
\#0 0x012656ec in vector<unsigned long long, false, unsigned int>::push_back (this=0x2336ef4 <g_prime_generator>, elem=#0xffbff1f0: 2) at ../src/util/vector.h:284
284 new (m_data + reinterpret_cast<SZ *>(m_data)[SIZE_IDX]) T(elem);
(gdb) bt
\#0 0x012656ec in vector<unsigned long long, false, unsigned int>::push_back (this=0x2336ef4 <g_prime_generator>, elem=#0xffbff1f0: 2) at ../src/util/vector.h:284
\#1 0x00ae66d4 in prime_generator::prime_generator (this=0x2336ef4 <g_prime_generator>) at ../src/util/prime_generator.cpp:24
\#2 0x00ae714c in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at ../src/util/prime_generator.cpp:99
\#3 0x00ae71c4 in _GLOBAL__sub_I_prime_generator.cpp(void) () at ../src/util/prime_generator.cpp:130
\#4 0x00b16a68 in __do_global_ctors_aux ()
\#5 0x00b16aa0 in _init ()
\#6 0x00640b10 in _start ()
(gdb) list
279
280 void push_back(T const & elem) {
281 if (m_data == 0 || reinterpret_cast<SZ *>(m_data)[SIZE_IDX] == reinterpret_cast<SZ *>(m_data)[CAPACITY_IDX]) {
282 expand_vector();
283 }
284 new (m_data + reinterpret_cast\<Z *>(m_data)[SIZE_IDX]) T(elem);
285 reinterpret_cast<SZ *>(m_data)[SIZE_IDX]++;
286 }
287
288 void insert(T const & elem) {
(gdb) ptype SZ
type = unsigned int
(gdb) ptype m_data
type = unsigned long long *
SIGBUS on Solaris is usually indicative of a misaligned access, but I am not sure if it is due to the casting going on an endianess issue
The SPARC data alignment requirements is most likely at issue.
The m_data field in the vector class is off by two fields that are used
to store the size and capacity of a vector.
You can debug this by displaying (printing or using the debugger) the pointer m_data and it's alignment.
One option is to supply a separate vector implementation
where the size and capacity fields are stored
in fields directly in the vector for porting this library utility.
Z3 interacts with memory alignment a few other places (but not overly many).
The main other potential places are in the watch lists (sat_solver and smt_context), and region memory allocators (region.h) and possibly in hash tables.

Golang append memory allocation VS. STL push_back memory allocation

I compared the Go append function and the STL vector.push_back and found that different memory allocation strategy which confused me. The code is as follow:
// CPP STL code
void getAlloc() {
vector<double> arr;
int s = 9999999;
int precap = arr.capacity();
for (int i=0; i<s; i++) {
if (precap < i) {
arr.push_back(rand() % 12580 * 1.0);
precap = arr.capacity();
printf("%d %p\n", precap, &arr[0]);
} else {
arr.push_back(rand() % 12580 * 1.0);
}
}
printf("\n");
return;
}
// Golang code
func getAlloc() {
arr := []float64{}
size := 9999999
pre := cap(arr)
for i:=0; i<size; i++ {
if pre < i {
arr = append(arr, rand.NormFloat64())
pre = cap(arr)
log.Printf("%d %p\n", pre, &arr)
} else {
arr = append(arr, rand.NormFloat64())
}
}
return;
}
But the memory address is invarient to the increment of size expanding, this really confused me.
By the way, the memory allocation strategy is different in this two implemetation (STL VS. Go), I mean the expanding size. Is there any advantage or disadvantage? Here is the simplified output of code above[size and first element address]:
Golang CPP STL
2 0xc0800386c0 2 004B19C0
4 0xc0800386c0 4 004AE9B8
8 0xc0800386c0 6 004B29E0
16 0xc0800386c0 9 004B2A18
32 0xc0800386c0 13 004B2A68
64 0xc0800386c0 19 004B2AD8
128 0xc0800386c0 28 004B29E0
256 0xc0800386c0 42 004B2AC8
512 0xc0800386c0 63 004B2C20
1024 0xc0800386c0 94 004B2E20
1280 0xc0800386c0 141 004B3118
1600 0xc0800386c0 211 004B29E0
2000 0xc0800386c0 316 004B3080
2500 0xc0800386c0 474 004B3A68
3125 0xc0800386c0 711 004B5FD0
3906 0xc0800386c0 1066 004B7610
4882 0xc0800386c0 1599 004B9768
6102 0xc0800386c0 2398 004BC968
7627 0xc0800386c0 3597 004C1460
9533 0xc0800386c0 5395 004B5FD0
11916 0xc0800386c0 8092 004C0870
14895 0xc0800386c0 12138 004D0558
18618 0xc0800386c0 18207 004E80B0
23272 0xc0800386c0 27310 0050B9B0
29090 0xc0800386c0 40965 004B5FD0
36362 0xc0800386c0 61447 00590048
45452 0xc0800386c0 92170 003B0020
56815 0xc0800386c0 138255 00690020
71018 0xc0800386c0 207382 007A0020
....
UPDATE:
See comments for Golang memory allocation strategy.
For STL, the strategy depends on the implementation. See this post for further information.
Your Go and C++ code fragments are not equivalent. In the C++ function, you are printing the address of the first element in the vector, while in the Go example you are printing the address of the slice itself.
Like a C++ std::vector, a Go slice is a small data type that holds a pointer to an underlying array that holds the data. That data structure has the same address throughout the function. If you want the address of the first element in the slice, you can use the same syntax as in C++: &arr[0].
You're getting the pointer to the slice header, not the actual backing array. You can think of the slice header as a struct like
type SliceHeader struct {
len,cap int
backingArray unsafe.Pointer
}
When you append and the backing array is reallocated, the pointer backingArray will likely be changed (not necessarily, but probably). However, the location of the struct holding the length, cap, and pointer to the backing array doesn't change -- it's still on the stack right where you declared it. Try printing &arr[0] instead of &arr and you should see behavior closer to what you expect.
This is pretty much the same behavior as std::vector, incidentally. Think of a slice as closer to a vector than a magic dynamic array.

Crash EXC_BAD_ACCESS on string with format

I am processing raw IP data to process a video signal (ATSC-MH). However, I am having issues with some basic issue and I'm apparently fried at the moment and need another set of eyes.
This is the function that flips. Funny part is that it was working for a while and I can't rememeber what I changes. The line that is **d is the one that is referred to in the error log. I can't do much NSLog debugging because the stream comes from an accessory(so no direct debugging pipe :().
-(NSString*)reportSMT{
//NSString* ret = #"Not implemented yet";
__autoreleasing NSMutableString* ret = [[NSMutableString alloc] initWithFormat:#"\nSMT:\n SecSynInd:%# PriInd:%#\n SecLen:%d SMTMHProVer:%d\n EnID:%d VerNum:%d\n CurNxtInd:%# SecNum:%d\n lastSec#:%d #Servs:%d\n\n",(Header.section_syntax_indicator?#"YES":#"NO"),(Header.private_indicator?#"YES":#"NO"),Header.section_length,Header.SMT_MH_protocol_version,Header.ensemble_id,Header.version_number,(Header.current_next_indicator?#"YES":#"NO"), Header.section_number,Header.last_section_number,Header.num_MH_services];
[ret appendString:[NSString stringWithFormat:#"SMT Table:\n"]];
for (int i = 0; i<Header.num_MH_services; i++) {
**[ret appendString:[NSString stringWithFormat:#"Serv(%d):\n ServID:%d MultiEnServ:%d\n ServStat:%d ServSPInd:%#\n ServShotName:%#\n ServCat:%d\n source:%# dest:%#\n #MHServComps:%d\n",i,Services[i].MH_service_id,Services[i].multi_ensemble_service,Services[i].MH_service_status,(Services[i].SP_indicator?#"YES":#"NO"),[NSString stringWithUTF8String:(char*)Services[i].short_MH_service_name],(Services[i].service_source_IP_address_flag?[Utility ParseIP:Services[i].service_source_IP_address]:#"N/A"),(Services[i].service_destination_IP_address_flag?[Utility ParseIP:Services[i].service_destination_IP_address]:#"N/A"),Services[i].num_components]];**
for (int m=0; m<Services[i].num_components; m++) {
[ret appendString:[NSString stringWithFormat:#" Comp(%d)(essential:%#):\n port#count:%d compSource:%#\n compDest:%# destPort:%d\n",m,(Services[i].components[m].essential_component_indicator?#"YES":#"NO") ,Services[i].components[m].port_num_count,(Services[i].components[m].component_source_IP_address_flag?[Utility ParseIP:Services[i].components[m].component_source_IP_address]:#"N/A"),(Services[i].components[m].component_destination_IP_address_flag?[Utility ParseIP:Services[i].components[m].component_destination_IP_address]:#"N/A"),Services[i].components[m].component_destination_UDP_port_num]];
}
}
return [ret copy];
}
Here is that Utility parseIP function. Though it didn't change anything to comment the call to it and hardcode a value there:
+(NSString*)ParseIP:(long)ip{
__autoreleasing NSString* ret = nil;
if (ip) {
unsigned char* ipPtr = (unsigned char*)&ip;
unsigned char ipc[4];
for (int i=0; i<4; i++) {
ipc[i] = *(ipPtr+i);
}
ret = [NSString stringWithFormat:#"(%d.%d.%d.%d)",ipc[3],ipc[2],ipc[1],ipc[0]];
}
return ret;
}
Here is the structure for that part of the SMT:
struct SMTChunk{
unsigned int MH_service_id;//16
unsigned char multi_ensemble_service;//2
unsigned char MH_service_status;//2
bool SP_indicator;//1
unsigned char short_MH_service_name_length;//3 /* m */
unsigned char* short_MH_service_name;//16*m
unsigned char reserved2;//2 should be 11
unsigned char MH_service_category;//6
unsigned char num_components;//5
bool IP_version_flag;//1
bool service_source_IP_address_flag;//1
bool service_destination_IP_address_flag;//1
unsigned long service_source_IP_address;//32 if (service_source_IP_address_flag)
unsigned long service_destination_IP_address;//32 if (service_destination _IP_address_flag)
struct SMTComponent* components;
unsigned char reserved4;//4 1111(f)
unsigned char num_MH_service_level_descriptors;//4
struct SMTServiceDescriptor* descriptors;
};
Like I said this was working before, so I'm pretty sure the parser that fills the data structure is fine.
Device Log(important part):
Date/Time: 2012-03-06 00:56:40.480 -0600
OS Version: iPhone OS 5.0.1 (9A405)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000a
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x300e4fb6 objc_msgSend + 10
1 Foundation 0x30dd9d14 _NSDescriptionWithLocaleFunc + 44
2 CoreFoundation 0x335d699e __CFStringAppendFormatCore + 7998
3 CoreFoundation 0x33551210 _CFStringCreateWithFormatAndArgumentsAux + 68
4 Foundation 0x30dd9c3e +[NSString stringWithFormat:] + 54
5 APT-test 0x000c9630 -[SMT reportSMT] (SMT.m:178)
6 APT-test 0x000c54bc -[VideoViewController saveTimerFun:] (VideoViewController.mm:940)
7 Foundation 0x30e79616 __NSFireTimer + 138
It feels like I've been working on this app forever so any help or pointers you can give are welcome.
Thanks in advance!
The printf wildcards and arguments do not appear to be balanced properly:
[NSString stringWithFormat:#"1%d 2%d 3%d 4%d 5%# 6%# 7%d 8%# 9%# A%d",
/* 1 */i,
/* 2 */Services[i].MH_service_id,
/* 3 */Services[i].multi_ensemble_service,
/* 4 */Services[i].MH_service_status,
/* 5 */(Services[i].SP_indicator?#"YES":#"NO"),
/* 6 */[NSString stringWithUTF8String:(char*)Services[i].short_MH_service_name],
/* 7 */(Services[i].service_source_IP_address_flag?[Utility ParseIP:Services[i].service_source_IP_address]:#"N/A"),
/* 8 */(Services[i].service_destination_IP_address_flag?[Utility ParseIP:Services[i].service_destination_IP_address]:#"N/A"),
/* 9 */Services[i].num_components]];
It looks like you’re trying to match the %# specifier at position 9 with Services[i].num_components, which is quite probable to result in EXC_BAD_ACCESS. You would do best to rewrite the code so that it’s more readable, this mess is only asking for trouble.

Using yyparse() to make a two pass assembler?

I'm writing an assembler for a custom micro controller I'm working on. I've got the assembler to a point where it will assemble instructions down to binary.
However, I'm now having problems with getting labels to work. Currently, when my assembler encounters a new label, it stores the name of the label and the memory location its referring to. When an instruction references a label, the assembler looks up the label and replaces the label with the appropriate value.
This is fine and dandy, but what if the label is defined after the instruction referencing it? Because of this, I need to have my parser run over the code twice.
Here's what I currently have for my main function:
303 int main(int argc, char* argv[])
304 {
305
306 if(argc < 1 || strcmp(argv[1],"-h")==0 || 0==strcmp(argv[1],"--help"))
307 {
308 //printf("%s\n", usage);
309 return 1;
310 }
311 // redirect stdin to the file pointer
312 int stdin = dup(0);
313 close(0);
314
315 // pass 1 on the file
316 int fp = open(argv[1], O_RDONLY, "r");
317 dup2(fp, 0);
318
319 yyparse();
320
321 lseek(fp, SEEK_SET, 0);
322
323 // pass 2 on the file
324 if(secondPassNeeded)
325 {
326 fp = open(argv[1], O_RDONLY, "r");
327 dup2(fp, 0);
328 yyparse();
329 }
330 close(fp);
331
332 // restore stdin
333 dup2(0, stdin);
334
335 for(int i = 0; i < labels.size(); i++)
336 {
337 printf("Label: %s, Loc: %d\n", labels[i].name.c_str(), labels[i].memoryLoc);
338 }
339 return 0;
340 }
I'm using this inside a flex/bison configuration.
If that is all you need, you don't need a full two-pass assembler. If the label is not defined when you reference it, you simply output a stand-in address (say 0x0000) and have a data structure that lists all of the places with forward references and what symbol they refered to. At the end of the file (or block if you have local symbols), you simply go through that list and patch the addresses.

Resources