堆和栈的布局

+--------------------+ <----高地址
|       ...          |        
+--------------------+ <----栈起始地址
|   栈向低地址增长   |        
|         V          |        
|      自由空间      |        
|         ^          |        
|   堆向高地址增长   |        
+--------------------+ <----堆起始地址
|全局变量            |
|.data已初始化       |
|.bss未初始化        |        
+--------------------+        
|      ...           |        
+--------------------+ <-----低地址

80X86 32位CPU寄存器

  • 数据寄存器:EAX EBX ECX EDX
  • 变址寄存器:ESI EDI
  • 指针寄存器:ESP EBP
  • 段寄存器:ES CS SS DS FS GS
  • 指令急诊寄存器:EIP
  • 标志寄存器:EFlags

函数调用的出入栈保护

堆栈平衡:函数调用前后ESP值是一样的,本质上是保证EIP的一致

call address
address:
 push ebp;esp向下偏移4字节;将ebp的值拷贝至新esp位置
 mov ebp, esp;
 ...
 pop ebp
 ret
  • call address - 函数调用后esp位置存的是eip地址
  • 进入函数后保存ebp值至栈
  • 使ebp为esp此后可随意改变esp和便于使用ebp进行栈内寻址

条件跳转

ZF(zero flag)= EFlags第六位 CF(carry flag)=EFlags第零位

  • jmp jump
  • je,jz jump if (equal) zero 等于则跳转 ZF=1
  • jne,jnz jump if not (equal) zero 不等于则跳转 ZF=0
  • jb jump if below 小于则跳转CF=1
  • jnb jump if not below 不小于则跳转 CF=0
  • ja jump if above 大于则跳转 CF=0且ZF=0
  • jna jump if not above 不大于则跳转 CF=1或ZF=1

函数调用/返回

  • call address相当于push eip和jump address
  • ret 相当于pop eip
  • push xxx 相当于sub esp,4和mov esp,xxx
  • pop xxx 相当于mov [esp], xxx和add esp,4

栈上变量

push ebp
mov ebp,esp
sub esp,048;栈上开辟空间存局部变量和寄存器值
push ebx
push esi
push edi
lea edi,[ebp-0C0h];起始
mov ecx,30h;被重复执行次数
mov eax,0CCCCCCCCh
rep stos dword ptr es:[edi] ;rep指令的目的是重复其上面的指令STOS指令的目的是将eax中的值拷贝到ES:EDI指向的地址.

初始化堆栈和分配局部变量,向分配好的局部变量空间放入int3中断,防止栈上内容被意外执行。

参考

http://stackoverflow.com/questions/4024492/can-anyone-help-me-interpret-this-simple-disassembly-from-windbg

标签: assembly
日期: 2013-12-22 17:30:06, 11 years and 25 days ago

introduction

https://github.com/Piot/Project-Generator

Project-Generator makes the native IDE project files.

it supports Visual Studio(windows), Xcode(mac os x), makefile(linux) and so on.

it likes the GYP. but, it is smaller, simpler and easier to understand than GYP. its config option in a XML file is more readable than GYP input format file.

process in generate.py

  • parses arguments
  • project module creates target project
  • project parser module initials target project with xml node
  • generator module write to the project files with project write module

project.py

  • class SourceFileNode - all source files
  • class Dependecy - dependent projects
  • class Define - macros
  • class Settings - project settings likes include paths, defines, dependecies, libraries,framewoorks and so on
  • class configuration - inherit from Settings, it is a build Settings with a name such as "debug", "relase" and so on.
  • class Project - the project object
  • relationship
Project+- depandencies
       +- configurations
       +- settings-+-paths
                   +-defines
                   +-denpendecies
                   +-libraries
                   +-frameworks

project_object.py

project_parser.py

initial project object with xml node

project_path.py

operation about paths

project_write.py

  • class ProjectFileCreator:a Factory in where ProjectFileOutput is made.
  • class ProjectOutput:a controller of project file's indent
  • class ProjectFileOutput:inherit from ProjectOutput wrapper of file operation

generator

  • codeblocks.py
  • codelite.py
  • makefile.py makefile in Linux platform
  • visualc.py Visual Studio in Windows platform
  • xcode.py Xcode in Mac OS X platform
标签: python
日期: 2013-11-29 17:30:06, 11 years and 48 days ago

Introduction

cJSON paser with a single file of C, and a single header file.like description of README, the library can take away as much legwork and is the dumbest possible parser.

homepage:http://sourceforge.net/projects/cjson/?source=directory

mirror:https://github.com/openxc/cJSON

license:MIT

the function of the cJSON library is that the string formatted json(JSON data) and the json structure(cJSON object) convert to each other.

Notice

  • no safe with multi-threads
  • when cJSON_Parse() and cJSON_CreateXXX() functions are finished, call cJSON_Delete to free.
  • when cJSON_PrintXXX() functions are finished, call Hooks::free_fn to free.
  • strdup() needs free.

Structure

In README, the author introducts two way to use the libaray.one is AUTO mode and the other is MANUAL mode. There is a structure introduction in the manual mode part.

Here's the structure: typedef struct cJSON { struct cJSON *next,*prev; struct cJSON *child; int type; char *valuestring; int valueint; double valuedouble; char *string; } cJSON; By default all values are 0 unless set by virtue of being meaningful. next/prev is a doubly linked list of siblings. next takes you to your sibling, prev takes you back from your sibling to you. Only objects and arrays have a "child", and it's the head of the doubly linked list. A "child" entry will have prev==0, but next potentially points on. The last sibling has next=0. The type expresses Null/True/False/Number/String/Array/Object, all of which are #defined in cJSON.h A Number has valueint and valuedouble. If you're expecting an int, read valueint, if not read valuedouble. Any entry which is in the linked list which is the child of an object will have a "string" which is the "name" of the entry. When I said "name" in the above example, that's "string". "string" is the JSON name for the 'variable name' if you will. Now you can trivially walk the lists, recursively, and parse as you please. You can invoke cJSON\_Parse to get cJSON to parse for you, and then you can take the root object, and traverse the structure (which is, formally, an N-tree), and tokenise as you please.

In fact, json structure is a tree, so cJSON struct is like the node of tree that has child node pointer and sibling pointers there are three type structure in json. those are object, number and string. the type member is as the type in json. the type member'value are False, True, NULL, Number, String, Array and Object. the value is stored in the one of valuestring, valueint and valuedouble by the type.

 +------+          +-----+           +-----+
 |cJSON |---prev---|cJSON| ---next---|cJSON|
 +------+          +-----+           +-----+
                      |
                    child      
                      |        +-----+          +-----+          +-----+
                      +--------|cJSON|---prev---|cJSON|---next---|cJSON|
                               +-----+          +-----+          +-----+

Functions

print_xxxx functions are convert json to string parse_xxxx functions are convert string to json

convert functions

  • cJSON_strcasecmp() - strcmpcase()
  • cJSON_strdup() - strdup()
  • parse_number() - atoi() and atof()
  • print_number() - itoa() and fto2()
  • parse_string() - to a unescape string
  • print_string() - to a unescape string
  • print_string_ptr() - to a escape string

parse functions

  • skip() - trim invisible char such as whitespace cr lf
  • parse_value() - parse json token
  • print_value() - json to string
  • parse_array() - parse json array token
  • print_array() - json array to string
  • parse_object()

all function

  • cJSON_strcasecmp() - strcmpcase()
  • cJSON_strdup() - strdup()
  • cJSON_InitHooks() - set malloc and free
  • cJSON_New_Item() - structure
  • cJSON_Delete()
  • parse_number() - atoi() and atof()
  • print_number() - itoa() and fto2()
  • parse_string() - to a unescape string
  • print_string() - to a unescape string
  • print_string_ptr() - to a escape string
  • skip() - trim invisible char such as whitespace cr lf
  • cJSON_ParseWithOpts - return_parse_end:the point to the remain string require_null_terminated:there is no remain string or return error
  • cJSON_Parse() - string to json the same as cJSON_ParseWithOpts(value, 0, 0)
  • cJSON_Print() - json to string
  • cJSON_PrintUnformatted() - json to unformatted string
  • parse_value() - parse json token
  • print_value() - json to string
  • parse_array() - parse json array token to string
  • print_array() - json array to string
  • parse_object() - string to json object
  • print_object() - json object
  • cJSON_GetArraySize() - json array size
  • cJSON_AddItemToArray() - add json to json array
  • cJSON_AddItemToObject() - add json to json object
  • cJSON_AddItemReferenceToArray() - add json to json array without clone
  • cJSON_AddItemReferenceToObject() - add json to json object without clone
  • cJSON_DetachItemFormObject
  • parse_object()

Process

parse_value() - parse the type of json or call parse_array() or parse_object() parse_array() - in loop, parse call parse_value() for every object in array. parse_object() - call parse self and loop to parse its childern by parse_string

标签: cJSON
日期: 2013-08-22 17:30:06, 11 years and 147 days ago

Recently, I read the source of sqlite, cJSON and expat. There is a structure in these source. It looks like:

typdef struct {
    void* (*mallocFn)(size_t s)
void ( * freenFn)(void * p)
} Mem;

The structure has two function pointer members. The one'type is the malloc function.The Other'type is the free function.

In the source, there is a function interface for set the function pointer.

When the program needs alloc and free memory, it calls the functions to be pointed by the two members of the structure.

In my opinion, there are three advantages:

  • Check memory leak.To implement the malloc and free functions with mark a record.When the program is end, check the records to find out memory leak.(I often use it)

  • Improve the performance.To implement the memory pool myself.(I never use it)

  • Out-Of-Memory testing.(this advantage is found in sqlite document)

标签: expat, sqlite, cJSON
日期: 2013-08-08 17:30:06, 11 years and 161 days ago

《Objective-C 基础教程》笔记

1. Hello

2. Extensions to C

#import

NSLog

%@

@"string"

BOOL YES NO

3. OOP

self
   
/* class.h BEGIN */
@interface Class:NSObject
{
    int _member;
}   

- (int)function:(int)parameter;

- (void)many_parameters_function:(int)parameter1 some_information:(NString *)parameter2;

- (void)no_parameter_function;
@end //Class
/* class.h END */
/* class.m BEGIN */
@implementation Class
- (int)function:(int)p 
{
}//function
- (void)many_parameters_function:(int)p1 some_information:(NString *)p2
{
}//many_parameters_function
- (void)no_parameter_function
{
} //noparameter_function
@end //Class
/* class.m END */
Objective-C does not support multiple inheritance
 /* Children.h BEGIN */
@interface Children : Parent

@end //Children
/* Children.h END */

super

isa()

overridden

5. Composition

description

6. Organization

@class sets up a forward reference

7. More About Xcode

defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions

'{"ORGANIZATIONNAME" = "zuohaitao";}'

command+shift+E

File->Make Snapshot

File->Snapshots

command+D

Help->Show Research Assistant.

8. Foundation Kit

  NSRange
    typedef struct _NSRange NSRange;
    struct _NSRange
    {
        NSUInteger location;
        NSUInteger length;
    };
  NSPoint
    typedef struct _NSPoint NSPoint;
    struct _NSPoint
    {
        CGFloat x;
        CGFloat y;
    };
  NSSize
    typedef struct _NSSize NSSize;
    struct _NSSize
    {
        CGFloat width;
        CGFloat height;
    };
  NSRect
    typedef struct _NSRect NSRect;
    struct _NSRect
    {
        NSPoint origin;
        NSSize size;
    };
  NSString
    + (id)stringWithFormat:(NSString *)format,...
    - (unsigned int)length
    - (BOOL)isEqualToString:(NSString *)aString
    - (NSComparisonResult)compare:(NSString *) string;
    - (NSComparisonResult)compare:(NSString *) string 
                          options:(unsigned) mask;
    - (BOOL)hasPrefix:(NSString *)aString;
    - (BOOL)hasSuffix:(NSString *)aString;
    - (NSRange)rangeOfString:(NSString *) aString;
    - (NSArray *)componentsSeparatedByString:(NSString *)separator
    - (NSString *)componentsJoinedByString:(NSString *)separator
    - (NSString *)stringByExpandingTildeInPath
  NSMutableString
    + (id)stringWithCapacity:(unsigned)capacity;
    - (void)appendString:(NSString *)aString;
    - (void)appendFormat:(NSString *)format, ...;
    - (void)deleteCharactersInRange:(NSRange)range;
  NSArray
    + (id)arrayWithObjects:(id)firstObj,...;
    - (unsigned)count;
    - (id)objectAtIndex:(unsigned int) index;
  NSMutableArray
    + (id)arrayWithCapacity:(unsigned) numItems;
    - (void)addObject:(id)anObject;
    - (void)removeObjectAtIndex:(unsigned)index;
    - (NSEnumerator *)objectEnumerator;
    - (id)nextObject;
        /* enumeration */
        NSEnumerator *enumerator;
        enumerator = [array objectEnumerator];
        id thingie;
        while(thingie = [enumerator nextObject]) {
            NSLog(@"I found %@", thingie);
        }
        /* Fast Enumeration */
        for(NSString *string in array) {
            NSLog(@"I found %@", string);
        }
  NSDictionary
    + (id)dictionaryWithObjectsAndKeys:(id)firstObject, (id)firstKey, ...;
    - (id)objectForKey:(id)aKey;
  NSMutableDictionary
    + (id)dictionaryWithCapacity:(unsigned int)numItems;
    - (void)setObject:(id)anObject forKey:(id)aKey;
    - (void)removeObjectForKey:(id)aKey;

because in Cocoa may classes are implemented as class clusters,

don't create subclass to extend, use categories.

  NSNumber
    + (NSNumber *)numberWithChar:(char)value;
    + (NSNumber *)numberWithInt:(int)value;
    + (NSNumber *)numberWithFloat:(float)value;
    + (NSNumber *)numberWithBool:(BOOL)value;
    - (char)charValue;
    - (int)intValue;
    - (float)floatValue;
    - (BOOL)boolValue;
    - (NSString *)stringValue;
  NSValue
    + (NSValue *)valueWithBytes:(const void *)value
                       objCType:(const char *)type;
    + (NSValue *)valueWithPoint:(NSPoint)point;
    + (NSValue *)valueWithSize:(NSSize)size;
    + (NSValue *)valueWithRect:(NSRect)rect;
    - (NSPoint)pointValue;
    - (NSSize)sizeValue;
    - (NSRect)rectValue;
  NSNull
    + (NSNull *) null;
  NSFileManager
    + (NSFileManager *)defaultManager
    - (NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path

9.0 Memory Management

  • Garbage Collection(GC)

If you know that your programs will only be run on Leopard or later, you can take advantage of Objective-C 2.0's garbage collection

  • Reference Counting(RC)

Automatic Reference Counting(ARC)

ARC is supported in Xcode 4.2 for OS X v10.6 and v10.7 (64-bit applications) and for iOS 4 and iOS 5.

Weak references are not supported in OS X v10.6 and iOS 4.

  • Manual Reference Counting(MRC)

    - (id)retain;
    -(oneway void)release;
    

oneway is used with the distributed objects API, which allows use of objective-c objects between different threads or applications. It tells the system that it should not block the calling thread until the method returns. Without it, the caller will block, even though the method's return type is void. Obviously, it is never used with anything other than void, as doing so would mean the method returns something, but the caller doesn't get it.

    - (unsigned)retainCount;
    - (id)autorelease;

The Rules of Cocoa Memory Management

   +----------------+-------------------------+--------------------------------------------+
   |Obtained Via... |Transient                |Hang On                                     |
   +----------------+-------------------------+--------------------------------------------+
   |alloc/new/copy  |Release when done        | Release in dealloc                         |
   +----------------+-------------------------+--------------------------------------------+
   |Any other way   |Don't need to do anything| Retain when acquired, release in dealloc   |
   +----------------+-------------------------+--------------------------------------------+
    /* Keeping The Pool Clean */
    NSAutoreleasePool *pool;
    pool = [[NSAutoreleasePool alloc] init];
    int i;
    for (i = 0; i < 1000000; i++) {
        id object = [someArray objectAtIndex: i];
        NSString *desc = [object descrption];
        // and do something with the description
        if (i % 1000 == 0) {
        [pool release];
        pool = [[NSAutoreleasePool alloc] init];
        }
    }
    [pool release]
    /* Keeping The Pool Clean */

10. Object Initialization

11. Properties

Objective-C 2.0 features can only be used on Mac OS X 10.5 (Leopard) or later

@property

assign retain copy

readonly readwrite

nonatomic

@synthesize

12.Categories

        @interface ClassName(CategoryName)

        @end //interface ClassName(CategoryName)
        @implementation ClassName(CategoryName)

        @end //implementation ClassName(CategoryName)
  • Bad Category

    1. You can not add variables to class.

    2. When names collide, the category wins.

  • Purpose

    1. split class implementation into multiple files or multiple frameworks

    2. creating forward references for private methods

    3. adding informal protocols to an object

  • Delegate

delegate is an object asked by another object to do some of its work.

e.g. the AppKit class NSApplication asks its delegate if it should open an Untitled window when the application launches.

@selector(func:)

[obj respondsToSelector:@selector(func:)]

13. Protocols

    @protocol FormalProtocolA

    - (void)functionA;

    @end //protocol FormalProtocolA
    @protocol FormalProtocolB
    - (void)functionB;
    @end //protocol FormalProtocolB
    @interface Obj:NSObject
    @end //interface Obj
    @implementation Obj
    - (void)functionA
    {
    }
    - (void)functionB
    {
    }
    @end //interface Obj
  • A shallow copy

    you don't duplicate the referred objects;

    you new copy simply points at the referred objects that already exist.

  • A deep copy

    makes duplicates of all the referred objects.

    - (id)copyWithZone:(NSZone *)zone
    {
        return [[[self class] allocWithZone: zone]init];
    }
  • Objective-C 2.0

  • @optional

  • @required

标签: objc
日期: 2013-04-15 17:30:06, 11 years and 276 days ago