System.Data.SQLite
Check-in [da8e102e28]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:no message
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sourceforge
Files: files | file ages | folders
SHA1: da8e102e28e2a234b5d6d4b747e9e3250a2ec132
User & Date: rmsimpson 2006-01-20 15:59:57
Context
2006-01-20
16:08
no message check-in: f58ef51a62 user: rmsimpson tags: sourceforge
15:59
no message check-in: da8e102e28 user: rmsimpson tags: sourceforge
15:54
1.0.24.5 check-in: e30d78fb6a user: rmsimpson tags: sourceforge
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added SQLite.Interop/merge.h.



































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// This code was automatically generated from assembly
// C:\src\SQLite.NET\System.Data.SQLite\bin\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[85184] = {0}; // The number of bytes to reserve
#pragma data_seg()

#pragma comment(lib, "mscoree")

extern BOOL WINAPI _CorDllMain(HANDLE, DWORD, LPVOID);
__declspec(dllexport) BOOL WINAPI _CorDllMainStub(HANDLE hModule, DWORD dwReason, LPVOID pvReserved)
{
  return _CorDllMain(hModule, dwReason, pvReserved);
}

Added tools/mergebin/MetaData.cpp.













































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#include "StdAfx.h"
#include "MetaData.h"

CMetadata::CStream::operator LPBYTE() const
{
  return m_pbData;
}

CMetadata::CMetadata(CPEFile& peFile) : m_peFile(peFile)
{
  PIMAGE_COR20_HEADER pCor = m_peFile;
  if (!pCor) throw;

  LPBYTE pb = (LPBYTE)m_peFile.GetPtrFromRVA(pCor->MetaData.VirtualAddress);
  LPBYTE pbRoot = pb;
  size_t x;
  if (!pb) throw;

  m_pdwSignature     = (LPDWORD)pb;
  m_pwMajorVersion   = (LPWORD)(m_pdwSignature + 1);
  m_pwMinorVersion   = m_pwMajorVersion + 1;
  m_pdwVersionLength = (LPDWORD)(m_pwMinorVersion + 3);
  m_pszVersion       = (LPSTR)(m_pdwVersionLength + 1);

  pb = (LPBYTE)m_pszVersion;
  x = *m_pdwVersionLength;
  if (x % 4) x += 4 - (x % 4);
  pb += x;
  pb += 2;
  
  m_pwStreams        = (LPWORD)pb;
  m_pStreams = new CStream[*m_pwStreams];
  pb = (LPBYTE)(m_pwStreams + 1);

  for (WORD n = 0; n < *m_pwStreams; n++)
  {
    m_pStreams[n].m_pdwOffset  = (LPDWORD)pb;
    m_pStreams[n].m_pdwSize    = m_pStreams[n].m_pdwOffset + 1;
    m_pStreams[n].m_pszName    = (LPSTR)(m_pStreams[n].m_pdwSize + 1);
    m_pStreams[n].m_pbData     = pbRoot + (*m_pStreams[n].m_pdwOffset);

    x = strlen(m_pStreams[n].m_pszName) + 1;
    if (x % 4) x += 4 - (x % 4);

    pb = (LPBYTE)m_pStreams[n].m_pszName + x;
  }
}

CMetadata::~CMetadata(void)
{
  delete[] m_pStreams;
}

CMetadata::operator CPEFile&() const
{
  return m_peFile;
}

CMetadata::CStream * CMetadata::GetStream(UINT uiStream)
{
  if (uiStream >= *m_pwStreams) return NULL;
  return &m_pStreams[uiStream];
}

CMetadata::CStream * CMetadata::GetStream(LPCSTR pszStreamName)
{
  for (WORD n = 0; n < *m_pwStreams; n++)
  {
    if (_stricmp(pszStreamName, m_pStreams[n].m_pszName) == 0)
      return &m_pStreams[n];
  }
  return NULL;
}

WORD * CMetadata::StreamCount() const
{
  return m_pwStreams;
}

Added tools/mergebin/MetaData.h.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#pragma once

#include "pefile.h"

class CMetadata
{
public:
  class CStream
  {
    friend CMetadata;
  public:
    operator LPBYTE() const;

  protected:
    DWORD *m_pdwOffset;
    DWORD *m_pdwSize;
    LPSTR  m_pszName;
    LPBYTE m_pbData;
  };
public:
  CMetadata(CPEFile& peFile);
  virtual ~CMetadata(void);

protected:
  CPEFile& m_peFile;

  DWORD   *m_pdwSignature;
  WORD    *m_pwMajorVersion;
  WORD    *m_pwMinorVersion;
  DWORD   *m_pdwVersionLength;
  LPSTR    m_pszVersion;
  WORD    *m_pwStreams;
  CStream *m_pStreams;

public:
  operator CPEFile&() const;

  WORD *               StreamCount () const;
  CMetadata::CStream * GetStream   (UINT uiStream);
  CMetadata::CStream * GetStream   (LPCSTR pszStreamName);
};

Added tools/mergebin/MetaDataTables.cpp.



















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#include "StdAfx.h"
#include "MetaDataTables.h"
#include "TableData.h"

CMetadataTables::CMetadataTables(CMetadata& metaData) : m_meta(metaData)
{
  CMetadata::CStream *ps = m_meta.GetStream("#~");
  if (!ps) throw;

  *static_cast<CMetadata::CStream *>(this) = *ps;

  LPBYTE pb = m_pbData + sizeof(DWORD);
  m_pbMajorVersion = pb;
  m_pbMinorVersion = m_pbMajorVersion + 1;
  m_pbHeapOffsetSizes = m_pbMinorVersion + 1;
  // Skip a byte
  m_pullMaskValid = (UINT64 *)(m_pbHeapOffsetSizes + 2);
  m_pullMaskSorted = m_pullMaskValid + 1;

  m_pdwTableLengths = (LPDWORD)(m_pullMaskSorted + 1);

  m_dwTables = 0;
  for (int n = 0; n < 64; n++)
  {
    if ((((*m_pullMaskValid) >> n) & 1) == 1)
    {
      m_pdwTableLengthIndex[n] = &m_pdwTableLengths[m_dwTables ++];
    }
    else
    {
      m_pdwTableLengthIndex[n] = NULL;
    }
  }
  m_pbData = (LPBYTE)(m_pdwTableLengths + m_dwTables);

  for (int n = 0; n < 64; n++)
  {
    if (m_pdwTableLengthIndex[n] && g_arTableTypes[n])
    {
      m_pTables[n] = g_arTableTypes[n](this);
    }
    else
      m_pTables[n] = 0;
  }
}

CMetadataTables::~CMetadataTables(void)
{
  for (int n = 0; n < 64; n++)
  {
    if (m_pTables[n])
      delete m_pTables[n];
  }
}

UINT CMetadataTables::GetStringIndexSize(void)
{
  return ((*m_pbHeapOffsetSizes) & 0x01) == 0 ? sizeof(WORD) : sizeof(DWORD);
}

UINT CMetadataTables::GetGuidIndexSize(void)
{
  return ((*m_pbHeapOffsetSizes) & 0x02) == 0 ? sizeof(WORD) : sizeof(DWORD);
}

UINT CMetadataTables::GetBlobIndexSize(void)
{
  return ((*m_pbHeapOffsetSizes) & 0x04) == 0 ? sizeof(WORD) : sizeof(DWORD);
}

DWORD *CMetadataTables::TableRowCount(UINT uType)
{
  return m_pdwTableLengthIndex[uType];
}

DWORD CMetadataTables::GetMaxIndexSizeOf(UINT * puiTables)
{
  DWORD dwMaxRows = 0;
  DWORD *pdwLength;
  UINT uCount = 0;

  while (*puiTables)
  {
    uCount ++;
    pdwLength = m_pdwTableLengthIndex[*puiTables];
    if (pdwLength)
      dwMaxRows = max(dwMaxRows, pdwLength[0]);

    puiTables ++;
  }

  return (dwMaxRows > (ULONG)(2 << (16 - uCount))) ? 4 : 2;
}

CTableData *CMetadataTables::GetTable(UINT uId)
{
  return m_pTables[uId];
}

Added tools/mergebin/MetaDataTables.h.



























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#pragma once
#include "metadata.h"

class CTableData;

class CMetadataTables :
  public CMetadata::CStream
{
  friend CTableData;

public:
  CMetadataTables(CMetadata& metaData);
  virtual ~CMetadataTables(void);

protected:
  CMetadata&  m_meta;
  BYTE       *m_pbMajorVersion;
  BYTE       *m_pbMinorVersion;
  BYTE       *m_pbHeapOffsetSizes;
  UINT64     *m_pullMaskValid;
  UINT64     *m_pullMaskSorted;
  DWORD      *m_pdwTableLengths;

  DWORD      *m_pdwTableLengthIndex[64];
  DWORD       m_dwTables;

  CTableData *m_pTables[64];

public:
  UINT        GetStringIndexSize ();
  UINT        GetGuidIndexSize   ();
  UINT        GetBlobIndexSize   ();
  DWORD       GetMaxIndexSizeOf  (UINT *);

  DWORD *     TableRowCount      (UINT uType);

  CTableData *GetTable           (UINT uId);
};

Added tools/mergebin/PEFile.cpp.







































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#include "StdAfx.h"
#include "PEFile.h"

#define MakePtr( cast, ptr, addValue ) (cast)( (DWORD_PTR)(ptr) + (DWORD_PTR)(addValue))

CPEFile::CPEFile(void)
{
  m_hMap = NULL;
  m_hFile = INVALID_HANDLE_VALUE;
  m_pBase = NULL;
}

CPEFile::~CPEFile(void)
{
  Close();
}

HRESULT CPEFile::Open(LPCTSTR pszFile, BOOL bReadOnly)
{
  HRESULT hr = S_OK;
  Close();

  m_hFile = CreateFile(pszFile, GENERIC_READ | ((bReadOnly == FALSE) ? GENERIC_WRITE: 0), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  if (m_hFile == INVALID_HANDLE_VALUE)
  {
    hr = HRESULT_FROM_WIN32(GetLastError());
  }
  else
  {
    m_hMap = CreateFileMapping(m_hFile, NULL, (bReadOnly == TRUE) ? PAGE_READONLY:PAGE_READWRITE, 0, 0, NULL);
    if (!m_hMap)
    {
      hr = HRESULT_FROM_WIN32(GetLastError());
    }
    else
    {
      m_pBase = (PIMAGE_DOS_HEADER)MapViewOfFile(m_hMap, FILE_MAP_READ | ((bReadOnly == FALSE) ? FILE_MAP_WRITE:0), 0, 0, 0);
      if (!m_pBase)
      {
        hr = HRESULT_FROM_WIN32(GetLastError());
      }
    }
  }

  if (SUCCEEDED(hr))
  {
    PIMAGE_FILE_HEADER pImageHeader = (PIMAGE_FILE_HEADER)m_pBase;
    if (m_pBase->e_magic != IMAGE_DOS_SIGNATURE)
    {
      hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);
    }

    m_pNTHeader = MakePtr(PIMAGE_NT_HEADERS, m_pBase, m_pBase->e_lfanew);
    if (IsBadReadPtr(m_pNTHeader, sizeof(m_pNTHeader->Signature)))
    {
      hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);
    }
    else
    {
      if (m_pNTHeader->Signature != IMAGE_NT_SIGNATURE)
      {
        hr = HRESULT_FROM_WIN32(ERROR_BAD_FORMAT);
      }
    }
  }

  if (FAILED(hr)) Close();

  return hr;
}

void CPEFile::Close(void)
{
  if (m_pBase)
  {
    UnmapViewOfFile(m_pBase);
  }

  if (m_hMap)
    CloseHandle(m_hMap);

  if (m_hFile != INVALID_HANDLE_VALUE)
    CloseHandle(m_hFile);

  m_hMap = NULL;
  m_hFile = INVALID_HANDLE_VALUE;
  m_pBase = NULL;
}

PIMAGE_SECTION_HEADER CPEFile::GetEnclosingSectionHeader(DWORD rva) const
{
  PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(m_pNTHeader);

  for (UINT i=0; i < m_pNTHeader->FileHeader.NumberOfSections; i++, section++ )
  {
    DWORD size = section->Misc.VirtualSize;
    if (!size)
      size = section->SizeOfRawData;

    if ( (rva >= section->VirtualAddress) && 
      (rva < (section->VirtualAddress + size)))
      return section;
  }
  return NULL;
}

LPVOID CPEFile::GetPtrFromRVA(DWORD rva) const
{
  PIMAGE_SECTION_HEADER pSectionHdr;
  INT delta;

  pSectionHdr = GetEnclosingSectionHeader(rva);
  if ( !pSectionHdr )
    return 0;

  delta = (INT)(pSectionHdr->VirtualAddress-pSectionHdr->PointerToRawData);
  return (PVOID) (((LPBYTE)m_pBase) + rva - delta);
}

PIMAGE_SECTION_HEADER CPEFile::GetSectionHeader(LPCSTR name) const
{
  PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(m_pNTHeader);

  for (UINT i=0; i < m_pNTHeader->FileHeader.NumberOfSections; i++, section++)
  {
    if (_strnicmp((char *)section->Name,name,IMAGE_SIZEOF_SHORT_NAME) == 0)
      return section;
  }

  return NULL;
}

CPEFile::operator PIMAGE_NT_HEADERS() const
{
  if (!m_pBase) return NULL;
  return m_pNTHeader;
}

CPEFile::operator PIMAGE_DOS_HEADER() const
{
  return m_pBase;
}

CPEFile::operator PIMAGE_COR20_HEADER() const
{
  if (!m_pBase) return NULL;

  DWORD dwRVA;
  dwRVA = m_pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
  if (!dwRVA)
  {
    return NULL;
  }

  return ((PIMAGE_COR20_HEADER)GetPtrFromRVA(dwRVA));
}

Added tools/mergebin/PEFile.h.



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#pragma once

class CPEFile
{
public:
  CPEFile();
  virtual ~CPEFile(void);

protected:
  HANDLE            m_hMap;
  HANDLE            m_hFile;
  PIMAGE_DOS_HEADER m_pBase;
  PIMAGE_NT_HEADERS m_pNTHeader;

public:
  HRESULT Open  (LPCTSTR pszFile, BOOL bReadOnly = TRUE);
  void    Close (void);

  PIMAGE_SECTION_HEADER GetEnclosingSectionHeader (DWORD rva) const;
  LPVOID                GetPtrFromRVA             (DWORD rva) const;
  PIMAGE_SECTION_HEADER GetSectionHeader          (LPCSTR name) const;
  
  operator PIMAGE_DOS_HEADER   () const;
  operator PIMAGE_NT_HEADERS   () const;
  operator PIMAGE_COR20_HEADER () const;
};

Added tools/mergebin/ReadMe.txt.



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
========================================================================
    CONSOLE APPLICATION : mergebin Project Overview
========================================================================

AppWizard has created this mergebin application for you.  

This file contains a summary of what you will find in each of the files that
make up your mergebin application.


mergebin.vcproj
    This is the main project file for VC++ projects generated using an Application Wizard. 
    It contains information about the version of Visual C++ that generated the file, and 
    information about the platforms, configurations, and project features selected with the
    Application Wizard.

mergebin.cpp
    This is the main application source file.

/////////////////////////////////////////////////////////////////////////////
Other standard files:

StdAfx.h, StdAfx.cpp
    These files are used to build a precompiled header (PCH) file
    named mergebin.pch and a precompiled types file named StdAfx.obj.

/////////////////////////////////////////////////////////////////////////////
Other notes:

AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.

/////////////////////////////////////////////////////////////////////////////

Added tools/mergebin/StreamTable.cpp.





























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "StdAfx.h"
#include "StreamTable.h"

CREATEINSTANCE g_arTableTypes[64] = {
  CStreamTable::CreateInstance<CModuleTable>,
  CStreamTable::CreateInstance<CTypeRefTable>,
  CStreamTable::CreateInstance<CTypeDefTable>,
  NULL,
};

CStreamTable::CStreamTable(CMetadataTables& tables) : m_tables(tables)
{
}

CStreamTable::~CStreamTable(void)
{
}

template<class C>
static CStreamTable * CALLBACK CStreamTable::CreateInstance(CMetadataTables *ptables)
{
  CStreamTable *p = new C(*ptables);
  p->Init();

  return p;
}

void CStreamTable::Init()
{
  m_pbData = m_tables.m_pbData;
  CStreamTable *p;

  for (UINT n = 0; n < GetType(); n++)
  {
    p = m_tables.GetTable(n);
    if (p)
    {
      m_pbData += (p->GetRowSize() * p->GetRowCount());
    }
  }
}

DWORD CStreamTable::GetRowCount()
{
  return *m_tables.TableRowCount(GetType());
}

UINT CStreamTable::GetRowSize()
{
  TABLE_COLUMN *pc = GetColumns();
  UINT ulen = 0;

  while (pc->uSize)
  {
    ulen += pc->uSize;
    pc ++;
  }

  return ulen;
}

UINT CStreamTable::GetColumnCount()
{
  TABLE_COLUMN *pc = GetColumns();
  UINT ucount = 0;

  while (pc->uSize)
  {
    ucount ++;
    pc ++;
  }
  return ucount;
}

LPBYTE CStreamTable::operator[](UINT uRow)
{
  return m_pbData + (uRow * GetRowSize());
}

Added tools/mergebin/StreamTable.h.





























































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#pragma once
#include "MetaDataTables.h"

typedef enum TableTypes
{
  ttModule = 0,
  ttTypeRef = 1,
  ttTypeDef = 2,
  ttFieldPtr = 3, 
  ttField = 4,
  ttMethodPtr = 5,
  ttMethodDef = 6,
  ttParamPtr = 7, 
  ttParam = 8,
  ttInterfaceImpl = 9,
  ttMemberRef = 10,
  ttConstant = 11, 
  ttCustomAttribute = 12,
  ttFieldMarshal = 13,
  ttPermission = 14,
  ttClassLayout = 15, 
  ttFieldLayout = 16,
  ttStandAloneSig = 17,
  ttEventMap = 18,
  ttEventPtr = 19, 
  ttEvent = 20,
  ttPropertyMap = 21,
  ttPropertyPtr = 22,
  ttProperty = 23, 
  ttMethodSemantics = 24,
  ttMethodImpl = 25,
  ttModuleRef = 26,
  ttTypeSpec = 27, 
  ttImplMap = 28, //lidin book is wrong again here?  It has enclog at 28
  ttFieldRVA = 29,
  ttENCLog = 30,
  ttENCMap = 31, 
  ttAssembly = 32,
  ttAssemblyProcessor= 33,
  ttAssemblyOS = 34,
  ttAssemblyRef = 35, 
  ttAssemblyRefProcessor = 36,
  ttAssemblyRefOS = 37,
  ttFile = 38,
  ttExportedType = 39, 
  ttManifestResource = 40,
  ttNestedClass = 41,
  ttTypeTyPar = 42,
  ttMethodTyPar = 43,
} TableTypes;

#define STRING_INDEXSIZE (m_tables.GetStringIndexSize())
#define GUID_INDEXSIZE (m_tables.GetGuidIndexSize())
#define BLOB_INDEXSIZE (m_tables.GetBlobIndexSize())
#define TABLE_ROWCOUNT(x) (m_tables.TableRowCount(x)[0])
#define TABLE_INDEXSIZE(x) (TABLE_ROWCOUNT(x) > 65535 ? 4 : 2)
#define MAX_INDEXSIZE(x) (m_tables.GetMaxIndexSizeOf(x))

class CStreamTable;

typedef CStreamTable* (CALLBACK* CREATEINSTANCE)(CMetadataTables *);

#define DECLARE_TABLE(classname, typ, nam) \
  public: \
  classname##(CMetadataTables& tables) : CStreamTable(tables) {} \
  UINT GetType() { return typ; } \
  LPCTSTR GetName() { return _T(nam); }

typedef struct TABLE_COLUMN
{
  UINT uSize;
  LPCTSTR pszName;
} TABLE_COLUMNS;

#define BEGIN_COLUMN_MAP() \
  protected: \
  TABLE_COLUMN *GetColumns() \
  { \
    static TABLE_COLUMN map[] = {

#define END_COLUMN_MAP() \
      { 0, NULL } \
    }; \
    return map; \
  }

#define COLUMN_ENTRY(name, size) { size, _T(name) },

class CStreamTable
{
public:
  CStreamTable(CMetadataTables& tables);
  virtual ~CStreamTable(void);

  DWORD GetRowCount();
  LPBYTE operator[](UINT uRow);

  virtual UINT GetType() = 0;
  virtual LPCTSTR GetName() = 0;

  template<class C> static CStreamTable * CALLBACK CreateInstance(CMetadataTables *ptables);

protected:
  CMetadataTables& m_tables;
  LPBYTE m_pbData;

  virtual UINT GetRowSize();
  virtual UINT GetColumnCount();

  virtual TABLE_COLUMN *GetColumns() = 0;

private:
  void Init();
};

class CModuleTable : public CStreamTable
{
  DECLARE_TABLE(CModuleTable, ttModule, "Module")
  
  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Generation", sizeof(WORD))
    COLUMN_ENTRY("Name",       STRING_INDEXSIZE)
    COLUMN_ENTRY("Mvid",       GUID_INDEXSIZE)
    COLUMN_ENTRY("EncId",      GUID_INDEXSIZE)
    COLUMN_ENTRY("EncBaseId",  GUID_INDEXSIZE)
  END_COLUMN_MAP()
};

static UINT ResolutionScopeIndex[] = {ttModule, ttModuleRef, ttAssemblyRef, ttTypeRef, 0};

class CTypeRefTable : public CStreamTable
{
  DECLARE_TABLE(CTypeRefTable, ttTypeRef, "TypeRef")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("ResolutionScope", MAX_INDEXSIZE(ResolutionScopeIndex))
    COLUMN_ENTRY("TypeName", STRING_INDEXSIZE)
    COLUMN_ENTRY("TypeNamespace", STRING_INDEXSIZE)
  END_COLUMN_MAP()
};

static UINT TypeDefOrRefIndex[] = {ttTypeDef, ttTypeRef, ttTypeSpec, 0};

class CTypeDefTable : public CStreamTable
{
  DECLARE_TABLE(CTypeDefTable, ttTypeDef, "TypeDef")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Flags", sizeof(DWORD))
    COLUMN_ENTRY("TypeName", STRING_INDEXSIZE)
    COLUMN_ENTRY("TypeNamespace", STRING_INDEXSIZE)
    COLUMN_ENTRY("Extends", MAX_INDEXSIZE(TypeDefOrRefIndex))
    COLUMN_ENTRY("FieldList", TABLE_INDEXSIZE(ttField))
    COLUMN_ENTRY("MethodList", TABLE_INDEXSIZE(ttMethodDef))
  END_COLUMN_MAP()
};

extern CREATEINSTANCE g_arTableTypes[64];

Added tools/mergebin/TableData.cpp.













































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#include "StdAfx.h"
#include "TableData.h"

CREATEINSTANCE g_arTableTypes[64] = {
  CTableData::CreateInstance<CModuleTable>,
  CTableData::CreateInstance<CTypeRefTable>,
  CTableData::CreateInstance<CTypeDefTable>,
  CTableData::CreateInstance<CFieldPtrTable>,
  CTableData::CreateInstance<CFieldTable>,
  CTableData::CreateInstance<CMethodPtrTable>,
  CTableData::CreateInstance<CMethodTable>,
  CTableData::CreateInstance<CParamPtrTable>,
  CTableData::CreateInstance<CParamTable>,
  CTableData::CreateInstance<CInterfaceImplTable>,
  CTableData::CreateInstance<CMemberRefTable>,
  CTableData::CreateInstance<CConstantTable>,
  CTableData::CreateInstance<CCustomAttributeTable>,
  CTableData::CreateInstance<CFieldMarshalTable>,
  CTableData::CreateInstance<CDeclSecurityTable>,
  CTableData::CreateInstance<CClassLayoutTable>,
  CTableData::CreateInstance<CFieldLayoutTable>,
  CTableData::CreateInstance<CStandAloneSigTable>,
  CTableData::CreateInstance<CEventMapTable>,
  CTableData::CreateInstance<CEventPtrTable>,
  CTableData::CreateInstance<CEventTable>,
  CTableData::CreateInstance<CPropertyMapTable>,
  CTableData::CreateInstance<CPropertyPtrTable>,
  CTableData::CreateInstance<CPropertyTable>,
  CTableData::CreateInstance<CMethodSemanticsTable>,
  CTableData::CreateInstance<CMethodImplTable>,
  CTableData::CreateInstance<CModuleRefTable>,
  CTableData::CreateInstance<CTypeSpecTable>,
  CTableData::CreateInstance<CImplMapTable>,
  CTableData::CreateInstance<CFieldRVATable>,
  NULL,
};

CTableData::CTableData(CMetadataTables& tables) : m_tables(tables)
{
  m_uiRowSize = 0;
}

CTableData::~CTableData(void)
{
  if (m_pColumns) 
    delete[] m_pColumns;
}

template<class C>
static CTableData * CALLBACK CTableData::CreateInstance(CMetadataTables *ptables)
{
  CTableData *p = new C(*ptables);
  p->Init();

  return p;
}

void CTableData::Init()
{
  m_pbData = m_tables.m_pbData;
  CTableData *p;
  UINT n = GetType();
  
  while(n--)
  {
    p = m_tables.GetTable(n);
    if (p)
    {
      m_pbData = p->m_pbData + (p->GetRowSize() * p->GetRowCount());
      break;
    }
  }

  m_pColumns = _CreateColumns();
  TABLE_COLUMNS *tc = m_pColumns + 1;

  while (tc->pszName && !tc->dwOffset)
  {
    tc->dwOffset = tc[-1].dwOffset + tc[-1].uSize;
    tc ++;
  }
}

TABLE_COLUMN * CTableData::GetColumns()
{
  return m_pColumns;
}

DWORD CTableData::GetRowCount()
{
  return *m_tables.TableRowCount(GetType());
}

UINT CTableData::GetRowSize()
{
  if (m_uiRowSize == 0)
  {
    TABLE_COLUMN *pc = m_pColumns;

    while (pc->uSize)
    {
      m_uiRowSize += pc->uSize;
      pc ++;
    }
  }

  return m_uiRowSize;
}

UINT CTableData::GetColumnCount()
{
  TABLE_COLUMN *pc = m_pColumns;
  UINT ucount = 0;

  while (pc->uSize)
  {
    ucount ++;
    pc ++;
  }
  return ucount;
}

int CTableData::GetColumnIndex(LPCTSTR pszName)
{
  TABLE_COLUMN *pc = m_pColumns;
  for (int n = 0; pc[n].pszName; n++)
  {
    if (lstrcmpi(pszName, pc[n].pszName) == 0) return n;
  }
  return -1;
}

UINT CTableData::GetColumnSize(UINT uIndex)
{
  return m_pColumns[uIndex].uSize;
}

UINT CTableData::GetColumnSize(LPCTSTR pszName)
{
  int n = GetColumnIndex(pszName);
  if (n < 0) return 0;

  return GetColumnSize(n);
}

LPBYTE CTableData::Column(UINT uRow, UINT uIndex)
{
  TABLE_COLUMN *pc = m_pColumns;
  LPBYTE pb = m_pbData + (uRow * GetRowSize()) + pc[uIndex].dwOffset;

  return pb;
}

LPBYTE CTableData::Column(UINT uRow, LPCTSTR pszName)
{
  int n = GetColumnIndex(pszName);
  if (n < 0) return NULL;
  return Column(uRow, n);
}

Added tools/mergebin/TableData.h.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#pragma once
#include "MetaDataTables.h"

typedef enum TableTypes
{
  ttModule = 0,
  ttTypeRef = 1,
  ttTypeDef = 2,
  ttFieldPtr = 3, 
  ttField = 4,
  ttMethodPtr = 5,
  ttMethodDef = 6,
  ttParamPtr = 7, 
  ttParam = 8,
  ttInterfaceImpl = 9,
  ttMemberRef = 10,
  ttConstant = 11, 
  ttCustomAttribute = 12,
  ttFieldMarshal = 13,
  ttDeclSecurity = 14,
  ttClassLayout = 15, 
  ttFieldLayout = 16,
  ttStandAloneSig = 17,
  ttEventMap = 18,
  ttEventPtr = 19, 
  ttEvent = 20,
  ttPropertyMap = 21,
  ttPropertyPtr = 22,
  ttProperty = 23, 
  ttMethodSemantics = 24,
  ttMethodImpl = 25,
  ttModuleRef = 26,
  ttTypeSpec = 27, 
  ttImplMap = 28,
  ttFieldRVA = 29,
  ttENCLog = 30,
  ttENCMap = 31, 
  ttAssembly = 32,
  ttAssemblyProcessor= 33,
  ttAssemblyOS = 34,
  ttAssemblyRef = 35, 
  ttAssemblyRefProcessor = 36,
  ttAssemblyRefOS = 37,
  ttFile = 38,
  ttExportedType = 39, 
  ttManifestResource = 40,
  ttNestedClass = 41,
  ttGenericParam = 42,
  ttMethodSpec = 43,
  ttGenericParamConstraint = 44,
} TableTypes;

typedef struct TABLE_COLUMN
{
  UINT uSize;
  LPCTSTR pszName;
  DWORD dwOffset;
} TABLE_COLUMNS;

class CTableData;

/*
** Helpers
*/
#define STRING_INDEXSIZE (m_tables.GetStringIndexSize())
#define GUID_INDEXSIZE (m_tables.GetGuidIndexSize())
#define BLOB_INDEXSIZE (m_tables.GetBlobIndexSize())
#define TABLE_ROWCOUNT(x) (m_tables.TableRowCount(x)[0])
#define TABLE_INDEXSIZE(x) (TABLE_ROWCOUNT(x) > 65535 ? 4 : 2)
#define MAX_INDEXSIZE(x) (m_tables.GetMaxIndexSizeOf(x))

#define DECLARE_TABLE(classname, typ, nam) \
  public: \
  classname##(CMetadataTables& tables) : CTableData(tables) {} \
  UINT GetType() { return typ; } \
  LPCTSTR GetName() { return _T(nam); }

#define BEGIN_COLUMN_MAP() \
  protected: \
  TABLE_COLUMN *_CreateColumns() \
  { \
    TABLE_COLUMN map[] = {

#define END_COLUMN_MAP() \
      { 0, NULL } \
    }; \
    TABLE_COLUMN *p = new TABLE_COLUMN[sizeof(map) / sizeof(TABLE_COLUMN)]; \
    CopyMemory(p, map, sizeof(map)); \
    return p; \
  }

#define COLUMN_ENTRY(name, size) { size, _T(name), 0 },
/*
** End Of Helpers
*/

class CTableData
{
public:
  CTableData(CMetadataTables& tables);
  virtual ~CTableData(void);

  virtual UINT          GetType        () = 0;
  virtual LPCTSTR       GetName        () = 0;
  virtual TABLE_COLUMN *_CreateColumns () = 0;

  template<class C> static CTableData * CALLBACK CreateInstance(CMetadataTables *ptables);

  virtual DWORD         GetRowCount ();
  virtual UINT          GetRowSize  ();

  int           GetColumnIndex (LPCTSTR pszName);
  UINT          GetColumnSize  (UINT uIndex);
  UINT          GetColumnSize  (LPCTSTR pszName);
  UINT          GetColumnCount ();
  LPBYTE        Column         (UINT uRow, UINT uIndex);
  LPBYTE        Column         (UINT uRow, LPCTSTR pszName);
  TABLE_COLUMN *GetColumns     ();

protected:
  CMetadataTables& m_tables;
  LPBYTE           m_pbData;
  UINT             m_uiRowSize;
  TABLE_COLUMN    *m_pColumns;

private:
  void Init ();
};

class CModuleTable : public CTableData
{
  DECLARE_TABLE(CModuleTable, ttModule, "Module")
  
  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Generation", sizeof(WORD))
    COLUMN_ENTRY("Name",       STRING_INDEXSIZE)
    COLUMN_ENTRY("Mvid",       GUID_INDEXSIZE)
    COLUMN_ENTRY("EncId",      GUID_INDEXSIZE)
    COLUMN_ENTRY("EncBaseId",  GUID_INDEXSIZE)
  END_COLUMN_MAP()
};

static UINT TypeDefOrRefIndex[]        = { ttTypeDef,   ttTypeRef,     ttTypeSpec,     0 };
static UINT HasConstantIndex[]         = { ttField,     ttParam,       ttProperty,     0 };
static UINT HasCustomAttributeIndex[]  = { ttMethodDef, ttField,       ttTypeRef,      ttTypeDef,   ttParam,    ttInterfaceImpl, ttMemberRef, ttModule, ttDeclSecurity, ttProperty, ttEvent, ttStandAloneSig, ttModuleRef, ttTypeSpec, ttAssembly, ttAssemblyRef, ttFile, ttExportedType, ttManifestResource, 0 };
static UINT HasFieldMarshalIndex[]     = { ttField,     ttParam,       0 };
static UINT HasDeclSecurityIndex[]     = { ttTypeDef,   ttMethodDef,   ttAssembly,     0 };
static UINT MemberRefParentIndex[]     = { ttTypeDef,   ttTypeRef,     ttModuleRef,    ttMethodDef, ttTypeSpec, 0 };
static UINT HasSemanticsIndex[]        = { ttEvent,     ttProperty,    0 };
static UINT MethodDefOrRefIndex[]      = { ttMethodDef, ttMemberRef,   0 };
static UINT MemberForwardedIndex[]     = { ttField,     ttMethodDef,   0 };
static UINT ImplementationIndex[]      = { ttFile,      ttAssemblyRef, ttExportedType, 0 };
static UINT CustomAttributeTypeIndex[] = { 63,          63,            ttMethodDef,    ttMemberRef, 63,         0 };
static UINT ResolutionScopeIndex[]     = { ttModule,    ttModuleRef,   ttAssemblyRef,  ttTypeRef,   0 };
static UINT TypeOrMethodDefIndex[]     = { ttTypeDef,   ttMethodDef,   0 };

class CTypeRefTable : public CTableData
{
  DECLARE_TABLE(CTypeRefTable, ttTypeRef, "TypeRef")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("ResolutionScope", MAX_INDEXSIZE(ResolutionScopeIndex))
    COLUMN_ENTRY("TypeName",        STRING_INDEXSIZE)
    COLUMN_ENTRY("TypeNamespace",   STRING_INDEXSIZE)
  END_COLUMN_MAP()
};

class CTypeDefTable : public CTableData
{
  DECLARE_TABLE(CTypeDefTable, ttTypeDef, "TypeDef")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Flags",         sizeof(DWORD))
    COLUMN_ENTRY("TypeName",      STRING_INDEXSIZE)
    COLUMN_ENTRY("TypeNamespace", STRING_INDEXSIZE)
    COLUMN_ENTRY("Extends",       MAX_INDEXSIZE(TypeDefOrRefIndex))
    COLUMN_ENTRY("FieldList",     TABLE_INDEXSIZE(ttField))
    COLUMN_ENTRY("MethodList",    TABLE_INDEXSIZE(ttMethodDef))
  END_COLUMN_MAP()
};

class CFieldPtrTable : public CTableData
{
  DECLARE_TABLE(CFieldPtrTable, ttFieldPtr, "FieldPtr")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Field", TABLE_INDEXSIZE(ttField))
  END_COLUMN_MAP()
};

class CFieldTable : public CTableData
{
  DECLARE_TABLE(CFieldTable, ttField, "Field")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Flags",     sizeof(WORD))
    COLUMN_ENTRY("Name",      STRING_INDEXSIZE)
    COLUMN_ENTRY("Signature", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CMethodPtrTable : public CTableData
{
  DECLARE_TABLE(CMethodPtrTable, ttMethodPtr, "MethodPtr")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Method", TABLE_INDEXSIZE(ttMethodDef))
  END_COLUMN_MAP()
};

class CMethodTable : public CTableData
{
  DECLARE_TABLE(CMethodTable, ttMethodDef, "Method")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("RVA",        sizeof(DWORD))
    COLUMN_ENTRY("ImplFlags",  sizeof(WORD))
    COLUMN_ENTRY("Flags",      sizeof(WORD))
    COLUMN_ENTRY("Name",       STRING_INDEXSIZE)
    COLUMN_ENTRY("Signature",  BLOB_INDEXSIZE)
    COLUMN_ENTRY("Parameters", TABLE_INDEXSIZE(ttParam))
  END_COLUMN_MAP()
};

class CParamPtrTable : public CTableData
{
  DECLARE_TABLE(CParamPtrTable, ttParamPtr, "ParamPtr")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Param", TABLE_INDEXSIZE(ttParam))
  END_COLUMN_MAP()
};

class CParamTable : public CTableData
{
  DECLARE_TABLE(CParamTable, ttParam, "Param")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Flags",    sizeof(WORD))
    COLUMN_ENTRY("Sequence", sizeof(WORD))
    COLUMN_ENTRY("Name",     STRING_INDEXSIZE)
  END_COLUMN_MAP()
};

class CInterfaceImplTable : public CTableData
{
  DECLARE_TABLE(CInterfaceImplTable, ttInterfaceImpl, "Interface")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Class",     TABLE_INDEXSIZE(ttTypeDef))
    COLUMN_ENTRY("Interface", MAX_INDEXSIZE(TypeDefOrRefIndex))
  END_COLUMN_MAP()
};

class CMemberRefTable : public CTableData
{
  DECLARE_TABLE(CMemberRefTable, ttMemberRef, "Member")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Class",     MAX_INDEXSIZE(MemberRefParentIndex))
    COLUMN_ENTRY("Name",      STRING_INDEXSIZE)
    COLUMN_ENTRY("Signature", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CConstantTable : public CTableData
{
  DECLARE_TABLE(CConstantTable, ttConstant, "Constant")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Type",   sizeof(WORD))
    COLUMN_ENTRY("Parent", MAX_INDEXSIZE(HasConstantIndex))
    COLUMN_ENTRY("Value",  BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CCustomAttributeTable : public CTableData
{
  DECLARE_TABLE(CCustomAttributeTable, ttCustomAttribute, "CustomAttribute")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Parent", MAX_INDEXSIZE(HasCustomAttributeIndex))
    COLUMN_ENTRY("Type",   MAX_INDEXSIZE(CustomAttributeTypeIndex))
    COLUMN_ENTRY("Value",  BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CFieldMarshalTable : public CTableData
{
  DECLARE_TABLE(CFieldMarshalTable, ttFieldMarshal, "FieldMarshal")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Parent",     MAX_INDEXSIZE(HasFieldMarshalIndex))
    COLUMN_ENTRY("NativeType", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CDeclSecurityTable : public CTableData
{
  DECLARE_TABLE(CDeclSecurityTable, ttDeclSecurity, "DeclSecurity")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Action",        sizeof(WORD))
    COLUMN_ENTRY("Parent",        MAX_INDEXSIZE(HasDeclSecurityIndex))
    COLUMN_ENTRY("PermissionSet", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CClassLayoutTable : public CTableData
{
  DECLARE_TABLE(CClassLayoutTable, ttClassLayout, "ClassLayout")
  
  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("PackingSize", sizeof(WORD))
    COLUMN_ENTRY("ClassSize",   sizeof(DWORD))
    COLUMN_ENTRY("Parent",      TABLE_INDEXSIZE(ttTypeDef))
  END_COLUMN_MAP()
};

class CFieldLayoutTable : public CTableData
{
  DECLARE_TABLE(CFieldLayoutTable, ttFieldLayout, "FieldLayout")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Offset", sizeof(DWORD))
    COLUMN_ENTRY("Field",  TABLE_INDEXSIZE(ttField))
  END_COLUMN_MAP()
};

class CStandAloneSigTable : public CTableData
{
  DECLARE_TABLE(CStandAloneSigTable, ttStandAloneSig, "StandAloneSig")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Signature", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CEventMapTable : public CTableData
{
  DECLARE_TABLE(CEventMapTable, ttEventMap, "EventMap")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Parent",    TABLE_INDEXSIZE(ttTypeDef))
    COLUMN_ENTRY("EventList", TABLE_INDEXSIZE(ttEvent))
  END_COLUMN_MAP()
};

class CEventTable : public CTableData
{
  DECLARE_TABLE(CEventTable, ttEvent, "Event")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("EventFlags", sizeof(WORD))
    COLUMN_ENTRY("Name",       STRING_INDEXSIZE)
    COLUMN_ENTRY("EventType",  MAX_INDEXSIZE(TypeDefOrRefIndex))
  END_COLUMN_MAP()
};

class CEventPtrTable : public CTableData
{
  DECLARE_TABLE(CEventPtrTable, ttEventPtr, "EventPtr")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Event", TABLE_INDEXSIZE(ttEvent))
  END_COLUMN_MAP()
};

class CPropertyMapTable : public CTableData
{
  DECLARE_TABLE(CPropertyMapTable, ttPropertyMap, "PropertyMap")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Parent",       TABLE_INDEXSIZE(ttTypeDef))
    COLUMN_ENTRY("PropertyList", TABLE_INDEXSIZE(ttProperty))
  END_COLUMN_MAP()
};

class CPropertyPtrTable : public CTableData
{
  DECLARE_TABLE(CPropertyPtrTable, ttEventPtr, "PropertyPtr")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Property", TABLE_INDEXSIZE(ttProperty))
  END_COLUMN_MAP()
};

class CPropertyTable : public CTableData
{
  DECLARE_TABLE(CPropertyTable, ttProperty, "Property")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Flags", sizeof(WORD))
    COLUMN_ENTRY("Name",  STRING_INDEXSIZE)
    COLUMN_ENTRY("Type",  BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CMethodSemanticsTable : public CTableData
{
  DECLARE_TABLE(CMethodSemanticsTable, ttMethodSemantics, "MethodSemantics")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Semantics",   sizeof(WORD))
    COLUMN_ENTRY("Method",      TABLE_INDEXSIZE(ttMethodDef))
    COLUMN_ENTRY("Association", MAX_INDEXSIZE(HasSemanticsIndex))
  END_COLUMN_MAP()
};

class CMethodImplTable : public CTableData
{
  DECLARE_TABLE(CMethodImplTable, ttMethodImpl, "MethodImpl")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Class",             TABLE_INDEXSIZE(ttTypeDef))
    COLUMN_ENTRY("MethodBody",        MAX_INDEXSIZE(MethodDefOrRefIndex))
    COLUMN_ENTRY("MethodDeclaration", MAX_INDEXSIZE(MethodDefOrRefIndex))
  END_COLUMN_MAP()
};

class CModuleRefTable : public CTableData
{
  DECLARE_TABLE(CModuleRefTable, ttModuleRef, "ModuleRef")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Name", STRING_INDEXSIZE)
  END_COLUMN_MAP()
};

class CTypeSpecTable : public CTableData
{
  DECLARE_TABLE(CTypeSpecTable, ttTypeSpec, "TypeSpec")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("Signature", BLOB_INDEXSIZE)
  END_COLUMN_MAP()
};

class CImplMapTable : public CTableData
{
  DECLARE_TABLE(CImplMapTable, ttImplMap, "ImplMap")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("MappingFlags",    sizeof(WORD))
    COLUMN_ENTRY("MemberForwarded", MAX_INDEXSIZE(MemberForwardedIndex))
    COLUMN_ENTRY("ImportName",      STRING_INDEXSIZE)
    COLUMN_ENTRY("ImportScope",     TABLE_INDEXSIZE(ttModuleRef))
  END_COLUMN_MAP()
};

class CFieldRVATable : public CTableData
{
  DECLARE_TABLE(CFieldRVATable, ttFieldRVA, "FieldRVA")

  BEGIN_COLUMN_MAP()
    COLUMN_ENTRY("RVA",   sizeof(DWORD))
    COLUMN_ENTRY("Field", TABLE_INDEXSIZE(ttField))
  END_COLUMN_MAP()
};

// Only tables up to ttFieldRVA are mapped, because they're all I needed.  If you need the tables beyond that, map them yourself!

typedef CTableData* (CALLBACK* CREATEINSTANCE)(CMetadataTables *);
extern CREATEINSTANCE g_arTableTypes[64];

Added tools/mergebin/mergebin.cpp.



























































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/********************************************************
 * mergebin
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

#include "stdafx.h"
#include "MetaData.h"
#include "MetaDataTables.h"
#include "TableData.h"

void DumpCLRInfo(LPCTSTR pszFile);
void MergeModules(LPCTSTR pszAssembly, LPCTSTR pszNative, LPCTSTR pszSection);
void DumpCLRPragma(LPCTSTR pszAssembly, LPCTSTR pszSection);

int _tmain(int argc, _TCHAR* argv[])
{
  if (argc == 1)
  {
    _tprintf(_T(
"MERGEBIN - Merges a pure .NET assembly with a native DLL\n \
Syntax: MERGEBIN [/I:assembly] [/S:sectionname assembly nativedll]\n \
/I:assembly            Returns the number of bytes required\n \
                       to consume the assembly\n \
/S:sectionname         The name of the section in the nativedll\n \
                       to insert the CLR data\n \
/P:assembly            Outputs the C++ pragma code that can be used\n \
                       as additional input to a C++ app to reserve\n \
                       a section block large enough for the managed code.\n \
\n \
The native DLL must have an unused section in it, into which the\n \
.NET assembly will be inserted.  You can do this with the following code:\n \
  #pragma data_seg(\".clr\")\n \
  #pragma comment(linker, \"/SECTION:.clr,ER\")\n \
   char __ph[92316] = {0}; // 92316 is the number of bytes to reserve\n \
  #pragma data_seg()\n \
You would then specify /SECTION:.CLR in the command-line for the location to\n \
insert the .NET assembly.  The number of bytes reserved in the section needs\n \
to be equal to or more than the number of bytes returned by the /I parameter.\n \
\n \
The native DLL must also export a function that calls _CorDllMain in \n \
MSCOREE.DLL.  This function must have the same parameters and calling\n \
conventions as DllMain, and its name must have the word \"CORDLLMAIN\"\n \
in it.\n \
"));
    return 0;
  }

  LPTSTR pszAssembly = NULL;
  LPTSTR pszNative = NULL;
  LPTSTR pszSection = NULL;
  BOOL bDoPragma = FALSE;

  for (int n = 1; n < argc; n++)
  {
    if (argv[n][0] != '-' && argv[n][0] != '/')
    {
      if (pszAssembly == NULL)
        pszAssembly = argv[n];
      else if (pszNative == NULL)
        pszNative = argv[n];
      else
      {
        _tprintf(_T("Too many files specified\n"));
        return 0;
      }
      continue;
    }

    switch(argv[n][1])
    {
    case 'I':
    case 'i':
      pszAssembly = &argv[n][3];
      if (argv[n][2] != ':' || lstrlen(pszAssembly) == 0)
      {
        _tprintf(_T("/I requires an assembly name\n"));
        return 0;
      }
      DumpCLRInfo(pszAssembly);
      return 0;
      break;
    case 'P':
    case 'p':
      pszAssembly = &argv[n][3];
      if (argv[n][2] != ':' || lstrlen(pszAssembly) == 0)
      {
        _tprintf(_T("/P requires an assembly name\n"));
        return 0;
      }
      bDoPragma = TRUE;
      break;
    case 'S':
    case 's':
      pszSection = &argv[n][3];
      if (argv[n][2] != ':' || lstrlen(pszSection) == 0)
      {
        _tprintf(_T("/S requires a section name\n"));
        return 0;
      }
      break;
    }
  }

  if (pszAssembly && pszNative && pszSection && !bDoPragma)
    MergeModules(pszAssembly, pszNative, pszSection);

  if (pszAssembly && bDoPragma)
    DumpCLRPragma(pszAssembly, pszSection);

  return 0;
}

BOOL GetMinMaxCOR20RVA(CPEFile& file, DWORD& dwMin, DWORD& dwMax)
{
  PIMAGE_COR20_HEADER pCor = file;
  dwMin = MAXDWORD;
  dwMax = 0;

  if (!pCor) return FALSE;

  if (pCor->MetaData.Size) dwMin = min(dwMin, pCor->MetaData.VirtualAddress);
  if (pCor->Resources.Size) dwMin = min(dwMin, pCor->Resources.VirtualAddress);
  if (pCor->StrongNameSignature.Size) dwMin = min(dwMin, pCor->StrongNameSignature.VirtualAddress);
  if (pCor->CodeManagerTable.Size) dwMin = min(dwMin, pCor->CodeManagerTable.VirtualAddress);
  if (pCor->VTableFixups.Size) dwMin = min(dwMin, pCor->VTableFixups.VirtualAddress);
  if (pCor->ExportAddressTableJumps.Size) dwMin = min(dwMin, pCor->ExportAddressTableJumps.VirtualAddress);
  if (pCor->ManagedNativeHeader.Size) dwMin = min(dwMin, pCor->ManagedNativeHeader.VirtualAddress);

  dwMax = max(dwMax, (pCor->MetaData.VirtualAddress + pCor->MetaData.Size));
  dwMax = max(dwMax, (pCor->Resources.VirtualAddress + pCor->Resources.Size));
  dwMax = max(dwMax, (pCor->StrongNameSignature.VirtualAddress + pCor->StrongNameSignature.Size));
  dwMax = max(dwMax, (pCor->CodeManagerTable.VirtualAddress + pCor->CodeManagerTable.Size));
  dwMax = max(dwMax, (pCor->VTableFixups.VirtualAddress + pCor->VTableFixups.Size));
  dwMax = max(dwMax, (pCor->ExportAddressTableJumps.VirtualAddress + pCor->ExportAddressTableJumps.Size));
  dwMax = max(dwMax, (pCor->ManagedNativeHeader.VirtualAddress + pCor->ManagedNativeHeader.Size));

  CMetadata meta(file);
  CMetadataTables tables(meta);
  CTableData *p;
  DWORD *pdwRVA;
  DWORD dwRows;

  for (int n = 0; n < 2; n++)
  {
    p = tables.GetTable((n == 0) ? ttMethodDef : ttFieldRVA);
    if (p)
    {
      dwRows = p->GetRowCount();
      for (UINT uRow = 0; uRow < dwRows; uRow ++)
      {
        pdwRVA = (DWORD *)p->Column(uRow, (UINT)0);
        if (*pdwRVA)
          dwMin = min(dwMin, (*pdwRVA));
      }
    }
  }
  return TRUE;
}

void DumpCLRInfo(LPCTSTR pszFile)
{
  CPEFile peFile;
  HRESULT hr;
  hr = peFile.Open(pszFile);
  if (FAILED(hr)) return;

  DWORD dwMinRVA;
  DWORD dwMaxRVA;

  if (!GetMinMaxCOR20RVA(peFile, dwMinRVA, dwMaxRVA))
  {
    _tprintf(_T("Unable to retrieve .NET assembly information for file %s\n"), pszFile);
    return;
  }

  _tprintf(_T("%d Bytes required to merge %s\n"), (dwMaxRVA - dwMinRVA) + ((PIMAGE_COR20_HEADER)peFile)->cb, pszFile);
}

void DumpCLRPragma(LPCTSTR pszAssembly, LPCTSTR pszSection)
{
  CPEFile peFile;
  HRESULT hr;
  DWORD dwMinRVA;
  DWORD dwMaxRVA;

  hr = peFile.Open(pszAssembly);
  if (FAILED(hr)) return;
  
  if (pszSection == NULL) pszSection = _T(".clr");

  if (!GetMinMaxCOR20RVA(peFile, dwMinRVA, dwMaxRVA))
  {
    _tprintf(_T("// Unable to retrieve .NET assembly information for file %s\n"), pszAssembly);
    return;
  }

  _tprintf(_T("// This code was automatically generated from assembly\n\
// %s\n\n\
#include <windef.h>\n\n\
#pragma data_seg(\"%s\")\n\
#pragma comment(linker, \"/SECTION:%s,ER\")\n\
  char __ph[%d] = {0}; // The number of bytes to reserve\n\
#pragma data_seg()\n\n\
#pragma comment(lib, \"mscoree\")\n\n\
extern BOOL WINAPI _CorDllMain(HANDLE, DWORD, LPVOID);\n\
__declspec(dllexport) BOOL WINAPI _CorDllMainStub(HANDLE hModule, DWORD dwReason, LPVOID pvReserved)\n\
{\n\
  return _CorDllMain(hModule, dwReason, pvReserved);\n\
}\n\
"), pszAssembly, pszSection, pszSection, (dwMaxRVA - dwMinRVA) + ((PIMAGE_COR20_HEADER)peFile)->cb);
}

/*   When merged, the native DLL's entrypoint must go to _CorDllMain in MSCOREE.DLL.
  ** In order to do this, we need to change the DLL's entrypoint to "something" that will
  ** call CorDllMain.  Since its too much hassle to add imports to the DLL and make drastic
  ** changes to it, we rely on the native DLL to export a function that we can call which will
  ** forward to CorDllMain.  Exported functions are easy to identify and get an RVA for.
  ** The exported function must have the same calling conventions and parameters as DllMain,
  ** and must contain the letters "CORDLLMAIN" in the name.  The search is case-insensitive. */
DWORD GetExportedCorDllMainRVA(CPEFile& file)
{
  PIMAGE_EXPORT_DIRECTORY pExportDir;
  PIMAGE_SECTION_HEADER header;
  INT delta; 
  DWORD i;
  DWORD *pdwFunctions;
  PWORD pwOrdinals;
  DWORD *pszFuncNames;
  DWORD exportsStartRVA;
  DWORD exportsEndRVA;
  CHAR szName[MAX_PATH + 1];
  PIMAGE_NT_HEADERS pNT = file;

  exportsStartRVA = pNT->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
  exportsEndRVA = exportsStartRVA + pNT->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;

  header = file.GetEnclosingSectionHeader(exportsStartRVA);
  if (!header)
    return 0;

  delta = (INT)(header->VirtualAddress - header->PointerToRawData);

  pExportDir   =  (PIMAGE_EXPORT_DIRECTORY)file.GetPtrFromRVA(exportsStartRVA);
  pdwFunctions =	(PDWORD)file.GetPtrFromRVA(pExportDir->AddressOfFunctions);
  pwOrdinals   =	(PWORD)file.GetPtrFromRVA(pExportDir->AddressOfNameOrdinals);
  pszFuncNames =	(DWORD *)file.GetPtrFromRVA(pExportDir->AddressOfNames);

  for (i = 0; i < pExportDir->NumberOfFunctions; i++, pdwFunctions++)
  {
    DWORD entryPointRVA = *pdwFunctions;

    if ( entryPointRVA == 0 )
      continue;

    for (UINT j = 0; j < pExportDir->NumberOfNames; j++)
    {
      if (pwOrdinals[j] == i)
      {
        lstrcpynA(szName, (LPSTR)file.GetPtrFromRVA(pszFuncNames[j]), MAX_PATH);
        szName[MAX_PATH] = 0;
        CharUpper(szName);
        if (strstr(szName, "CORDLLMAIN") != 0) return entryPointRVA;
      }
    }
  }
  return 0;
}

// Merges a pure .NET assembly with a native DLL, inserting it into the specified section
void MergeModules(LPCTSTR pszAssembly, LPCTSTR pszNative, LPCTSTR pszSection)
{
  CPEFile peFile;
  CPEFile peDest;
  HRESULT hr;
  DWORD dwMinRVA;
  DWORD dwMaxRVA;
  DWORD dwDestRVA;
  PIMAGE_SECTION_HEADER pSection;
  LPBYTE pSrc;
  LPBYTE pDest;
  DWORD dwSize;
  DWORD dwNewEntrypoint;
  PIMAGE_COR20_HEADER pCor;
  PIMAGE_NT_HEADERS pNT;
  int diffRVA;
  CTableData *p;
  DWORD *pdwRVA;
  DWORD dwRows;

  // Open the .NET assembly
  hr = peFile.Open(pszAssembly);
  if (FAILED(hr)) return;

  // Scan the .NET assembly and find the block of .NET code specified in the .NET metadata
  if (!GetMinMaxCOR20RVA(peFile, dwMinRVA, dwMaxRVA))
  {
    _tprintf(_T("Unable to retrieve .NET assembly information for file %s\n"), pszAssembly);
    return;
  }
  // Total number of bytes of the block of .NET code we're going to merge
  dwSize = (dwMaxRVA - dwMinRVA) + ((PIMAGE_COR20_HEADER)peFile)->cb;

  // Open the destination file for readwrite access
  hr = peDest.Open(pszNative, FALSE);
  if (FAILED(hr)) return;

  // Make sure it has the section specified in the command-line
  pSection = peDest.GetSectionHeader(pszSection);
  if (!pSection)
  {
    _tprintf(_T("Unable to find section %s in file\n"), pszSection);
    return;
  }

  // If the section isn't large enough, tell the user how large it needs to be
  if (pSection->Misc.VirtualSize < dwSize)
  {
    _tprintf(_T("Not enough room in section for data.  Need %d bytes\n"), dwSize);
    return;
  }

  /*
  ** Find a new entrypoint to use for the DLL.  The old entrypoint is written into the .NET header
  */
  dwNewEntrypoint = GetExportedCorDllMainRVA(peDest);
  if (!dwNewEntrypoint)
  {
    _tprintf(_T("Native DLL must export a function that calls _CorDllMain, and its name must contain the word \"CorDllMain\".\n"));
    return;
  }

  // Change this section's flags
  pSection->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ;
  dwDestRVA = pSection->VirtualAddress;

  // If the native DLL has been merged with an assembly beforehand, we need to strip the .NET stuff and restore the entrypoint
  pCor = peDest;
  if (pCor)
  {
    if (pCor->Flags & 0x10)
    {
      pNT = peDest;
      pNT->OptionalHeader.AddressOfEntryPoint = pCor->EntryPointToken;
    }
  }

  // Copy the assembly's .NET header into the section
  dwSize = ((PIMAGE_COR20_HEADER)peFile)->cb;
  pSrc = (LPBYTE)(PIMAGE_COR20_HEADER)peFile;
  pDest = (LPBYTE)peDest.GetPtrFromRVA(dwDestRVA);
  CopyMemory(pDest, pSrc, dwSize);

  // Fixup the NT header on the native DLL to include the new .NET header
  ((PIMAGE_NT_HEADERS)peDest)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = pSection->VirtualAddress;
  ((PIMAGE_NT_HEADERS)peDest)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = dwSize;
  dwDestRVA += dwSize;
  if (dwDestRVA % 4) dwDestRVA += (4 - (dwDestRVA % 4));

  // Copy the .NET block of code and metadata into the section, after the header
  dwSize = dwMaxRVA - dwMinRVA;
  pSrc = (LPBYTE)peFile.GetPtrFromRVA(dwMinRVA);
  pDest = (LPBYTE)peDest.GetPtrFromRVA(dwDestRVA);
  CopyMemory(pDest, pSrc, dwSize);

  // Figure out by how much we need to change the RVA's to compensate for the relocation
  diffRVA = dwDestRVA - dwMinRVA;
  pNT = peDest;
  pCor = peDest;

  // Fixup the DLL entrypoints
  if (pNT->OptionalHeader.AddressOfEntryPoint != dwNewEntrypoint)
  {
    pCor->EntryPointToken = pNT->OptionalHeader.AddressOfEntryPoint;
    pNT->OptionalHeader.AddressOfEntryPoint = dwNewEntrypoint;
  }
  // Adjust the .NET headers to indicate we're a mixed DLL
  pCor->Flags = (pCor->Flags & 0xFFFE) | 0x10;

  // Fixup the metadata header RVA's
  if (pCor->MetaData.VirtualAddress) pCor->MetaData.VirtualAddress += diffRVA;
  if (pCor->Resources.VirtualAddress) pCor->Resources.VirtualAddress += diffRVA;
  if (pCor->StrongNameSignature.VirtualAddress) pCor->StrongNameSignature.VirtualAddress += diffRVA;
  if (pCor->CodeManagerTable.VirtualAddress) pCor->CodeManagerTable.VirtualAddress += diffRVA;
  if (pCor->VTableFixups.VirtualAddress) pCor->VTableFixups.VirtualAddress += diffRVA;
  if (pCor->ExportAddressTableJumps.VirtualAddress) pCor->ExportAddressTableJumps.VirtualAddress += diffRVA;
  if (pCor->ManagedNativeHeader.VirtualAddress) pCor->ManagedNativeHeader.VirtualAddress += diffRVA;

  CMetadata meta(peDest);
  CMetadataTables tables(meta);

  // Fixup all the RVA's for methods and fields that have them in the .NET code
  for (int n = 0; n < 2; n++)
  {
    p = tables.GetTable((n == 0) ? ttMethodDef : ttFieldRVA);
    if (p)
    {
      dwRows = p->GetRowCount();
      for (UINT uRow = 0; uRow < dwRows; uRow ++)
      {
        pdwRVA = (DWORD *)p->Column(uRow, (UINT)0);
        if (*pdwRVA)
          *pdwRVA = (*pdwRVA) + diffRVA;
      }
    }
  }

  if (pCor->Flags & 0x08)
    _tprintf(_T("WARNING: %s must be re-signed before it can be used!\n"), pszNative);

  _tprintf(_T("Success!\n"));
}

Added tools/mergebin/mergebin.sln.









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mergebin", "mergebin.vcproj", "{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Win32 = Debug|Win32
		Release|Win32 = Release|Win32
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}.Debug|Win32.ActiveCfg = Debug|Win32
		{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}.Debug|Win32.Build.0 = Debug|Win32
		{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}.Release|Win32.ActiveCfg = Release|Win32
		{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}.Release|Win32.Build.0 = Release|Win32
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal

Added tools/mergebin/mergebin.vcproj.

















































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
	ProjectType="Visual C++"
	Version="8.00"
	Name="mergebin"
	ProjectGUID="{F9D4C5F6-85FE-4E1A-BCB5-70FB8772FAFB}"
	RootNamespace="mergebin"
	Keyword="Win32Proj"
	>
	<Platforms>
		<Platform
			Name="Win32"
		/>
	</Platforms>
	<ToolFiles>
	</ToolFiles>
	<Configurations>
		<Configuration
			Name="Debug|Win32"
			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			CharacterSet="2"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
				MinimalRebuild="true"
				BasicRuntimeChecks="3"
				RuntimeLibrary="3"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
				DebugInformationFormat="4"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				OutputFile="$(ProjectName).exe"
				LinkIncremental="2"
				GenerateDebugInformation="true"
				SubSystem="1"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
		<Configuration
			Name="Release|Win32"
			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			CharacterSet="2"
			WholeProgramOptimization="0"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="1"
				FavorSizeOrSpeed="2"
				WholeProgramOptimization="false"
				PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
				StringPooling="true"
				ExceptionHandling="0"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="2"
				WarningLevel="3"
				Detect64BitPortabilityProblems="true"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				OutputFile="$(ProjectName).exe"
				LinkIncremental="1"
				GenerateManifest="false"
				GenerateDebugInformation="true"
				SubSystem="1"
				OptimizeReferences="2"
				EnableCOMDATFolding="2"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCWebDeploymentTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
	</Configurations>
	<References>
	</References>
	<Files>
		<Filter
			Name="Source Files"
			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
			>
			<File
				RelativePath=".\mergebin.cpp"
				>
			</File>
			<File
				RelativePath=".\MetaData.cpp"
				>
			</File>
			<File
				RelativePath=".\MetaDataTables.cpp"
				>
			</File>
			<File
				RelativePath=".\PEFile.cpp"
				>
			</File>
			<File
				RelativePath=".\stdafx.cpp"
				>
				<FileConfiguration
					Name="Debug|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
				<FileConfiguration
					Name="Release|Win32"
					>
					<Tool
						Name="VCCLCompilerTool"
						UsePrecompiledHeader="1"
					/>
				</FileConfiguration>
			</File>
			<File
				RelativePath=".\TableData.cpp"
				>
			</File>
		</Filter>
		<Filter
			Name="Header Files"
			Filter="h;hpp;hxx;hm;inl;inc;xsd"
			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
			>
			<File
				RelativePath=".\MetaData.h"
				>
			</File>
			<File
				RelativePath=".\MetaDataTables.h"
				>
			</File>
			<File
				RelativePath=".\PEFile.h"
				>
			</File>
			<File
				RelativePath=".\stdafx.h"
				>
			</File>
			<File
				RelativePath=".\TableData.h"
				>
			</File>
		</Filter>
		<Filter
			Name="Resource Files"
			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
			UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
			>
		</Filter>
		<File
			RelativePath=".\ReadMe.txt"
			>
		</File>
	</Files>
	<Globals>
	</Globals>
</VisualStudioProject>

Added tools/mergebin/stdafx.cpp.

















>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
// stdafx.cpp : source file that includes just the standard includes
// mergebin.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

Added tools/mergebin/stdafx.h.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once


#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
#define _WIN32_WINNT 0x0400

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here