CreateMutex
까보면 다나와~
유용한 지식 자료들/기타 (38)

윈도우 버전 정보 (GetVersion)

http://www.codeguru.com/cpp/misc/misc/system/article.php/c8973/Determine-Windows-Version-and-Edition.htm

-----

The first difference is made by the major version:

  • 3 is for Windows NT 3.5
  • 4 is for the Windows NT 4
  • 5 is for Windows 2000, Windows XP, Windows Server 2003 and Windows Home Server
  • 6 is for Windows Vista, Windows Server 2008 and Windows 7

http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx

'유용한 지식 자료들 > 기타' 카테고리의 다른 글

Windows7 update 관련 프로세스  (0) 2013.05.15
중국에서 사용하는 메신저 프로그램  (0) 2013.02.25
PEB structure  (0) 2012.08.09
TEB structure  (0) 2012.08.09
Win32 Thread Information Block (TIB), TEB  (0) 2012.08.08
  Comments,     Trackbacks

PEB structure
kd> !strct _PEB
struct _PEB (sizeof=488)
+000 byte InheritedAddressSpace
+001 byte ReadImageFileExecOptions
+002 byte BeingDebugged
+003 byte SpareBool
+004 void *Mutant
+008 void *ImageBaseAddress
+00c struct _PEB_LDR_DATA *Ldr
+010 struct _RTL_USER_PROCESS_PARAMETERS *ProcessParameters
+014 void *SubSystemData
+018 void *ProcessHeap
+01c void *FastPebLock
+020 void *FastPebLockRoutine
+024 void *FastPebUnlockRoutine
+028 uint32 EnvironmentUpdateCount
+02c void *KernelCallbackTable
+030 uint32 SystemReserved[2]
+038 struct _PEB_FREE_BLOCK *FreeList
+03c uint32 TlsExpansionCounter
+040 void *TlsBitmap
+044 uint32 TlsBitmapBits[2]
+04c void *ReadOnlySharedMemoryBase
+050 void *ReadOnlySharedMemoryHeap
+054 void **ReadOnlyStaticServerData
+058 void *AnsiCodePageData
+05c void *OemCodePageData
+060 void *UnicodeCaseTableData
+064 uint32 NumberOfProcessors
+068 uint32 NtGlobalFlag
+070 union _LARGE_INTEGER CriticalSectionTimeout
+070 uint32 LowPart
+074 int32 HighPart
+070 struct __unnamed3 u
+070 uint32 LowPart
+074 int32 HighPart
+070 int64 QuadPart
+078 uint32 HeapSegmentReserve
+07c uint32 HeapSegmentCommit
+080 uint32 HeapDeCommitTotalFreeThreshold
+084 uint32 HeapDeCommitFreeBlockThreshold
+088 uint32 NumberOfHeaps
+08c uint32 MaximumNumberOfHeaps
+090 void **ProcessHeaps
+094 void *GdiSharedHandleTable
+098 void *ProcessStarterHelper
+09c uint32 GdiDCAttributeList
+0a0 void *LoaderLock
+0a4 uint32 OSMajorVersion
+0a8 uint32 OSMinorVersion
+0ac uint16 OSBuildNumber
+0ae uint16 OSCSDVersion
+0b0 uint32 OSPlatformId
+0b4 uint32 ImageSubsystem
+0b8 uint32 ImageSubsystemMajorVersion
+0bc uint32 ImageSubsystemMinorVersion
+0c0 uint32 ImageProcessAffinityMask
+0c4 uint32 GdiHandleBuffer[34]
+14c function *PostProcessInitRoutine
+150 void *TlsExpansionBitmap
+154 uint32 TlsExpansionBitmapBits[32]
+1d4 uint32 SessionId
+1d8 void *AppCompatInfo
+1dc struct _UNICODE_STRING CSDVersion
+1dc uint16 Length
+1de uint16 MaximumLength
+1e0 uint16 *Buffer





========kernel32.dll???================

1. fs레지스터 => teb 를 가르키고 있다.

2. teb+0x30 위치에 peb 구조체를 가르키는 offset이 위치해 있다.

3. peb+0x0c의 위치에 PEB_LDR_DATA 구조체를 가르키는 포인터가 있다.

4. PEB_LDR_DATA+0x1c에 InInitializationOnderModuleList에 있고,
그 곳의 1번째가 ntdll.dll 2번째가 kernel32.dll 주소이다. **

InInitializationOnderModuleList 구조체 정보

0x000 Flink : LIST_ENTRY
0x004 Blink : LIST_ENTRY
0x008 DllBase : Ptr32
0x00C EntryPoint : Ptr32
0x010 SizeOfImage : Uint4B
0x014 FullDllName : UNICODE_STRING
0x014 (0x000) Length : Uint2B
0x016 (0x002) MaximumLength : Uint2B
0x018 (0x004) Buffer : Ptr32
0x01C BaseDllName : UNICODE_STRING
0x01C (0x000) Length : Uint2B
0x01E (0x002) MaximumLength : Uint2B
0x020 (0x004) Buffer : Ptr32


============find function=====================

5. kernel32.dll base address + 0x3c

6. exports directory offset =kernel32.dll base address+PE header offset+120(0x78)

7. exports directory table=kernel32.dll base address+exports directory offset

8. name pointers table =exports directory table+32

9. name pointers table (함수 이름이나 hash사용)

10. exports directory table+36
ordinals table 함수의 주소를 가르킨다. ordinals table의 서수의 순서에 근거하여 함수의 주소를 찾아낸다.


============heap overflow 에서 peb 이용방법================

FastPebLockRoutine 이 함수를 덮어쓴다 (undocumented 오프셋 위치는 PEB + 0x20
메모리:0x7ffdf020 0x7ffdf024)

(정의)Address of fast-locking routine for PEB. Definition of routine is:

typedef void (*PPEBLOCKROUTINE)(

PVOID PebLock

);

Peb->FastPebLockRoutine =>&RtlEnterCriticalSection (0xC0000005) overwrite
잘못된 메모리참조

=====================================================================================
undocumented peb source code

#define LDRP_STATIC_LINK 0x00000002 // dll은 과정까지 정적 링크한다
#define LDRP_IMAGE_DLL 0x00000004
#define LDRP_LOAD_IN_PROGRESS 0x00001000 //모듈 로드
#define LDRP_UNLOAD_IN_PROGRESS 0x00002000 //모듈 언로드
#define LDRP_ENTRY_PROCESSED 0x00004000 //
#define LDRP_ENTRY_INSERTED 0x00008000
#define LDRP_CURRENT_LOAD 0x00010000
#define LDRP_FAILED_BUILTIN_LOAD 0x00020000
#define LDRP_DONT_CALL_FOR_THREAD 0x00040000
#define LDRP_PROCESS_ATTACH_CALLED 0x00080000 // (DllMain)
#define LDRP_DEBUG_SYMBOLS_LOADED 0x00100000
#define LDRP_IMAGE_NOT_AT_BASE 0x00200000
#define LDRP_WX86_IGNORE_MACHINETYPE 0x00400000 // 사용한다! kdex2x86.strct _PEB_LDR_DATA

다음은 peb를 이용해 현재의 디렉토리 정보 얻을때 사용할 수 있는 peb에 속해있는 구조체------------
_RTL_USER_PROCESS_PARAMETERS (peb + 0x10)

typedef struct _RTL_USER_PROCESS_PARAMETERS
{
ULONG MaximumLength; // 00h
ULONG Length; // 04h
ULONG Flags; // 08h
ULONG DebugFlags; // 0Ch
PVOID ConsoleHandle; // 10h
ULONG ConsoleFlags; // 14h
HANDLE InputHandle; // 18h
HANDLE OutputHandle; // 1Ch
HANDLE ErrorHandle; // 20h
CURDIR CurrentDirectory; // 24h ********현재의 디렉토리 정보 ************
UNICODE_STRING DllPath; // 30h
UNICODE_STRING ImagePathName; // 38h
UNICODE_STRING CommandLine; // 40h
PWSTR Environment; // 48h
ULONG StartingX; // 4Ch
ULONG StartingY; // 50h
ULONG CountX; // 54h
ULONG CountY; // 58h
ULONG CountCharsX; // 5Ch
ULONG CountCharsY; // 60h
ULONG FillAttribute; // 64h
ULONG WindowFlags; // 68h
ULONG ShowWindowFlags; // 6Ch
UNICODE_STRING WindowTitle; // 70h
UNICODE_STRING DesktopInfo; // 78h
UNICODE_STRING ShellInfo; // 80h
UNICODE_STRING RuntimeInfo; // 88h
RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20]; // 90h
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;

vxmag-ex)
mov eax, dword ptr fs:[30h] ; goto PEB
mov eax, dword ptr [eax+10h] ; goto RTL_USER_PROCESS_PARAMETERS
add eax, 24h ; goto CurrentDirectory
mov eax, dword ptr [eax+4] ; gimme unicode_buffer


typedef struct _PEB_LDR_DATA {

unsigned int Length ; // 0x00
int Initialized ; // 0x04
PVOID SsHandle ; // 0x08
LIST_ENTRY InLoadOrderModuleList ; // 0x0c
LIST_ENTRY InMemoryOrderModuleList ; // 0x14
LIST_ENTRY InInitializationOrderModuleList ;// 0x1c

} PEB_LDR_DATA, *PPEB_LDR_DATA ; // Windows 2000 SourceCode의 속에 LDR DATA TABLE ENTRY의 정의가 없다, 그러나 그것은 가장 중요한 구조이다.

typedef struct _LDR_DATA_TABLE_ENTRY // offset
{

LIST_ENTRY InLoadOrderLinks; // 0x00
LIST_ENTRY InMemoryOrderLinks; // 0x08
LIST_ENTRY InInitializationOrderLinks; // 0x10
ULONG DllBase; // 0x18
ULONG EntryPoint; // 0x1C
ULONG SizeOfImage; // 0x20
UNICODE_STRING FullDllName; // 0x24
UNICODE_STRING BaseDllName; // 0x2C
ULONG Flags; // 0x34
SHORT LoadCount; // 0x38
WORD Fill; // 0x3A
LIST_ENTRY HashLinks ; // 0x3C
ULONG TimeDateStamp; // 0x44
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; // 0x48 bytes


#define LDRP_HASH_TABLE_SIZE 32
#define LDRP_HASH_MASK (LDRP_HASH_TABLE_SIZE-1)
#define LDRP_COMPUTE_HASH_INDEX(ch) (((ch) - 'a') & LDRP_HASH_MASK) // 사용한다! kdex2x86.strct PEB

PEB2를 바꾼다
typedef struct _PEB2 { BYTE Reserved[12] ; PPEB_LDR_DATA Ldr ; // 0x0C
} PEB2, *PPEB2 ;

** PEB의 필드 debug **

kd> !strct _PEB

--------------------------------------------------

 

http://leony.egloos.com/369899

  Comments,     Trackbacks

TEB structure

TEB structure 

03.
// Instead of using the Tls fields, use the Win32 TLS APIs
04.//     TlsAlloc, TlsGetValue, TlsSetValue, TlsFree
05.//
06.// Instead of using the ReservedForOle field, use the COM API
07.//     CoGetContextToken
08.//
09.typedef struct _TEB {
10.    union {
11.        struct {
12.            BYTE Reserved1[1952];
13.            PVOID Reserved2[412];
14.            PVOID TlsSlots[64];
15.            BYTE Reserved3[8];
16.            PVOID Reserved4[26];
17.            PVOID ReservedForOle;  // Windows 2000 only
18.            PVOID Reserved5[4];
19.            PVOID TlsExpansionSlots;
20.        };
21.        struct {
22.            NT_TIB          Tib;                        /* 000 */
23.            PVOID           EnvironmentPointer;         /* 01c */
24.            CLIENT_ID       ClientId;                   /* 020 */
25.            PVOID           ActiveRpcHandle;            /* 028 */
26.            PVOID           ThreadLocalStoragePointer;  /* 02c */
27.            PPEB            Peb;                        /* 030 */
28.            ULONG           LastErrorValue;             /* 034 */
29.            ULONG           CountOfOwnedCriticalSections;/* 038 */
30.            PVOID           CsrClientThread;            /* 03c */
31.            PVOID           Win32ThreadInfo;            /* 040 */
32.            ULONG           Win32ClientInfo[31];        /* 044 used for user32 private data in Wine */
33.            PVOID           WOW32Reserved;              /* 0c0 */
34.            ULONG           CurrentLocale;              /* 0c4 */
35.            ULONG           FpSoftwareStatusRegister;   /* 0c8 */
36.            PVOID           SystemReserved1[54];        /* 0cc used for kernel32 private data in Wine */
37.            LONG            ExceptionCode;              /* 1a4 */
38.            ACTIVATION_CONTEXT_STACK ActivationContextStack; /* 1a8 */
39.            BYTE            SpareBytes1[24];            /* 1bc used for ntdll private data in Wine */
40.            PVOID           SystemReserved2[10];        /* 1d4 used for ntdll private data in Wine */
41.            GDI_TEB_BATCH   GdiTebBatch;                /* 1fc used for vm86 private data in Wine */
42.            ULONG           gdiRgn;                     /* 6dc */
43.            ULONG           gdiPen;                     /* 6e0 */
44.            ULONG           gdiBrush;                   /* 6e4 */
45.            CLIENT_ID       RealClientId;               /* 6e8 */
46.            HANDLE          GdiCachedProcessHandle;     /* 6f0 */
47.            ULONG           GdiClientPID;               /* 6f4 */
48.            ULONG           GdiClientTID;               /* 6f8 */
49.            PVOID           GdiThreadLocaleInfo;        /* 6fc */
50.            PVOID           UserReserved[5];            /* 700 */
51.            PVOID           glDispachTable[280];        /* 714 */
52.            ULONG           glReserved1[26];            /* b74 */
53.            PVOID           glReserved2;                /* bdc */
54.            PVOID           glSectionInfo;              /* be0 */
55.            PVOID           glSection;                  /* be4 */
56.            PVOID           glTable;                    /* be8 */
57.            PVOID           glCurrentRC;                /* bec */
58.            PVOID           glContext;                  /* bf0 */
59.            ULONG           LastStatusValue;            /* bf4 */
60.            UNICODE_STRING  StaticUnicodeString;        /* bf8 used by advapi32 */
61.            WCHAR           StaticUnicodeBuffer[261];   /* c00 used by advapi32 */
62.            PVOID           DeallocationStack;          /* e0c */
63.            PVOID           TlsSlots_[64];              /* e10 */
64.            LIST_ENTRY      TlsLinks;                   /* f10 */
65.            PVOID           Vdm;                        /* f18 */
66.            PVOID           ReservedForNtRpc;           /* f1c */
67.            PVOID           DbgSsReserved[2];           /* f20 */
68.            ULONG           HardErrorDisabled;          /* f28 */
69.            PVOID           Instrumentation[16];        /* f2c */
70.            PVOID           WinSockData;                /* f6c */
71.            ULONG           GdiBatchCount;              /* f70 */
72.            ULONG           Spare2;                     /* f74 */
73.            ULONG           Spare3;                     /* f78 */
74.            ULONG           Spare4;                     /* f7c */
75.            PVOID           ReservedForOle_;            /* f80 */
76.            ULONG           WaitingOnLoaderLock;        /* f84 */
77.            PVOID           Reserved5_[3];              /* f88 */
78.            PVOID          *TlsExpansionSlots_;         /* f94 */
79.            ULONG           ImpersonationLocale;        /* f98 */
80.            ULONG           IsImpersonating;            /* f9c */
81.            PVOID           NlsCache;                   /* fa0 */
82.            PVOID           ShimData;                   /* fa4 */
83.            ULONG           HeapVirtualAffinity;        /* fa8 */
84.            PVOID           CurrentTransactionHandle;   /* fac */
85.            PVOID           ActiveFrame;                /* fb0 */
86.            PVOID          *FlsSlots;                   /* fb4 */
87.                        struct _TEB    *self;
88.        };
89.    };
90.} TEB;
91.typedef TEB *PTEB;

'유용한 지식 자료들 > 기타' 카테고리의 다른 글

윈도우 버전 정보 (GetVersion)  (0) 2012.12.07
PEB structure  (0) 2012.08.09
Win32 Thread Information Block (TIB), TEB  (0) 2012.08.08
64비트 인지 아닌지 확인하기  (0) 2012.07.18
Clustering VS Classification  (0) 2012.06.27
  Comments,     Trackbacks

Win32 Thread Information Block (TIB), TEB

Position Length Windows Versions Description
FS:[0x00] 4 Win9x and NT Current Structured Exception Handling (SEH) frame
FS:[0x04] 4 Win9x and NT Top of stack
FS:[0x08] 4 Win9x and NT Current bottom of stack
FS:[0x0C] 4 Unknown - TIB Subsystem?
FS:[0x10] 4 NT Fiber data
FS:[0x14] 4 Win9x and NT Arbitrary data slot
FS:[0x18] 4 Win9x and NT Linear address of TIB
---- End of NT subsystem independent part ----
FS:[0x1C] 4 NT Environment Pointer
FS:[0x20] 4 NT Process ID
FS:[0x24] 4 NT Current thread ID
FS:[0x28] 4 NT Active RPC Handle
FS:[0x2C] 4 Win9x and NT Linear address of the thread-local storage array
FS:[0x30] 4 NT Linear address of Process Environment Block (PEB)
FS:[0x34] 4 NT Last error number
FS:[0x38] 4 NT Count of owned critical sections
FS:[0x3C] 4 NT Address of CSR Client Thread
FS:[0x40] 4 NT Win32 Thread Information

~

FS:[0xF28] 4 NT Thread error mode (RtlSetThreadErrorMode)

http://en.wikipedia.org/wiki/Win32_Thread_Information_Block

 

FS레지스터에 관한 정보,, 빨간색 글자가 많이 쓰임.

 

'유용한 지식 자료들 > 기타' 카테고리의 다른 글

PEB structure  (0) 2012.08.09
TEB structure  (0) 2012.08.09
64비트 인지 아닌지 확인하기  (0) 2012.07.18
Clustering VS Classification  (0) 2012.06.27
Aho Corasick String Matching in Python  (0) 2012.05.17
  Comments,     Trackbacks

64비트 인지 아닌지 확인하기

http://blog.naver.com/PostView.nhn?blogId=denoil&logNo=30043054121

'유용한 지식 자료들 > 기타' 카테고리의 다른 글

TEB structure  (0) 2012.08.09
Win32 Thread Information Block (TIB), TEB  (0) 2012.08.08
Clustering VS Classification  (0) 2012.06.27
Aho Corasick String Matching in Python  (0) 2012.05.17
리눅스에서 SSD  (0) 2012.05.15
  Comments,     Trackbacks

Clustering VS Classification

CLUSTERING

- Data is not labeled

- Group points that are "close" to each other

- Identify structure or patterns in data

- Unsupervised learning


CLASSIFICATION

- Labeled data points

- Want a "rule" that assigns labels to new points

- Supervised learning





군집화/분류화 그런 차이? 


  Comments,     Trackbacks

Aho Corasick String Matching in Python

Aho Corasick String Matching in Python

from collections import deque
class State:
    sid = None        ## store the id of state
    value = None      ## stores values of state
    tranList = None    ## used to store the list of next states for transition
    outputSet = None    ## it is set datastructure for storing the outputs at that state
    failState = None

    def __init__(self ,sid, val):
        self.sid = sid
        self.value = val
        self.tranList = []
        self.failState = 0
        self.outputSet = set()

    def getTransition(self, val):
        """ this function gets the next state on input val"""
        for node in self.tranList:
            if node.value == val:
                return node
        return None
   

    def testTransition(self, val):
        """ This checks whether there is transition or not on input val"""
        """ for current state, the transition is always true on any input"""

        if self.sid == 0:    
           return True
        else:
            for nd in self.tranList:
                if nd.value == val:
                    return True
            return False
       
    def addOutput(self, key):
        """This adds the key to the output in the state"""
        self.outputSet = self.outputSet ^ key
       
         
    ##------------------------------------------------------------------------
   

class ahoCorasick:
    root = None
    newstate = None

    def __init__(self):
        self.root = State(0, ' ')
        self.newstate = 0

    def addKeyword(self, keywords):
        """Adds the keyword in the tree"""
   
        for key in keywords.split(' '):
           
            j = 0
            state = 0
            current = self.root
            key = key.upper()

            while j < len(key):
                ch = key[j]
                j = j+ 1
                child = current.getTransition(ch)
                if child != None:
                    current = child
                else:
                    self.newstate = self.newstate +1
                    nd = State(self.newstate, ch)
                    current.tranList.append(nd)
                    current = nd
                    while j < len(key):
                        self.newstate = self.newstate +1
                        nd2 = State(self.newstate, key[j])
                        current.tranList.append(nd2)
                        current = nd2
                        j = j+1
                    break
            current.outputSet.add(key)
       
##-------------------------------------------------------------------
    def setFailTransitions(self):
        """Sets the fail transitions in tree"""
        queue = deque()
        current = self.root
        child = self.root

        for nd in self.root.tranList:
            queue.append(nd)
            nd.failState = self.root

        while len(queue) != 0:
            r = queue.popleft()
            for nd in r.tranList:
                queue.append(nd)
                state = r.failState
                val = nd.value
                current = state
                while True:
                    if current.testTransition(val) == False:
                        current = current.failState
                    else:
                        break
                child = current.getTransition(val)
                if child == None:
                    nd.failState = current
                else:
                    nd.failState = child
            nd.addOutput(nd.failState.outputSet)

##--------------------------------------------------------------------------------------------------
    def findSubstrings(self, findStr):
        """ Finds all substrings of input which are keywords in the tree"""
        for string in findStr.split(' '):
            string = string.upper()
            print "Finding substrings in ", string
            current = self.root
            j = 0
       
            while j < len(string):
                while True:
                    if current.testTransition(string[j]) == False:
                        current = current.failState
                    else:
                        child = current.getTransition(string[j])
##                      print "before break", child.sid
                        break
                if child != None:
##                  print "in none"
                    current = child
                    if len(child.outputSet) != 0:
                        print j
                        itr = iter(child.outputSet)
                        for keyw in itr:
                            print keyw
                j = j + 1   
                   
   
##---------------------------------------------------------
    def displayTree(self):
        """ It is used to display the tree of keywords. Prints ID of node and value of node"""
        queue = deque()
        for nd in self.root.tranList:
            queue.append(nd)

        while len(queue) !=0:
            node = queue.popleft()
            for nd in node.tranList:
                queue.append(nd)
            print node.sid, node.value
           
               
    def displayOutput(self):
        """ This function displays the outputs at a state"""
        queue = deque()
        for nd in self.root.tranList:
            queue.append(nd)

        while len(queue) !=0:
            node = queue.popleft()
            for nd in node.tranList:
                queue.append(nd)
           
            itr = iter(node.outputSet)
            if len(node.outputSet) !=0:
                print node.sid
            for string in itr:
                print string

if (__name__ == "__main__"):
   
    x = ahoCorasick()
    """ Usage: Create object of ahoCorasick
        to enter keywords use addKeyword("string of keywords")
        then call setFailTransitions (fail function)
        to find substrings of string use findSubstrings"""

##    x.addKeyword("he")
##    x.addKeyword("she")
##    x.addKeyword("his")
##    x.addKeyword("hers")
   
##    x.addKeyword("ATC")
##    x.addKeyword("TC")
   
##    x.displayOutput()
   
####    x.enter("help")
####    x.enter("hi")
   
    x.addKeyword("john jane")
  
       
    x.setFailTransitions()
##    x.findSubstrings("ACGATCTCTCGATC")
    x.findSubstrings("johnjane")
  Comments,     Trackbacks

리눅스에서 SSD

http://our-psychommunity.com/blog/lazyman/29


1. 파일시스템 선택 - 저널링없는 ext4

오래된 SSD+Linux 가이드는, 드라이브의 수명을 늘리기 위해서 ext3/ext4 같은 저널링 파일 시스템의 쓰기 낭비를 피하는, ext2 파일 시스템을 추천한다. TRIM 지원이 나타나면서 ext2는 최고의 선택이 아니게 되었다. TRIM 명령은 ext2 파일시스템에서 돌아가지만, 두개의 단점이 있다.

   1. Ext2는 오프라인 TRIM만을 지원한다 - 다시 말하면, 파일시스템을 읽기전용으로 마운트해야한다.
   2. hdprm 이나 hdprm의 랩퍼 스크립트인 wiper.sh 을 사용해서 TRIM 명령어를 직접 실행해야한다.

ext4 파일시스템은 이러한 제한이 없다. ext4 파일시스템에서 저널링 기능을 끌수있게 되면서 ext2 보다 더 나은 선택이 되었다. 저널이 없는 파일시스템은 깨끗이 언마운트되지 않으면(예를 들어, 전원이 갑자기 나갔을 경우) 데이터 손실이 더 쉽다는걸 확실히 알아야 한다. 하지만 이 글을 읽은 이후에는, 드라이브의 수명을 늘리기 위한 기회를 얻을 수 있을 것이다.

ext4의 저널을 어떻게 끌 것인가? 첫번째, 저널의 제거는 파일시스템이 마운트된 상태에서는 할 수 없다. 운영체제가 포함된 드라이브의 저널을 끄려면, 다른 드라이브로 부팅하는게 필요하다. 난 Arch Linux를 사용하고, 우분투 라이브 CD 같은 Arch 인스톨 디스크로 작업했다. 파일시스템 변경 툴의 필요성이 표준 이슈가 되면서, 여러 리눅스 라이브 배포판으로 작업 가능하게 되었다.

다른 디스크로 부팅 했으면, 터미널을 열고 루트 권한을 얻거나 sudo를 사용해 명령어를 입력해라.  저널을 제거하기를 원하는 ext4 파티션이  /dev/sda1 이라고 가정하고, 아래에 따라 작업한다.
명령어:
tune2fs -O ^has_journal /dev/sda1
그리고 나서 파일시스템 검사를 돌리는게 좋다.
e2fsck -f /dev/sda1
두 번째 단계를 완료 하지 않으면 파일 시스템이 마운트 되지 않는다는 보고를 몇개 봤다. 그러니까 건너띄지 말자. 여러분은 SSD를 가지고 있고, fsck는 진짜로 빠르게 진행된다.
컴퓨터를 재시작하고, 저널이 꺼진 ext4 파티션이 포함된 SSD로 부팅하자. 터미널을 열고 실행해라
dmesg | grep EXT4
모든게 잘 됐다면 부팅 과정에서 아래 메시지를 보게 될거다.
EXT4-fs(sda1): mounted filesystem without journal
예전처럼 저널을 추가하고 싶으면, 위 단계를 실행해라. 단, tune2fs 명령에서 caret(^) 을 빼고 나서.

2. TRIM 지원 켜기

TRIM 지원이 없으면, SSD는 결국 엄청 느려질 꺼다. 근본 원인은 SSD가 쓰는 것보다 더 큰 블록 데이터를 지운다는 사실이다. TRIM없이 데이터를 지웠을때, 드라이브 펌웨어는 캐쉬로 전체 블록을 복사하고, 전체 블락을 지우고, 삭제된 데이터를 뺀 캐쉬의 내용을 쓴다. - 블록의 모든 데이터가 파일시스템에서 지워졌다고 표시가 되어있더라도 말이다. TRIM이 있다면, 운영체제는 블록이 파일시스템에서 삭제 된 시점에, free로 표시됐다고 드라이브에게 전달할 수 있다. SSD는 TRIM 지원 펌웨어 발표를 시작할꺼고, 리눅스 커널은 2.6.33 부터 TRIM 지원을 추가하기 시작했다.

처음에 실행중인 커널이 TRIM 지원을 하는지 확인하자. 다음을 실행해라
uname -a
커널 버전 숫자를 봐라. 2.6.33 이거나 더 높으면 커널은 TRIM을 지원할꺼다. 어떤 배포판은 *어쩌면* TRIM 코드를 이전 커널에 집어넣을 수도 있지만, 그런 거까지 조사해본 적은 없다.
다음은, hdparm 명령을 사용해 드라이브가 TRIM을 지원하는지 확인해라. SSD가 /dev/sda1이라고 가정하고 명령어를 넣는다.
hdparm -I /dev/sda
드라이브 기능 목록이 출력될꺼다. 드라이브에서 기능이 지원되는 걸 표시하기위해 * 가 같이 나온다. TRIM이 지원되면 아래줄처럼 보일꺼다.
* Data Set Management TRIM supported
(줄의 시작에 * 표시를 확인해라. 기능을 지원한다는 뜻이다.)
커널과 드라이브가 TRIM을 지원한다고 가정하고, 위에 설명한 ext4 파일 시스템을 사용중이면 /etc/fstab 파일에 “discard” 옵션을 추가하는 걸로 켤 수 있다. ext4 파일시스템을 사용중인 줄을 보고 바꿔라.
이거에서:
/dev/sda1 / ext4 defaults
이걸로:
/dev/sda1 / ext4 discard,defaults
물론, 파티션하고 마운트 지점하고 기존 옵션은 다를꺼다. 요점은 “discard” 옵션을 네번째 행에다가 추가하는 거다. 새로 수정한 fstab파일을 테스트하려면, 루트 권한으로 실행해라:
mount -oremount /dev/sda1
그리고 실행해라
mount
그러면 마운트된 모든 파일시스템이 옵션이랑 같이 보일꺼다. 위의 예제를 사용하면,  작업 중에 알게 된 “discard”옵션을 찾게 된다.
/dev/sda1 on / type ext4 (rw,discard)

3. 스왑을 위해 무엇을 할 것인가

스왑 공간은 SSD를 사용할 때, 미묘한 문제가 있다. 평균 시스텝의 메모리가 수기가 바이트가 되면서  스왑의 필요성이 감소했다. 예로, 난 2GB 메모리를 가지고 여러 가상머신을 돌리고, 기본적인 웹브라우징과 ssh 세션으로도 다 쓰지 못한다. 하지만 여러분의 컴퓨터가 최대절전모드를 사용한다면, 스왑공간은 적어도 시스템의 메모리보다 같아야 한다. 최대 절전모드 중에는 메모리의 내용을 스왑공간에 보관하기 때문이다.

스왑 공간을 가지고 있다면, 시스템의 “swappiness” 파라미터를 변경하는걸 추천한다. Swappiness는 0부터 100까지 숫자이며, 리눅스가 메모리에서 디스크의 스왑 공간으로 데이터를 얼마나 적극적으로 이동 시키는 지를 나타낸다. 숫자가 높으면, 시스템이 메모리 부족시에 스왑으로 이동하는 것을 더욱 선호한다.

현재 swappiness 설정을 보려면,
/proc/sys/vm/swappiness 파일의 내용을 보면 된다.
cat /proc/sys/vm/swappiness
SSD를 사용할때, 나는 swappiness를 항상 1로 설정했다. 스왑공간이 있지만, 가장 까다로운 상황을 빼고는 절대 사용하지 않을것이다. 다시말하면, 이것은 쓰기 회수를 줄여 디스크의 수명을 늘이자는 것이다. swappiness 값을 변경하려면
/etc/rc.local 파일에 아래 줄을 추가해라.
echo 1 > /proc/sys/vm/swappiness
/etc/rc.local 은 시스템 시작시, 다른 모든 초기화 스크립트가 실행된 후에 실행되는 파일이며, 다른 초기화 스크립트 안에 적용되지 않는 최적화를 위해 관리자가 사용하는 것이다.

다른 최적화들...

나머지 팁들은 여러 사이트에 돌아다니는 것들이다. 내 경우엔 잘 작동해서 추가한다.

4. noatime 옵션을 가지고 파일시스템을 마운트하자.

스텝2에서 /etc/fstab 에 “discard” 옵션을 추가한것 처럼, “noatime”옵션을 추가하면 된다. “noatime”을 사용하는 것은, 리눅스가 파일과 디렉토리에 마지막 접근 시간을 갱신하는 것을 막기 위해서다. 드라이브의 수명을 늘리기 위해 쓰기 회수를 줄이고, 약간의 성능 향상도 가져온다. 2단계에서 작업한 것과 같은 파티션을 사용 중이면, /etc/fstab의 그 줄을 
이거에서
/dev/sda1 / ext4 discard,defaults
이걸로 바꾸자.
/dev/sda1 / ext4 noatime,discard,defaults
2단계와 같은 방법으로 fstab파일을 테스트해라. mount 명령어와 -oremount 옵션을 사용한걸 기억하자.
참고: ext2, ext3, ext4 파일시스템에서도 “noatime”옵션 사용이 가능하다.

5. noop 디스크 스케줄러를 사용하자

리눅스는, 디스크를 다루기 위해 읽기 순서와 쓰기 요청을 결정할 책임이 있는 ,몇가지 다른 디스크 스케줄러를 가지고 있다.  noop 스케줄러를 사용하는 것은, 리눅스가  데이터들이 디스크의 물리적인 위치 어디에 놓여 있는지를 전혀 고려하지 않고, 받은 순서대로 요청을 처리하는 간단한 방식을 적용하는 걸 의미한다..
시스템이 사용중인 스케줄러를 보려면
/sys/block/sda/queue/scheduler 의 내용을 보면 된다.
cat /sys/block/sda/queue/scheduler
대괄호 안에 있는게 현재 사용중인 스케줄러다.
[noop] deadline cfq
noop 스케줄러를 사용하도록 하려면
/etc/rc.local 파일에 아래 줄을 추가해라.
echo noop > /sys/blocks/sda/queue/scheduler
그건 그렇고, 리눅스에서 적용할 수 있는 다른 스케줄러를 살펴보려면, 리눅스 매거진의 이 기사를 확인해라.

6. 파이어폭스의 캐쉬를 tmpfs로 옮기자.

대부분의 사용자는, 파이어폭스를 사용하는 것이 디스크 활성화의 가장 큰 비율의 원인이 된다.  디스크의 쓰기 회수를 줄이기 위해서, 캐쉬를 tmpfs 파일시스템으로 옮길 수 있다.  브라우저의 캐쉬는 디스크를 거치지 않고, 물리적인 메모리에(RAM) 저장된다. 물론, 리부팅하면 사라지지만, 대부분의 사람은 그것을 신경쓰지 않을 것이다.
tmpfs 파일 시스템을 만들기 위해 /etc/fstab 파일을 한번 더 수정해야 한다. 아래 줄은 시스템의 /tmp 디렉토리를 tmpfs로 변환시킨다.
none /tmp tmpfs defaults 0 0
재부팅 후에, mount 명령어를 사용해서, 수정사항이 아래 줄처럼 작업되었는지 확인해라.
none on /tmp type tmpfs (rw)
tmpfs 가 생성된 것을 확인했다면, 파이어폭스를 열고 주소창에 about:config 를 입력하자. 마우스 오른쪽 버튼을 클릭하고 새로만들기->문자열 을 선택해라. 환경 설정 이름을 “browser.cache.disk.parent_directory”  으로 입력하고, 문자열 값에 "tmp/firefox-cache"를 집어넣자.
*
파이어폭스를 재시작하고 /tmp 디렉토리 안을 살펴보자. 브라우저의 캐쉬가 새로운 위치에 있는지 확인해라.

결론
기존의 하드 드라이브와 SSD 의 기본적인 차이점을 이해하고 있다면, 왜 수정사항이 이치에 맞는지 쉽게 알 수 있다. 추측하자면, 일이년 안에 이런 직접 변경하는 내용은 필요 없을 것이다. SSD는 주류가 될 것이고, 리눅스 배포판들은 여러분들을 위해 미리 설정되어 나올 것이다. 그러나 지금은, 여러분에게 이 가이드가 도움이 되기를 바란다.

Trackback Address >> http://our-psychommunity.com/blog/lazyman/trackback/29



펌이요~...

결론적으로 Vsphere에서는 크게 소용이 없다는..Trim 지원이 안됌

  Comments,     Trackbacks

How to Compile and Install Linux Kernel 3.1 / 3.0 in Ubuntu 11.10, 11.04, 10.10 and 10.04

How to Compile and Install Linux Kernel 3.1 / 3.0 in Ubuntu 11.10, 11.04, 10.10 and 10.04




Here in this post I will explain how to compile and install Linux Kernel 3.0 and Linux Kernel 3.1 in Ubuntu. Linux Kernel 3.0.1 is the latest stable release and you can download it from kernel.org. If you are new to Linux then I strongly recommend you try with Linux Kernel 3.0 and you can later patch it with Linux Kernel 3.0.1. If you don’t like to compile the kernel, then you can directly install the debian packages Click Here.

Fedora users Click Here.

Update: Follow the same steps to compile and install the Linux Kernel 3.1 in your system.

Dependencies

To compile Linux Kernel the following are required to be installed.

  • gcc latest version,
  • ncurses development package and
  • system packages should be up-to date

To install the dependencies run the following commands in terminal and type the password for the user, when prompted.

For gcc

$ sudo apt-get install gcc

For ncurses development package

$ sudo apt-get install libncurses5-dev

After installing the above packages then update your system by running the following command

$ sudo apt-get update && sudo apt-get upgrade

Now download the Linux Kernel 3.0 from kernel.org or by using the below command. If you are trying with Linux Kernel 3.1 / 3.0.7 then just replace the name linux-3.0 with linux-3.1 / linux-3.0.7 in all commands below.

Update

Download the Kernel source from github, no download link available on kernel.org  Click Here for mirror downloads. 

$ wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3.0.tar.bz2

Once the download complete move to the directory where you have downloaded the kernel package “linux-3.0.tar.bz2“. Now extract the tar file to the location “/usr/src/“.

To move to the directory, for example if the downloaded package is in your Downloads directory. Use the below command.

$ cd Downloads/

To extract the tar file run the following command. Type the password for the user when prompted.

$ sudo tar -xvf linux-3.0.tar.bz2 -C /usr/src/

Now move to the directory where the extracted file is, or copy and paste the below command in terminal.

$ cd /usr/src/linux-3.0/

Now you can configure, compile and install Linux Kernel 3.0 in your system. Run the commands one by one and type the password for the user, when prompted.

To Configure

$ sudo make menuconfig

The above command is used to configure the Linux kernel. Once you execute the command, you will get a pop up window with the list of menus and you can select the items for the new configuration. If your unfamiliar with the configuration just check for the file systems menu and check whether ext4 is chosen or not, if not select it and save the configuration. Check the screen shot below for menuconfig.

If you like to have your existing configuration then run the below command.

$ sudo make oldconfig

There are other alternate configuration commands are available and you can find them in README file under linux-3.0 directory.

To Compile

$ sudo make

The above command is used to compile the Linux Kernel. It will take some time to complete it, approximately 40 min to 50 min it depends on your system configuration.

To Install

$ sudo make modules_install install

The above command will install the Linux Kernel 3.0 into your system. It will create some files under /boot/ directory and it will automatically make a entry in your grub.cfg. Check whether it made correct entry and check for the files it created.

The files under /boot/ directory are,

  • System.map-3.0.0
  • vmlinuz-3.0.0
  • initrd.img-3.0.0
  • config-3.0.0

If you unable to find the initrd.img-3.0.0 file then create it. Run the below command to create it.

$ sudo update-initramfs -u -k 3.0.0

Update

If the above command unable to update / generate the initramfs then run the following command to create new initramfs.

$ sudo update-initramfs -c -k 3.0.0

Your grub.cfg file should be like the screen shots(example) below if not edit it.

For Linux Kernel 3.0

For Linux Kernel 3.0.1

To modify the grub.cfg under “/boot/grub/” directory. Open the file using below command.

$ sudo gedit /boot/grub/grub.cfg

After modifying your grub.cfg, update your grub by running the following command.

$ sudo update-grub

Restart your system by default it will boot in Ubuntu 3.0.0, you can able to see while booting. To check after booting open a terminal and type “uname -r“. Check the screen shot below.

Hope this will be helpful for you!!!

출처 : http://www.howopensource.com/2011/08/how-to-compile-and-install-linux-kernel-3-0-in-ubuntu-11-04-10-10-and-10-04/ 

  Comments,     Trackbacks

PPT 활용에 대한 네이버 카페.
정말 대단한 사람들 많다~
http://opencast.naver.com/PT827/33/flow  
  Comments,     Trackbacks