2014년 8월 7일 목요일

[OS X][XNU] kext strnstr link fail

KEXT 내부에서 strnstr 을 사용했는데 컴파일은 잘되는데, 로딩할때 바인딩 에러가 난다..

왜그런지 인터넷을 찾아보아도 답이 없길래 직접 확인해보았다.

사건의 발단은 Kernel/string.h 에 strnstr 이 선언되어 있다.



extern int strcasecmp(const char *s1, const char *s2);
extern int strncasecmp(const char *s1, const char *s2, size_t n);
extern char *strnstr(char *s, const char *find, size_t slen);
extern char *strchr(const char *s, int c);
extern char *STRDUP(const char *, int);

extern int strprefix(const char *s1, const char *s2);


그런데 로딩시도를 하면 자꾸 아래 같은 에러가 발생한다.

(kernel) kxld[com.dplab.driver.xxxxio]: The following symbols are unresolved for this kext:
(kernel) kxld[com.dplab.driver.xxxxio]: _strnstr


그래서 System.kext/Plugins 에 존재하는 라이브러리 심볼을 덤프 해봤다.

(nm 명령어는 display name list 명령어로 심볼정보를 출력해줌)

nm /System/Library/Extensions/System.kext/PlugIns/Libkern.kext/Libkern | grep str
                 U __ZN12OSSymbolPool18reconstructSymbolsEv
                 U __ZNK11OSMetaClass18instanceDestructedEv
                 U __ZNK11OSMetaClass19instanceConstructedEv
                 U _copyinstr
                 U _copyoutstr
                 U _lck_mtx_destroy
                 U _lck_rw_destroy
                 U _lck_spin_destroy
                 U _strcasecmp
                 U _strcat
                 U _strchr
                 U _strcmp
                 U _strcpy
                 U _strlcat
                 U _strlcpy
                 U _strlen
                 U _strncasecmp
                 U _strncat
                 U _strncmp
                 U _strncpy
                 U _strnlen
                 U _strprefix
                 U _strtol
                 U _strtoq
                 U _strtoul

                 U _strtouq

음.. Libkern 에 _strnstr 이 진짜 없다. ....

어디있는지 다 찾아보니..

nm /System/Library/Extensions/System.kext/PlugIns/Private.kext/Private | grep strnstr
                 U _strnstr

Private.kext 에 있다.

그래서 Private.kext 를 링크해보니..


Diagnostics for /tmp/xxxxxio.kext:
Dependency Resolution Failures: 

    Only Apple kexts may link against com.apple.kpi.private.


쓰지 말란다. ....

머 이런...

암튼 다른 분들은 삽질하지 마시길..








2014년 8월 6일 수요일

[OS X] [lldb][kernel debugging 위주] 중요 명령어 정리

LLDB command

lldb 명령어는 windbg 명령어보다 복잡하다. 하지만 먼가 체계가 잘 잡혀있는
스크립트같은 느낌을 주는 명령어이다. 익숙해지는데 시간이 걸리겠지만 ..
익숙해지면 windbg 보다 더 능숙하게 디버깅할 수 있을 것 같다.


일단 몇개만 나열하고 나머지는 업데이트 할 예정.



target modules

  target modules lookup -n symbol modulename
  ex> target mod loo -n sysent mach_kernel

target modules list ( == image list )

target variable

  global values

  target variable <variable name>

memory read

   memory read -f A <address>  - display value with symbol - same as dds command in windbg
   ex> memory read -f A fffffff87000000 -c1

   memory read -t type <address> - same as dt command in windbg - very important !

thread backtrace all

thread select #num

process attach -p pid

process detach

bt



2014년 7월 31일 목요일

[Windows NT] NtCreateUserProcess

NtCreateUserProcess 과정과 Process & Thread & Image Callback 과정을 종합적으로 보여주는 그림.

궁금한 부분있으면 댓글로 남겨주세요.

If you have a question about this, leave a message ^^

(NtCreateUserProcess, NtCreateThreadEx)

2014년 5월 13일 화요일

[windows] Process & Thread Object Generic Mapping Info

You can find the information with windbg command in Windows XP

Don't miss generic desired access ^^


kd> ?? (*((nt!_OBJECT_TYPE**)@@(nt!PsProcessType)))->TypeInfo.GenericMapping
struct _GENERIC_MAPPING
+0x000 GenericRead : 0x20410
+0x004 GenericWrite : 0x20beb
+0x008 GenericExecute : 0x120000
+0x00c GenericAll : 0x1f0fff


kd> ?? (*((nt!_OBJECT_TYPE**)@@(nt!PsThreadType)))->TypeInfo.GenericMapping
struct _GENERIC_MAPPING
+0x000 GenericRead : 0x20048
+0x004 GenericWrite : 0x20037
+0x008 GenericExecute : 0x120000
+0x00c GenericAll : 0x1f03fjustlif


?? -> Evaluate C++ Expression

Process
GenericRead STANDARD_RIGHTS_READ | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION,

GenericWrite STANDARD_RIGHTS_WRITE | PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD |
PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_DUP_HANDLE |
PROCESS_TERMINATE | PROCESS_SET_QUOTA |
PROCESS_SET_INFORMATION | PROCESS_SET_PORT,

GenericExecute STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,

GenericAll PROCESS_ALL_ACCESS

Thread
GenericRead STANDARD_RIGHTS_READ | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,

GenericWrite STANDARD_RIGHTS_WRITE | THREAD_TERMINATE | THREAD_SUSPEND_RESUME | THREAD_ALERT |
THREAD_SET_INFORMATION | THREAD_SET_CONTEXT,

GenericExecute STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,

GenericAll THREAD_ALL_ACCESS

2014년 5월 4일 일요일

linux - cscope




Linux

find ./ \( -name "*.c" -o -name "*.h" -o -name "*.asm" \) -print > cscope.files
cscope -i cscope.files

2014년 4월 28일 월요일

windows format syntax





http://msdn.microsoft.com/en-us/library/56e442dc.aspx

c++-String manipulation



함수 리스트

strtod, _strtod_l, wcstod, _wcstod_l
strtol, wcstol, _strtol_l, _wcstol_l
strtoul, _strtoul_l, wcstoul, _wcstoul_l
_strtoi64, _wcstoi64, _strtoi64_l, _wcstoi64_l
_strtoui64, _wcstoui64, _strtoui64_l, _wcstoui64_l

http://msdn.microsoft.com/ko-kr/library/53b7b72e.aspx





2014년 2월 17일 월요일

vim make project - vs in windows

Using vim in windows


" filename(line) : error|warning|fatal error C0000: message
" cope
set errorformat=\ %#%f(%l)\ :\ %#%t%[A-z]%#\ %[A-Z\ ]%#%n:\ %m

set makeprj=Drvbuild.bat


view error window
:cl

:cw
:copen

:cn
:cp
:cfirst
:clast

map cn :cn
map cp :cp



2014년 1월 27일 월요일

GetDiskFreeSpaceEx Function Internal call path


GetDiskFreeSpaceEx

ntdll!ZwQueryVolumeInformationFile


sysenter ----------------------------------------------------------------------

nt!NtQueryVolumeInformationFile

IRP_MJ_QUERY_VOLUME_INFORMATION | FileFsVolumeInformation

NtfsFsdDispatch

NtfsFsdDispatchSwitch

NtfsCommonQueryVolumeInfo

NtfsQueryFsSizeInfo

2014년 1월 21일 화요일

linux - ctags


Ctags 사용법




- Ctags 사용시 Prototype 과 extern 정의도 tag 로 포함시키는 명령어.


ctags -R --c-kinds=+px


-R recursive


−−−kinds=[+|−]kinds
Specifies a list of language-specific kinds of tags (or kinds) to include in the output file for a particular language, where is case-insensitive and is one of the built-in language names (see the −−list−languages option for a complete list). The parameter kinds is a group of one-letter flags designating kinds of tags (particular to the language) to either include or exclude from the output. The specific sets of flags recognized for each language, their meanings and defaults may be list using the −−list−kinds option. Each letter or group of letters may be preceded by either ’+’ to add it to, or ’−’ to remove it from, the default set. In the absence of any preceding ’+’ or ’−’ sign, only those kinds explicitly listed in kinds will be included in the output (i.e. overriding the default for the specified language).
As an example for the C language, in order to add prototypes and external variable declarations to the default set of tag kinds, but exclude macros, use −−c−kinds=+px−d; to include only tags for functions, use −−c−kinds=f.

2013년 12월 22일 일요일

linux-vim-misc

vim 

set autochdir
set autoindent
set smartindent



grep

search string in a file or files
command option searchstring path

grep -Iinr '^obref' .


find

search file list in directory

command path option regular expression

find . -name '*.[ch]'


find + grep

find . -name '*.[ch]' | xargs grep -in '^obref'


Windows Findstr

command searchstring path(windows style) - '.' not work opposite to linux shell
findstr printf *.c









2013년 12월 16일 월요일

windows driver build - sources


Sources 파일에 대하여 몇가지 중요한 부분만 정리해 본다.


Sources 

- TARGETNAME

빌드될 바이너리 이름 

- TARGETTYPE

DRIVER, EXPORT_DRIVER, DRIVER_LIBRARY, PROGRAM, DYNLINK

- TARGETPATH

빌드된 바이너리 위치

- SOURCES

소스 파일 ( 여러줄로 표현할 경우 '\' 를 사용 )

- INCLUDES

header 파일 참조 경로

- C_DEFINES

- USER_CFLAGS

- TARGETLIBS

라이브러리 참조 경로 ( 참고로 전체 경로로 써 주어야 함)

ex>

***************************************************************



TARGETTYPE=DRIVER_LIBRARY
TARGETNAME=klib
TARGETPATH=..\bin


C_DEFINES = $(C_DEFINES)
INCLUDES=$(DDK_INC_PATH);..\inc


SOURCES= klib.



***************************************************************
TARGETTYPE=DRIVER
TARGETNAME=kdrv
TARGETPATH=..\bin


C_DEFINES = $(C_DEFINES)
INCLUDES=$(DDK_INC_PATH);..\inc

TARGETLIBS = ..\bin\*\klib.lib

SOURCES= kdrv.



더 자세히 읽고 싶다면 아래 주소 참고

http://www.wd-3.com/archive/WinBuild.htm


2013년 12월 12일 목요일

KeEnterCriticalRegion

커널에서 APC 를 디스패치할 수 없도록 하기 위해서는 단순히 IRQL 을 APC_LEVEL로 올리면 가능하다. 하지만 윈도우에서는 스레드 커널 구조체에 값을 지정하여 특정 구간에서는 APC 를 불가능하도록 만드는 방법을 사용하고 있다.

다음 두 개의 함수를 사용해서 구간을 진입하게 된다.

KeEnterCriticalRegion 
{
   Thread->KernelApcDisable -= 1
}


KeLeaveCriticalRegion 
{
   Thread->KernelApcDisable += 1
}



KeEnterCriticalRegion, KeLeaveCriticalRegion

윈도우 커널에서는 스레드 커널 구조체의 ( KTHREAD ) 의 특정 필드를 통해서 위 매커니즘을 구현하게 된다.

KTHREAD.KernelApcDisable

이 값은 3가지 방향을 갖는다.  0, minus, plus




위와 같이 두개의 함수가 KernelApcDisable 값을 1씩 증감하면서 변화 시킨다.

+ 2    APC Dispatch Disable  ( KeEnterCriticalRegion 이 연속으로 호출됨 )
+ 1
   0    APC Dispatch Enable, If APC Dispatch Entry exist
- 1
- 2     APC Dispatch Disable ( KeLeaveCriticalRegion 이 연속으로 호출 됨 )  발생해서는 안되는 상황


KernelApcDisable 값이 '0' 이 될 때만 APC Dispatch 가 가능하다는 점을 기억하자.

만약 이 값을 boolean 으로 만들었다면 KeEnterCriticalRegion 와 KeLeaveCriticalRegion 함수 호출에 대한 pair를  추적하기 힘들었을 것이다.

signed value 로 지정함으로써 두개의 함수가 몇번 호출했는지 추적도 가능하고 APC Dispatch 가 가능한 구간도 지정할 수 있다.