source: dev/trunk/abdev/BasicCompiler64/MakePeHdr.cpp @ 318

Last change on this file since 318 was 318, checked in by dai_9181, 16 years ago

64bit版でコンパイルできるようにした。

File size: 54.0 KB
Line 
1#include "stdafx.h"
2
3#include <jenga/include/common/Environment.h>
4#include <jenga/include/common/Path.h>
5#include <jenga/include/common/Directory.h>
6
7#include <jenga/include/smoothie/Smoothie.h>
8
9#include <Class.h>
10#include <Compiler.h>
11
12#include <../Enum.h>
13
14#include "../BasicCompiler_Common/common.h"
15#include "../BasicCompiler_Common/DebugSection.h"
16#include "Opcode.h"
17
18
19////////////////////////////
20// 特殊関数の構造体ポインタ
21////////////////////////////
22
23// グローバル関数、静的メソッド
24const UserProc
25    *pSub_System_StartupProgram,
26    *pSub_System_GlobalArea,
27    *pSub_DebugSys_StartProc,
28    *pSub_DebugSys_EndProc,
29    *pSub_DebugSys_SaveContext,
30    *pSub_System_GetEip,
31    *pSub_System_InitDllGlobalVariables,
32    *pSub_System_InitStaticLocalVariables,
33    *pSub_System_Call_Destructor_of_GlobalObject,
34    *pSub_System_End,
35    *pSub_System_GetSp,
36    *pSub_pow,
37    *pSub_calloc,
38    *pSub_realloc,
39    *pSub_free,
40    *pSub_System_GC_malloc_ForObject,
41    *pSub_System_GC_malloc_ForObjectPtr,
42    *pSub_System_GC_free_for_SweepingDelete,
43    *pSubStaticMethod_System_TypeBase_InitializeUserTypes;
44
45// 動的メソッド
46const UserProc
47    *pUserProc_System_CGarbageCollection_RegisterGlobalRoots;
48
49
50//////////////////////////////
51// 各セクションの位置とサイズ
52int FileSize_CodeSection,
53    FileSize_ExportSection,
54    FileSize_ImportSection,
55    FileSize_DataSection,
56    FileSize_RWSection,
57    FileSize_RSrcSection,
58    FileSize_RelocSection,
59    FileSize_DebugSection;
60int FilePos_CodeSection,
61    FilePos_ExportSection,
62    FilePos_ImportSection,
63    FilePos_DataSection,
64    FilePos_RWSection,
65    FilePos_RSrcSection,
66    FilePos_RelocSection,
67    FilePos_DebugSection;
68int MemSize_CodeSection,
69    MemSize_ExportSection,
70    MemSize_ImportSection,
71    MemSize_DataSection,
72    MemSize_RWSection,
73    MemSize_RSrcSection,
74    MemSize_RelocSection,
75    MemSize_DebugSection;
76int MemPos_CodeSection,
77    MemPos_ExportSection,
78    MemPos_ImportSection,
79    MemPos_DataSection,
80    MemPos_RWSection,
81    MemPos_RSrcSection,
82    MemPos_RelocSection,
83    MemPos_DebugSection;
84int bUse_CodeSection,
85    bUse_ExportSection,
86    bUse_ImportSection,
87    bUse_DataSection,
88    bUse_RWSection,
89    bUse_RSrcSection,
90    bUse_RelocSection,
91    bUse_DebugSection;
92
93
94void Compile(void){
95    extern HWND hMainDlg;
96    extern HWND hOwnerEditor;
97    extern HANDLE hHeap;
98    extern BOOL bDebugCompile;
99    extern DWORD ImageBase;
100    extern int obp_AllocSize;
101    extern char *basbuf;
102    extern char OutputFileName[MAX_PATH];
103    int i,i2,i3,i4,i5;
104    char temporary[MAX_PATH],*temp2;
105    HANDLE hFile;
106
107
108    //コードセクションのメモリ上の位置
109    MemPos_CodeSection=     0x1000;
110
111    //データセクションのメモリ上の位置(仮定)
112    MemPos_DataSection=     0x10000000;
113
114
115    //エクスポート セクションを利用するかどうか
116    if( compiler.IsDll() ) bUse_ExportSection=1;
117    else bUse_ExportSection=0;
118
119
120    // 静的リンク
121    compiler.StaticLink( compiler.staticLibraries );
122
123
124    //////////////////
125    // データテーブル
126    if(bDebugCompile){
127        compiler.GetObjectModule().dataTable.Add( (long)0x00000002 );
128    }
129
130
131    //////////////////////
132    // コード生成前の準備
133    //////////////////////
134
135    //重複エラー情報管理のメモリを確保(グローバル領域コンパイル用)
136    extern char **SynonymErrorWords;
137    extern int SynonymErrorNum;
138    SynonymErrorNum=0;
139    SynonymErrorWords=(char **)HeapAlloc(hHeap,0,1);
140
141    //列挙体に関する情報の初期化
142    CEnumParent::InitEnum();
143
144    //列挙体からクラスコードを生成
145    char *temp;
146    temp=CEnumParent::GenerateCodes();
147    AddSourceCode(temp);
148    HeapDefaultFree(temp);
149
150    // 名前空間情報を取得
151    NamespaceSupporter::CollectNamespaces(
152        compiler.GetObjectModule().GetCurrentSource().GetBuffer(),
153        compiler.GetObjectModule().meta.GetNamespaces()
154    );
155
156    //クラス名を取得(詳細情報はGetAllClassInfoで取得)
157    //   CollectProcedures関数の中で参照されるオブジェクト名を事前に取得する。
158    //     ※オブジェクトの内容までは取得しない
159    compiler.GetObjectModule().meta.GetClasses().CollectClassesForNameOnly( compiler.GetObjectModule().GetCurrentSource() );
160
161    //TypeDef情報を初期化
162    compiler.GetObjectModule().meta.GetTypeDefs().CollectTypeDefs();
163
164    //定数情報を取得
165    GetConstInfo();
166
167    //サブルーチン(ユーザー定義、DLL関数)の識別子、アドレスを取得
168    compiler.pCompilingClass = NULL;
169    CollectProcedures(
170        compiler.GetObjectModule().GetCurrentSource(),
171        compiler.GetObjectModule().meta.GetUserProcs(),
172        compiler.GetObjectModule().meta.GetDllProcs()
173    );
174
175    // クラス情報を取得(※注 - CollectProceduresの後に呼び出す)
176    compiler.GetObjectModule().meta.GetClasses().GetAllClassInfo();
177
178    // サブルーチン(ユーザー定義、DLL関数)のイテレータの準備
179    compiler.GetObjectModule().meta.GetUserProcs().Iterator_Init();
180    compiler.GetObjectModule().meta.GetDllProcs().Iterator_Init();
181
182
183    //コードと行番号の関係
184    extern SourceLines oldSourceLines;
185    oldSourceLines.clear();
186
187
188    ///////////////////////////
189    // 最低限必要な関数を取得
190    ///////////////////////////
191    cp=-1;
192
193    if(pSub_System_StartupProgram=GetSubHash("_System_StartupProgram",1))
194        pSub_System_StartupProgram->Using();
195
196    if(pSub_System_GlobalArea=GetSubHash(compiler.globalAreaProcName.c_str(),1))
197    {
198        pSub_System_GlobalArea->Using();
199        pSub_System_GlobalArea->ThisIsAutoGenerationProc();
200    }
201
202    if(pSub_DebugSys_StartProc=GetSubHash("_DebugSys_StartProc",1))
203        pSub_DebugSys_StartProc->Using();
204
205    if(pSub_DebugSys_EndProc=GetSubHash("_DebugSys_EndProc",1))
206        pSub_DebugSys_EndProc->Using();
207
208    if(pSub_DebugSys_SaveContext=GetSubHash("_DebugSys_SaveContext",1))
209        pSub_DebugSys_SaveContext->Using();
210
211    if(pSub_System_GetEip=GetSubHash("_System_GetEip",1)){
212        pSub_System_GetEip->Using();
213        pSub_System_GetEip->ThisIsSystemProc();
214    }
215
216    if(pSub_System_InitDllGlobalVariables=GetSubHash("_System_InitDllGlobalVariables",1)){
217        pSub_System_InitDllGlobalVariables->Using();
218        pSub_System_InitDllGlobalVariables->ThisIsSystemProc();
219    }
220
221    if(pSub_System_InitStaticLocalVariables=GetSubHash("_System_InitStaticLocalVariables",1)){
222        pSub_System_InitStaticLocalVariables->Using();
223        pSub_System_InitStaticLocalVariables->ThisIsSystemProc();
224    }
225
226    if(pSub_System_Call_Destructor_of_GlobalObject=GetSubHash("_System_Call_Destructor_of_GlobalObject",1)){
227        pSub_System_Call_Destructor_of_GlobalObject->Using();
228        pSub_System_Call_Destructor_of_GlobalObject->ThisIsSystemProc();
229    }
230
231    if(pSub_System_End=GetSubHash("_System_End",1)){
232        pSub_System_End->Using();
233    }
234
235    if(pSub_System_GetSp=GetSubHash("_System_GetSp",1)){
236        pSub_System_GetSp->Using();
237        pSub_System_GetSp->ThisIsSystemProc();
238    }
239
240    if(pSub_pow=GetSubHash("pow",1))
241        pSub_pow->Using();
242
243    if(pSub_calloc=GetSubHash("calloc",1))
244        pSub_calloc->Using();
245
246    if(pSub_realloc=GetSubHash("realloc",1))
247        pSub_realloc->Using();
248
249    if(pSub_free=GetSubHash("free",1))
250        pSub_free->Using();
251
252    if( pSub_System_GC_malloc_ForObject = GetSubHash( "_System_GC_malloc_ForObject",1 ) )
253        pSub_System_GC_malloc_ForObject->Using();
254
255    if( pSub_System_GC_malloc_ForObjectPtr = GetSubHash( "_System_GC_malloc_ForObjectPtr",1 ) )
256        pSub_System_GC_malloc_ForObjectPtr->Using();
257
258    if( pSub_System_GC_free_for_SweepingDelete = GetSubHash( "_System_GC_free_for_SweepingDelete",1 ) )
259        pSub_System_GC_free_for_SweepingDelete->Using();
260
261    if( pSubStaticMethod_System_TypeBase_InitializeUserTypes = GetSubHash( "ActiveBasic.Core._System_TypeBase.InitializeUserTypes",1 ) ){
262        pSubStaticMethod_System_TypeBase_InitializeUserTypes->Using();
263        pSubStaticMethod_System_TypeBase_InitializeUserTypes->ThisIsAutoGenerationProc();
264    }
265
266    if( pUserProc_System_CGarbageCollection_RegisterGlobalRoots = GetClassMethod( "_System_CGarbageCollection", "RegisterGlobalRoots" ) ){
267        pUserProc_System_CGarbageCollection_RegisterGlobalRoots->Using();
268        pUserProc_System_CGarbageCollection_RegisterGlobalRoots->ThisIsAutoGenerationProc();
269    }
270
271    //リロケーション情報
272    pobj_Reloc=new CReloc();
273
274    //レジスタのブロッキングを管理するためのオブジェクトを生成
275    pobj_BlockReg=new CBlockReg;
276
277    //レキシカルスコープ情報を初期化
278    compiler.codeGenerator.lexicalScopes.Init(0);
279
280
281    /////////////////////////////////////////////////////////////////
282    // デバッグコンパイル用のログを生成する
283    /////////////////////////////////////////////////////////////////
284#ifdef _DEBUG
285    {
286        ofstream ofs("middle_code.txt");
287        ofs << basbuf << endl;
288        ofs.close();
289    }
290#endif
291
292
293    //////////////////////
294    // グローバル実行領域
295    //////////////////////
296
297    cp=-1;
298    UserProc::CompileStartForGlobalArea();
299
300    if( !compiler.IsDll() ){
301        // 名前空間が初期化されているかをチェック
302        if( compiler.GetNamespaceSupporter().GetLivingNamespaceScopes().size() ){
303            SetError();
304        }
305
306        //ラベル管理オブジェクトを初期化
307        compiler.codeGenerator.gotoLabels.clear();
308
309        //Gotoラベルスケジュール
310        compiler.codeGenerator.gotoLabelSchedules.clear();
311
312        //With情報のメモリを確保
313        extern WITHINFO WithInfo;
314        WithInfo.ppName=(char **)HeapAlloc(hHeap,0,1);
315        WithInfo.pWithCp=(int *)HeapAlloc(hHeap,0,1);
316        WithInfo.num=0;
317
318        //Continueアドレスを初期化
319        compiler.codeGenerator.ClearContinueArea();
320
321        //スタックフレーム管理用クラスを選択
322        pobj_sf=new StackFrame();
323
324        // コード生成対象を選択
325        compiler.codeGenerator.Select( compiler.GetObjectModule().globalNativeCode );
326
327        trace_for_sourcecodestep( "★★★ グローバル領域のコンパイルを開始" );
328
329
330        //未完成
331        //breakpoint;
332
333        if( compiler.IsCore() )
334        {
335            //sub rsp,スタックフレームサイズ
336            compiler.codeGenerator.op_sub_RV( sizeof(_int64), REG_RSP, 0x108 );
337
338            if(bDebugCompile){
339                //デバッグ用の変数を定義
340                DebugVariable();
341            }
342
343            //GC用の変数を定義
344            InitGCVariables();
345
346            //_System_StartupProgramの呼び出し
347            compiler.codeGenerator.op_call(pSub_System_StartupProgram);
348        }
349
350        // _System_GlobalArea の呼び出し
351        compiler.codeGenerator.op_call( pSub_System_GlobalArea );
352
353
354        if( !compiler.IsStaticLibrary() )
355        {
356            ///////////////////////////////////////
357            // グローバル文字列変数の解放処理
358            ///////////////////////////////////////
359
360            //call _System_End
361            extern const UserProc *pSub_System_End;
362            compiler.codeGenerator.op_call(pSub_System_End);
363
364
365            //add rsp,スタックフレームサイズ
366            compiler.codeGenerator.op_add_RV( REG_RSP, 0x108 );
367
368            //xor rax,rax(raxを0に初期化する)
369            compiler.codeGenerator.op_zero_reg(REG_RAX);
370
371            //ret
372            compiler.codeGenerator.op_ret();
373        }
374
375        //スタックフレームスケジュールを実行
376        pobj_sf->RunningSchedule( 0x100 );
377        delete pobj_sf;
378        pobj_sf=0;
379
380        //グローバル実行領域のコードサイズ
381        extern int GlobalOpBufferSize;
382        GlobalOpBufferSize = compiler.linker.GetNativeCode().GetSize();
383
384        //With情報のメモリを解放
385        for(i=0;i<WithInfo.num;i++){
386            SetError(22,"With",WithInfo.pWithCp[i]);
387            HeapDefaultFree(WithInfo.ppName[i]);
388        }
389        HeapDefaultFree(WithInfo.ppName);
390        HeapDefaultFree(WithInfo.pWithCp);
391
392        // 名前空間が正しく閉じられているかをチェック
393        if( compiler.GetNamespaceSupporter().GetLivingNamespaceScopes().size() ){
394            SetError(63,NULL,-1);
395        }
396
397    }
398    else{
399        ////////////////
400        // DLLの場合
401        ////////////////
402
403
404    }
405
406    //重複エラー情報管理のメモリを解放(グローバル領域用)
407    for(i=0;i<SynonymErrorNum;i++) HeapDefaultFree(SynonymErrorWords[i]);
408    HeapDefaultFree(SynonymErrorWords);
409
410
411    StepCompileProgress();
412
413
414    /////////////////////
415    // ローカル実行領域
416    /////////////////////
417
418    //プロシージャをコンパイル開始
419    cp=0;
420    CompileLocal();
421
422    // 終了
423    ///////////////////////
424
425    StepCompileProgress();
426
427
428    //レジスタのブロッキングを管理するためのオブジェクトを破棄
429    delete pobj_BlockReg;
430
431    //ネイティブコード生成はここまで
432    //////////////////////////////////////////////////////////
433
434
435
436    trace( "コード生成が終了しました。" );
437
438
439    if( compiler.IsStaticLibrary() )
440    {
441        // 静的リンクライブラリ
442
443        // 格納先ディレクトリを作る
444        Jenga::Common::Path path( OutputFileName );
445        Jenga::Common::Directory dir( path.GetDriveName() + path.GetDirName(), true );
446
447        // 書き込む
448        if( !compiler.GetObjectModule().Write( OutputFileName ) )
449        {
450            MessageBox(0,"XML書き込みに失敗","test",0);
451        }
452        return;
453    }
454
455    extern BOOL bError;
456    if( !bError )
457    {
458        CompileMessage( "リンク中..." );
459    }
460
461
462    compiler.linker.Link( compiler.GetObjectModule() );
463
464    extern SourceLines oldSourceLines;
465    oldSourceLines = compiler.linker.GetNativeCode().GetSourceLines();
466
467
468    /////////////////////////////////////////////////////////////////
469    // vtblの構築
470    /////////////////////////////////////////////////////////////////
471
472    compiler.GetObjectModule().meta.GetClasses().GenerateVTables();
473
474
475
476    ////////////////////////////////
477    // ここで一旦ログを取る
478    ////////////////////////////////
479    Diagnose();
480
481
482
483    ////////////////////////////////
484    // 使用するDLL関数のチェック
485    ////////////////////////////////
486    compiler.GetObjectModule().meta.GetDllProcs().Iterator_Reset();
487    while( compiler.GetObjectModule().meta.GetDllProcs().Iterator_HasNext() )
488    {
489        const DllProc *pDllProc = compiler.GetObjectModule().meta.GetDllProcs().Iterator_GetNext();
490
491        if( !pDllProc->IsUsing() ){
492            continue;
493        }
494/*
495        //エラーチェック
496        HINSTANCE hLib;
497        hLib=LoadLibrary( pDllProc->GetDllFileName().c_str() );
498        if(!hLib){
499            extern char OutputFileName[MAX_PATH];
500            char temp2[MAX_PATH],temp3[MAX_PATH];
501            _splitpath(OutputFileName,temp2,temp3,NULL,NULL);
502            lstrcat(temp2,temp3);
503            lstrcpy(temp3,pDllProc->GetDllFileName().c_str());
504            GetFullPath(temp3,temp2);
505            hLib=LoadLibrary(temp3);
506
507            if(!hLib){
508                SetError(-106,pDllProc->GetDllFileName().c_str(),pDllProc->GetCodePos());
509            }
510        }
511
512        if(hLib){
513            if(!GetProcAddress(hLib,pDllProc->GetAlias().c_str())){
514                FreeLibrary(hLib);
515                SetError(-107,pDllProc->GetAlias(),pDllProc->GetCodePos());
516            }
517            FreeLibrary(hLib);
518        }
519*/
520    }
521
522
523
524    /////////////////////////////
525    // リソースデータを読み込む
526    /////////////////////////////
527    extern char ResourceFileName[MAX_PATH];
528    GetResourceData(ResourceFileName);
529
530
531    //////////////////////////////
532    // エクスポート情報(DLLのみ)
533    //////////////////////////////
534    IMAGE_EXPORT_DIRECTORY ImageExportDirectory;
535    DWORD *lpdwExportAddressTable;
536    DWORD *lpdwExportNamePointerTable;
537    WORD *lpwExportOrdinalTable;
538    char lpExportNames[8192];
539    int ExportNamesLength;
540    int ExportNum;
541    int DllMain_EntryPoint;
542
543    DllMain_EntryPoint=-1;
544    ExportNum=0;
545    ExportNamesLength=0;
546    lpdwExportAddressTable=(DWORD *)HeapAlloc(hHeap,0,1);
547    lpdwExportNamePointerTable=(DWORD *)HeapAlloc(hHeap,0,1);
548    lpwExportOrdinalTable=(WORD *)HeapAlloc(hHeap,0,1);
549
550    if(bUse_ExportSection){
551        _splitpath(OutputFileName,NULL,NULL,lpExportNames,temporary);
552        lstrcat(lpExportNames,temporary);
553        ExportNamesLength=lstrlen(lpExportNames)+1;
554
555        UserProc *pUserProc,*psi2;
556        while(1){
557            //辞書順にサーチ
558            temporary[0]=0;
559            compiler.GetObjectModule().meta.GetUserProcs().Iterator_Reset();
560            while( compiler.GetObjectModule().meta.GetUserProcs().Iterator_HasNext() )
561            {
562                pUserProc = compiler.GetObjectModule().meta.GetUserProcs().Iterator_GetNext();
563                if(pUserProc->IsExport()){
564                    if(temporary[0]=='\0'){
565                        lstrcpy(temporary,pUserProc->GetName().c_str());
566                        psi2=pUserProc;
567                    }
568                    else{
569                        i3=lstrlen(temporary);
570                        i4=(int)pUserProc->GetName().size();
571                        if(i3<i4) i3=i4;
572                        if(memcmp(temporary,pUserProc->GetName().c_str(),i3)>0){
573                            lstrcpy(temporary,pUserProc->GetName().c_str());
574                            psi2=pUserProc;
575                        }
576                    }
577                }
578            }
579            if(psi2==0) break;
580            pUserProc=psi2;
581
582            pUserProc->ExportOff();
583
584            if( pUserProc->GetName() == "DllMain" ){
585                DllMain_EntryPoint = pUserProc->GetBeginOpAddress();
586            }
587
588            lpdwExportAddressTable=(DWORD *)HeapReAlloc(hHeap,0,lpdwExportAddressTable,(ExportNum+1)*sizeof(DWORD));
589            lpdwExportAddressTable[ExportNum] = pUserProc->GetBeginOpAddress();
590
591            lpdwExportNamePointerTable=(DWORD *)HeapReAlloc(hHeap,0,lpdwExportNamePointerTable,(ExportNum+1)*sizeof(DWORD));
592            lpdwExportNamePointerTable[ExportNum]=ExportNamesLength;
593
594            lpwExportOrdinalTable=(WORD *)HeapReAlloc(hHeap,0,lpwExportOrdinalTable,(ExportNum+1)*sizeof(WORD));
595            lpwExportOrdinalTable[ExportNum]=ExportNum;
596
597            lstrcpy(lpExportNames+ExportNamesLength,pUserProc->GetName().c_str());
598            ExportNamesLength+=lstrlen(lpExportNames+ExportNamesLength)+1;
599
600            ExportNum++;
601        }
602        for(i=0;i<ExportNum;i++){
603            lpdwExportNamePointerTable[i]+=
604                sizeof(IMAGE_EXPORT_DIRECTORY)+ //エクスポートディレクトリテーブルを飛び越す
605                ExportNum*sizeof(DWORD)+        //エクスポート アドレス テーブルを飛び越す
606                ExportNum*sizeof(DWORD)+        //エクスポート名ポインタ テーブルを飛び越す
607                ExportNum*sizeof(WORD);         //エクスポート序数テーブルを飛び越す
608        }
609
610        ImageExportDirectory.Characteristics=0;
611        ImageExportDirectory.TimeDateStamp=(DWORD)time(NULL);
612        ImageExportDirectory.MajorVersion=0;
613        ImageExportDirectory.MinorVersion=0;
614        ImageExportDirectory.Name=sizeof(IMAGE_EXPORT_DIRECTORY)+
615            ExportNum*sizeof(DWORD)+    //エクスポート アドレス テーブルを飛び越す
616            ExportNum*sizeof(DWORD)+    //エクスポート名ポインタ テーブルを飛び越す
617            ExportNum*sizeof(WORD);     //エクスポート序数テーブルを飛び越す
618        ImageExportDirectory.Base=1;
619        ImageExportDirectory.NumberOfFunctions=ExportNum;
620        ImageExportDirectory.NumberOfNames=ExportNum;
621        ImageExportDirectory.AddressOfFunctions=sizeof(IMAGE_EXPORT_DIRECTORY);
622        ImageExportDirectory.AddressOfNames=ImageExportDirectory.AddressOfFunctions+ExportNum*sizeof(DWORD);
623        ImageExportDirectory.AddressOfNameOrdinals=ImageExportDirectory.AddressOfNames+ExportNum*sizeof(DWORD);
624    }
625
626
627    /////////////////////
628    //インポートDLL情報
629    /////////////////////
630
631    /*
632    インポート アドレス テーブル(ルックアップと同じ内容だが、プログラム実行時に実行アドレスに書き換えられる)
633    ルックアップ テーブル(ヒントを示すRVA)
634    IMAGE_IMPORT_DESCRIPTOR1[size=0x14] インポートヘッダ
635    IMAGE_IMPORT_DESCRIPTOR2[size=0x14]
636    IMAGE_IMPORT_DESCRIPTOR3[size=0x14]
637    ...
638    Dll名1[size=0x10]
639    Dll名2[size=0x10]
640    Dll名3[size=0x10]
641    ...
642    ヒントテーブル(関数名を羅列したもの)
643    */
644
645    /*
646    IMAGE_IMPORT_DESCRIPTOR1[size=0x14] インポートヘッダ
647    IMAGE_IMPORT_DESCRIPTOR2[size=0x14]
648    IMAGE_IMPORT_DESCRIPTOR3[size=0x14]
649    ...
650    Dll名1[size=0x10]
651    Dll名2[size=0x10]
652    Dll名3[size=0x10]
653    ...
654    ルックアップ テーブル(ヒントを示すRVA)
655    ヒントテーブル
656    インポート アドレス テーブル(ルックアップと同じ内容だが、プログラム実行時に実行アドレスに書き換えられる)
657    */
658
659    char **ppDllNames=(char **)HeapAlloc(hHeap,0,1);
660
661    int ImportDllNum=0;
662
663    compiler.GetObjectModule().meta.GetDllProcs().Iterator_Reset();
664    while( compiler.GetObjectModule().meta.GetDllProcs().Iterator_HasNext() )
665    {
666        const DllProc *pDllProc = compiler.GetObjectModule().meta.GetDllProcs().Iterator_GetNext();
667
668        if( !pDllProc->IsUsing() ){
669            continue;
670        }
671
672        if( pDllProc->GetDllFileName().size() > 16 ){
673            SetError(7,NULL,cp);
674            break;
675        }
676        for(i2=0;i2<ImportDllNum;i2++){
677            if( pDllProc->GetDllFileName() == ppDllNames[i2] ){
678                break;
679            }
680        }
681        if(i2==ImportDllNum){
682            ppDllNames=(char **)HeapReAlloc(hHeap,0,ppDllNames,(ImportDllNum+1)*sizeof(char **));
683            ppDllNames[ImportDllNum]=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,16);
684            lstrcpy(ppDllNames[ImportDllNum],pDllProc->GetDllFileName().c_str());
685            ImportDllNum++;
686        }
687    }
688
689    //IMAGE_IMPORT_DESCRIPTOR、及びルックアップ テーブル サイズの計算
690    IMAGE_IMPORT_DESCRIPTOR *pImportDescriptor;
691    int LookupSize;
692    LookupSize=0;
693    pImportDescriptor=(IMAGE_IMPORT_DESCRIPTOR *)HeapAlloc(hHeap,0,(ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR));
694    for(i=0;i<ImportDllNum;i++){
695        //IMAGE_IMPORT_DESCRIPTOR
696        pImportDescriptor[i].OriginalFirstThunk=LookupSize; //※すぐ下で再計算
697        pImportDescriptor[i].TimeDateStamp=0;
698        pImportDescriptor[i].ForwarderChain=0;
699        pImportDescriptor[i].Name=i*0x10;   //※すぐ下で再計算
700
701        compiler.GetObjectModule().meta.GetDllProcs().Iterator_Reset();
702        while( compiler.GetObjectModule().meta.GetDllProcs().Iterator_HasNext() )
703        {
704            const DllProc *pDllProc = compiler.GetObjectModule().meta.GetDllProcs().Iterator_GetNext();
705
706            if( !pDllProc->IsUsing() ){
707                continue;
708            }
709
710            if( pDllProc->GetDllFileName() == ppDllNames[i] ){
711                //ルックアップデータのサイズを追加
712                LookupSize+=sizeof(_int64);
713            }
714        }
715        LookupSize+=sizeof(_int64); //NULL用
716    }
717    memset(&pImportDescriptor[i],0,sizeof(IMAGE_IMPORT_DESCRIPTOR));
718    for(i=0;i<ImportDllNum;i++){
719        //インポートアドレステーブル分の差分を追加
720        pImportDescriptor[i].OriginalFirstThunk+=LookupSize;
721
722        //DLL名への差分を追加
723        pImportDescriptor[i].Name+=
724            LookupSize+         //インポート アドレス テーブル
725            LookupSize+         //ルックアップテーブル
726            (ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR);   //IMAGE_IMPORT_DESCRIPTOR
727    }
728
729    //ルックアップ テーブル、ヒント テーブル
730    unsigned _int64 *pLookupTable;
731    pLookupTable=(unsigned _int64 *)HeapAlloc(hHeap,0,LookupSize*sizeof(_int64)+1);
732    char *pHintTable;
733    int HintSize,HintAllocSize;
734    HintSize=0;
735    HintAllocSize=128*2;
736    pHintTable=(char *)HeapAlloc(hHeap,0,HintAllocSize);
737    for(i=0,i5=0;i<ImportDllNum;i++){
738        compiler.GetObjectModule().meta.GetDllProcs().Iterator_Reset();
739        while( compiler.GetObjectModule().meta.GetDllProcs().Iterator_HasNext() )
740        {
741            DllProc *pDllProc = compiler.GetObjectModule().meta.GetDllProcs().Iterator_GetNext();
742
743            if( !pDllProc->IsUsing() ){
744                continue;
745            }
746
747            if( pDllProc->GetDllFileName() == ppDllNames[i] ){
748                //ルックアップの位置をセット(後にインポート アドレス テーブルにセットしなおされる)
749                pDllProc->SetLookupAddress( i5*sizeof(_int64) );
750
751                //ルックアップ テーブルの値をセット
752                pLookupTable[i5++]=
753                    LookupSize+         //インポート アドレス テーブル
754                    LookupSize+         //ルックアップテーブル
755                    (ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR)+   //IMAGE_IMPORT_DESCRIPTOR
756                    ImportDllNum*0x10+  //DLL名の羅列
757                    HintSize;           //ヒント名へのオフセット
758
759                //ヒント テーブル
760                pHintTable[HintSize++]=0;
761                pHintTable[HintSize++]=0;
762                lstrcpy(pHintTable+HintSize,pDllProc->GetAlias().c_str());
763                i4=(int)pDllProc->GetAlias().size();
764                HintSize+=i4+1;
765                if(i4%2==0) pHintTable[HintSize++]=0;
766
767                if(HintAllocSize<HintSize+128){
768                    HintAllocSize+=128;
769                    pHintTable=(char *)HeapReAlloc(hHeap,0,pHintTable,HintAllocSize);
770                }
771            }
772        }
773        pLookupTable[i5++]=0;
774    }
775
776
777    if( compiler.IsDll() ){
778        //DLLの場合はリロケーション情報を仮生成
779        //※正式な生成は各セクションのメモリ上のサイズが決定してから再度行う。
780        pobj_Reloc->ResetRelocBuffer();
781    }
782
783
784
785    //グローバル変数情報を扱う構造体も初期バッファの有無による配置を行う
786    //(デバッグ情報で利用される)
787    BOOST_FOREACH( Variable *pVar, compiler.GetObjectModule().meta.GetGlobalVars() ){
788        if(pVar->GetOffsetAddress()&0x80000000){
789            pVar->SetOffsetAddress(
790                (pVar->GetOffsetAddress()&0x7FFFFFFF)
791                + compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()
792            );
793        }
794    }
795
796
797
798    ////////////////////////////////////
799    // デバッグセクションを生成
800    ////////////////////////////////////
801
802    //デバッグセクションを生成
803    CDebugSection *pobj_DebugSection;
804    pobj_DebugSection=new CDebugSection();
805    extern BOOL bDebugCompile;
806    extern BOOL bError;
807    if(bDebugCompile&&bError==0){
808        CompileMessage( "デバッグ情報を生成しています。" );
809
810        pobj_DebugSection->make();
811
812        CompileMessage( "デバッグ情報の生成が完了しました。" );
813    }
814
815
816
817    /////////////////////////////////////
818    // 各セクションの位置とサイズを計算
819    /////////////////////////////////////
820
821    //コードセッションのファイル上のサイズ
822    if(compiler.linker.GetNativeCode().GetSize()%FILE_ALIGNMENT)
823    {
824        FileSize_CodeSection =
825            compiler.linker.GetNativeCode().GetSize()
826            + (FILE_ALIGNMENT-compiler.linker.GetNativeCode().GetSize()%FILE_ALIGNMENT);
827    }
828    else
829    {
830        FileSize_CodeSection = compiler.linker.GetNativeCode().GetSize();
831    }
832    if(FileSize_CodeSection) bUse_CodeSection=1;
833    else bUse_CodeSection=0;
834
835    //エクスポートセクションのファイル上のサイズ
836    i=  sizeof(IMAGE_EXPORT_DIRECTORY)+ //エクスポートディレクトリテーブルを飛び越す
837        ExportNum*sizeof(DWORD)+        //エクスポート アドレス テーブルを飛び越す
838        ExportNum*sizeof(DWORD)+        //エクスポート名ポインタ テーブルを飛び越す
839        ExportNum*sizeof(WORD)+         //エクスポート序数テーブルを飛び越す
840        ExportNamesLength;              //シンボル名バッファ
841    if(bUse_ExportSection){
842        if(i%FILE_ALIGNMENT) FileSize_ExportSection=i+(FILE_ALIGNMENT-i%FILE_ALIGNMENT);
843        else FileSize_ExportSection=i;
844    }
845    else FileSize_ExportSection=0;
846
847    //インポートセクションのファイル上のサイズ
848    i=
849        LookupSize+         //インポート アドレス テーブル
850        LookupSize+         //ルックアップテーブル
851        (ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR)+   //IMAGE_IMPORT_DESCRIPTOR
852        ImportDllNum*0x10+  //DLL名の羅列
853        HintSize;           //ヒント名
854    if(i%FILE_ALIGNMENT) FileSize_ImportSection=i+(FILE_ALIGNMENT-i%FILE_ALIGNMENT);
855    else FileSize_ImportSection=i;
856    bUse_ImportSection=1;   //インポートセクションは必ず存在する
857
858    //データセクションのファイル上のサイズ
859    if(compiler.GetObjectModule().dataTable.GetSize()%FILE_ALIGNMENT) FileSize_DataSection=compiler.GetObjectModule().dataTable.GetSize()+(FILE_ALIGNMENT-compiler.GetObjectModule().dataTable.GetSize()%FILE_ALIGNMENT);
860    else FileSize_DataSection=compiler.GetObjectModule().dataTable.GetSize();
861    if(FileSize_DataSection) bUse_DataSection=1;
862    else bUse_DataSection=0;
863
864    //リライタブルセクションのファイル上のサイズ(グローバル変数の初期情報のみを格納)
865    if( compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize() % FILE_ALIGNMENT )
866    {
867        FileSize_RWSection =
868            compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()
869            + (FILE_ALIGNMENT-compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()%FILE_ALIGNMENT);
870    }
871    else{
872        if( compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize() )
873        {
874            FileSize_RWSection = compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize();
875        }
876        else FileSize_RWSection=FILE_ALIGNMENT;
877    }
878    bUse_RWSection=1;
879
880    //リソースセクションのファイル上のサイズ
881    char *RSrcSectionBuffer;
882    int RSrcSectionSize;
883    RSrcSectionBuffer=GetRSrcSectionBuffer(&RSrcSectionSize);
884    if(RSrcSectionSize%FILE_ALIGNMENT) FileSize_RSrcSection=RSrcSectionSize+(FILE_ALIGNMENT-RSrcSectionSize%FILE_ALIGNMENT);
885    else FileSize_RSrcSection=RSrcSectionSize;
886    if(FileSize_RSrcSection) bUse_RSrcSection=1;
887    else bUse_RSrcSection=0;
888
889    //リロケーションセクションのファイル上のサイズ
890    if(pobj_Reloc->length%FILE_ALIGNMENT) FileSize_RelocSection=pobj_Reloc->length+(FILE_ALIGNMENT-pobj_Reloc->length%FILE_ALIGNMENT);
891    else FileSize_RelocSection=pobj_Reloc->length;
892    if(FileSize_RelocSection) bUse_RelocSection=1;
893    else bUse_RelocSection=0;
894
895    //デバッグセクションのファイル上のサイズ
896    if(pobj_DebugSection->length%FILE_ALIGNMENT) FileSize_DebugSection=pobj_DebugSection->length+(FILE_ALIGNMENT-pobj_DebugSection->length%FILE_ALIGNMENT);
897    else FileSize_DebugSection=pobj_DebugSection->length;
898    if(FileSize_DebugSection) bUse_DebugSection=1;
899    else bUse_DebugSection=0;
900
901
902    //各セッションのファイル上の位置
903    FilePos_CodeSection=    EXE_HEADER_SIZE;
904    FilePos_ExportSection=  FilePos_CodeSection+
905                            FileSize_CodeSection;
906    FilePos_ImportSection=  FilePos_ExportSection+
907                            FileSize_ExportSection;
908    FilePos_DataSection=    FilePos_ImportSection+
909                            FileSize_ImportSection;
910    FilePos_RWSection=      FilePos_DataSection+
911                            FileSize_DataSection;
912    FilePos_RSrcSection=    FilePos_RWSection+
913                            FileSize_RWSection;
914    FilePos_RelocSection=   FilePos_RSrcSection+
915                            FileSize_RSrcSection;
916    FilePos_DebugSection=   FilePos_RelocSection+
917                            FileSize_RelocSection;
918
919    //コードセッションのメモリ上のサイズ
920    if(FileSize_CodeSection%MEM_ALIGNMENT) MemSize_CodeSection=FileSize_CodeSection+(MEM_ALIGNMENT-FileSize_CodeSection%MEM_ALIGNMENT);
921    else MemSize_CodeSection=FileSize_CodeSection;
922
923    //エクスポートセクションのメモリ上のサイズ
924    if(FileSize_ExportSection%MEM_ALIGNMENT) MemSize_ExportSection=FileSize_ExportSection+(MEM_ALIGNMENT-FileSize_ExportSection%MEM_ALIGNMENT);
925    else MemSize_ExportSection=FileSize_ExportSection;
926
927    //インポートセクションのメモリ上のサイズ
928    if(FileSize_ImportSection%MEM_ALIGNMENT) MemSize_ImportSection=FileSize_ImportSection+(MEM_ALIGNMENT-FileSize_ImportSection%MEM_ALIGNMENT);
929    else MemSize_ImportSection=FileSize_ImportSection;
930
931    //データセクションのメモリ上のサイズ
932    if(FileSize_DataSection%MEM_ALIGNMENT) MemSize_DataSection=FileSize_DataSection+(MEM_ALIGNMENT-FileSize_DataSection%MEM_ALIGNMENT);
933    else MemSize_DataSection=FileSize_DataSection;
934
935    //リライタブルセクションのメモリ上のサイズ
936    i = compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()
937        + compiler.GetObjectModule().meta.GetGlobalVars().GetAllSize();
938    if(i%MEM_ALIGNMENT) MemSize_RWSection=i+(MEM_ALIGNMENT-i%MEM_ALIGNMENT);
939    else MemSize_RWSection=i;
940
941    //リソースセクションのメモリ上のサイズ
942    if(FileSize_RSrcSection%MEM_ALIGNMENT) MemSize_RSrcSection=FileSize_RSrcSection+(MEM_ALIGNMENT-FileSize_RSrcSection%MEM_ALIGNMENT);
943    else MemSize_RSrcSection=FileSize_RSrcSection;
944
945    //リロケーションセクションのメモリ上のサイズ
946    if(FileSize_RelocSection%MEM_ALIGNMENT) MemSize_RelocSection=FileSize_RelocSection+(MEM_ALIGNMENT-FileSize_RelocSection%MEM_ALIGNMENT);
947    else MemSize_RelocSection=FileSize_RelocSection;
948
949    //デバッグセクションのメモリ上のサイズ
950    if(FileSize_DebugSection%MEM_ALIGNMENT) MemSize_DebugSection=FileSize_DebugSection+(MEM_ALIGNMENT-FileSize_DebugSection%MEM_ALIGNMENT);
951    else MemSize_DebugSection=FileSize_DebugSection;
952
953
954    //各セッションのメモリ上の位置
955    if(bUse_ExportSection)  MemPos_ExportSection=   0x1000+
956                                                    MemSize_CodeSection;
957    else                    MemPos_ExportSection=0;
958    if(bUse_ImportSection)  MemPos_ImportSection=   0x1000+
959                                                    MemSize_CodeSection+
960                                                    MemSize_ExportSection;
961    else                    MemPos_ImportSection=0;
962    if(bUse_DataSection)    MemPos_DataSection=     0x1000+
963                                                    MemSize_CodeSection+
964                                                    MemSize_ExportSection+
965                                                    MemSize_ImportSection;
966    else                    MemPos_DataSection=0;
967    if(bUse_RWSection)      MemPos_RWSection=       0x1000+
968                                                    MemSize_CodeSection+
969                                                    MemSize_ExportSection+
970                                                    MemSize_ImportSection+
971                                                    MemSize_DataSection;
972    else                    MemPos_RWSection=0;
973    if(bUse_RSrcSection)    MemPos_RSrcSection=     0x1000+
974                                                    MemSize_CodeSection+
975                                                    MemSize_ExportSection+
976                                                    MemSize_ImportSection+
977                                                    MemSize_DataSection+
978                                                    MemSize_RWSection;
979    else                    MemPos_RSrcSection=0;
980    if(bUse_RelocSection)   MemPos_RelocSection=    0x1000+
981                                                    MemSize_CodeSection+
982                                                    MemSize_ExportSection+
983                                                    MemSize_ImportSection+
984                                                    MemSize_DataSection+
985                                                    MemSize_RWSection+
986                                                    MemSize_RSrcSection;
987    else                    MemPos_RelocSection=0;
988    if(bUse_DebugSection)   MemPos_DebugSection=    0x1000+
989                                                    MemSize_CodeSection+
990                                                    MemSize_ExportSection+
991                                                    MemSize_ImportSection+
992                                                    MemSize_DataSection+
993                                                    MemSize_RWSection+
994                                                    MemSize_RSrcSection+
995                                                    MemSize_RelocSection;
996    else                    MemPos_DebugSection=0;
997
998
999
1000    ////////////////////////////
1001    // エクスポート情報の再配置
1002    ////////////////////////////
1003    if(bUse_ExportSection){
1004        for(i=0;i<ExportNum;i++){
1005            lpdwExportAddressTable[i]+=MemPos_CodeSection;
1006            lpdwExportNamePointerTable[i]+=MemPos_ExportSection;
1007        }
1008
1009        ImageExportDirectory.Name+=                     MemPos_ExportSection;
1010        ImageExportDirectory.AddressOfFunctions+=       MemPos_ExportSection;
1011        ImageExportDirectory.AddressOfNames+=           MemPos_ExportSection;
1012        ImageExportDirectory.AddressOfNameOrdinals+=    MemPos_ExportSection;
1013    }
1014
1015
1016    ////////////////////////////
1017    // インポート情報の再配置
1018    ////////////////////////////
1019    for(i=0,i5=0;i<ImportDllNum;i++){
1020        //IMAGE_IMPORT_DESCRIPTOR
1021        pImportDescriptor[i].OriginalFirstThunk+=MemPos_ImportSection;
1022        pImportDescriptor[i].Name+=MemPos_ImportSection;
1023
1024        //インポート アドレス テーブル(ルックアップ テーブルを差し引く)
1025        pImportDescriptor[i].FirstThunk=pImportDescriptor[i].OriginalFirstThunk-
1026            LookupSize;         //ルックアップテーブル
1027
1028        compiler.GetObjectModule().meta.GetDllProcs().Iterator_Reset();
1029        while( compiler.GetObjectModule().meta.GetDllProcs().Iterator_HasNext() )
1030        {
1031            const DllProc *pDllProc = compiler.GetObjectModule().meta.GetDllProcs().Iterator_GetNext();
1032
1033            if( !pDllProc->IsUsing() ){
1034                continue;
1035            }
1036
1037            if( pDllProc->GetDllFileName() == ppDllNames[i] ){
1038                //ルックアップ テーブル
1039                pLookupTable[i5++]+=MemPos_ImportSection;
1040            }
1041        }
1042        i5++;
1043    }
1044
1045
1046    ////////////////////////////////////////
1047    //仮想関数データテーブルスケジュール
1048    compiler.GetObjectModule().meta.GetClasses().ActionVtblSchedule(ImageBase,MemPos_CodeSection);
1049
1050
1051    if( compiler.IsDll() ){
1052        //DLLの場合はリロケーション情報を生成
1053        pobj_Reloc->ResetRelocBuffer();
1054    }
1055
1056
1057    compiler.linker.SetImageBase( ImageBase );
1058    compiler.linker.ResolveDataTableSchedules( MemPos_DataSection );
1059    compiler.linker.ResolveDllProcSchedules( MemPos_CodeSection, MemPos_ImportSection, LookupSize, HintSize );
1060    compiler.linker.ResolveUserProcSchedules( MemPos_CodeSection );
1061    compiler.linker.ResolveGlobalVarSchedules( MemPos_RWSection );
1062    compiler.linker.ResolveVtblSchedule( MemPos_DataSection );
1063
1064
1065    ////////////////////////////////
1066    // リソースアドレススケジュール
1067    extern DWORD *lpdwRSrcAddrSchedule;
1068    extern int RSrcAddrScheduleNum;
1069    for(i=0;i<RSrcAddrScheduleNum;i++){
1070        *(DWORD *)(RSrcSectionBuffer+lpdwRSrcAddrSchedule[i])+=MemPos_RSrcSection;
1071    }
1072    HeapDefaultFree(lpdwRSrcAddrSchedule);
1073
1074
1075    //Dosスタブ
1076    char *DosStubBuffer;
1077    int DosStubSize;
1078    hFile=CreateFile(
1079        ( Jenga::Common::Environment::GetAppDir() + "\\SubOperation\\dosstub.pgm" ).c_str(),
1080        GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
1081    if(hFile==INVALID_HANDLE_VALUE){
1082        MessageBox(hOwnerEditor,"dosstub.pgmの読み込みに失敗","error",MB_OK);
1083        goto EndWriteOpcode;
1084    }
1085    DosStubSize=GetFileSize(hFile,NULL);
1086    DosStubBuffer=(char *)HeapAlloc(hHeap,0,DosStubSize);
1087    ReadFile(hFile,DosStubBuffer,DosStubSize,(DWORD *)&i2,NULL);
1088    CloseHandle(hFile);
1089
1090
1091    extern BOOL bError;
1092    if(bError) goto EndWriteOpcode;
1093
1094
1095    ////////////////////////////
1096    // EXEファイルのヘッダ情報
1097    ////////////////////////////
1098
1099    IMAGE_DOS_HEADER ImageDosHeader;
1100    ImageDosHeader.e_magic= 0x5A4D;
1101    ImageDosHeader.e_cblp=  0x0090;
1102    ImageDosHeader.e_cp=    0x0003;
1103    ImageDosHeader.e_crlc=  0;
1104    ImageDosHeader.e_cparhdr=4;
1105    ImageDosHeader.e_minalloc=0x0000;
1106    ImageDosHeader.e_maxalloc=0xFFFF;
1107    ImageDosHeader.e_ss=    0x0000;
1108    ImageDosHeader.e_sp=    0x00B8;
1109    ImageDosHeader.e_csum=  0x0000;
1110    ImageDosHeader.e_ip=    0x0000;
1111    ImageDosHeader.e_cs=    0x0000;
1112    ImageDosHeader.e_lfarlc=0x0040;
1113    ImageDosHeader.e_ovno=  0x0000;
1114    ImageDosHeader.e_res[0]=0;
1115    ImageDosHeader.e_res[1]=0;
1116    ImageDosHeader.e_res[2]=0;
1117    ImageDosHeader.e_res[3]=0;
1118    ImageDosHeader.e_oemid= 0x0000;
1119    ImageDosHeader.e_oeminfo=0x0000;
1120    ImageDosHeader.e_res2[0]=0;
1121    ImageDosHeader.e_res2[1]=0;
1122    ImageDosHeader.e_res2[2]=0;
1123    ImageDosHeader.e_res2[3]=0;
1124    ImageDosHeader.e_res2[4]=0;
1125    ImageDosHeader.e_res2[5]=0;
1126    ImageDosHeader.e_res2[6]=0;
1127    ImageDosHeader.e_res2[7]=0;
1128    ImageDosHeader.e_res2[8]=0;
1129    ImageDosHeader.e_res2[9]=0;
1130    ImageDosHeader.e_lfanew=0x0100; //PEヘッダの位置
1131
1132
1133    /////////////////////////////////////////////
1134    // PEヘッダ
1135    /////////////////////////////////////////////
1136
1137    IMAGE_NT_HEADERS64 ImagePeHdr;
1138    ImagePeHdr.Signature=IMAGE_NT_SIGNATURE;
1139
1140    //マシンタイプ
1141    ImagePeHdr.FileHeader.Machine=              IMAGE_FILE_MACHINE_AMD64;
1142
1143    ImagePeHdr.FileHeader.NumberOfSections=     bUse_CodeSection+
1144                                                bUse_ExportSection+
1145                                                bUse_ImportSection+
1146                                                bUse_DataSection+
1147                                                bUse_RWSection+
1148                                                bUse_RSrcSection+
1149                                                bUse_RelocSection+
1150                                                bUse_DebugSection;  //セクション数
1151    ImagePeHdr.FileHeader.TimeDateStamp=        (DWORD)time(NULL);
1152    ImagePeHdr.FileHeader.PointerToSymbolTable= 0x00000000;
1153    ImagePeHdr.FileHeader.NumberOfSymbols=      0x00000000;
1154    ImagePeHdr.FileHeader.SizeOfOptionalHeader= IMAGE_SIZEOF_NT_OPTIONAL64_HEADER;
1155    if( compiler.IsDll() ){
1156        ImagePeHdr.FileHeader.Characteristics=  IMAGE_FILE_EXECUTABLE_IMAGE|
1157                                                IMAGE_FILE_DLL|
1158                                                IMAGE_FILE_LARGE_ADDRESS_AWARE;
1159    }
1160    else{
1161        ImagePeHdr.FileHeader.Characteristics=  IMAGE_FILE_RELOCS_STRIPPED|
1162                                                IMAGE_FILE_EXECUTABLE_IMAGE|
1163                                                IMAGE_FILE_LARGE_ADDRESS_AWARE;
1164    }
1165
1166    ImagePeHdr.OptionalHeader.Magic=                IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1167    ImagePeHdr.OptionalHeader.MajorLinkerVersion=   5;
1168    ImagePeHdr.OptionalHeader.MinorLinkerVersion=   0;
1169    ImagePeHdr.OptionalHeader.SizeOfCode=           FileSize_CodeSection;   //コードサイズ(.textのセッションサイズ)
1170    ImagePeHdr.OptionalHeader.SizeOfInitializedData=FileSize_DataSection;   //データサイズ(.dataのセッションサイズ)
1171    ImagePeHdr.OptionalHeader.SizeOfUninitializedData=0;                    //未初期化データのサイズ(なし)
1172    if( compiler.IsDll() ){
1173        if(DllMain_EntryPoint==-1)
1174            ImagePeHdr.OptionalHeader.AddressOfEntryPoint=0;
1175        else
1176            ImagePeHdr.OptionalHeader.AddressOfEntryPoint=MemPos_CodeSection+DllMain_EntryPoint;
1177    }
1178    else ImagePeHdr.OptionalHeader.AddressOfEntryPoint= MemPos_CodeSection;
1179    ImagePeHdr.OptionalHeader.BaseOfCode=           MemPos_CodeSection; //.textのアドレス
1180
1181    ImagePeHdr.OptionalHeader.ImageBase=            ImageBase;      //イメージベース
1182    ImagePeHdr.OptionalHeader.SectionAlignment=     MEM_ALIGNMENT;      //セクションアラインメント
1183    ImagePeHdr.OptionalHeader.FileAlignment=        FILE_ALIGNMENT;
1184    ImagePeHdr.OptionalHeader.MajorOperatingSystemVersion=4;
1185    ImagePeHdr.OptionalHeader.MinorOperatingSystemVersion=0;
1186    ImagePeHdr.OptionalHeader.MajorImageVersion=    0;
1187    ImagePeHdr.OptionalHeader.MinorImageVersion=    0;
1188    ImagePeHdr.OptionalHeader.MajorSubsystemVersion=4;
1189    ImagePeHdr.OptionalHeader.MinorSubsystemVersion=0;
1190    ImagePeHdr.OptionalHeader.Win32VersionValue=    0;
1191    ImagePeHdr.OptionalHeader.SizeOfImage=          EXE_HEADER_SIZE+
1192                                                    MemSize_CodeSection+
1193                                                    MemSize_ExportSection+
1194                                                    MemSize_ImportSection+
1195                                                    MemSize_DataSection+
1196                                                    MemSize_RWSection+
1197                                                    MemSize_RSrcSection+
1198                                                    MemSize_RelocSection+
1199                                                    MemSize_DebugSection;//すべてのイメージサイズ
1200    ImagePeHdr.OptionalHeader.SizeOfHeaders=        EXE_HEADER_SIZE;//ヘッダサイズ
1201    ImagePeHdr.OptionalHeader.CheckSum=             0;
1202    extern unsigned short TypeOfSubSystem;
1203    ImagePeHdr.OptionalHeader.Subsystem=            TypeOfSubSystem;
1204    ImagePeHdr.OptionalHeader.DllCharacteristics=   0;
1205    ImagePeHdr.OptionalHeader.SizeOfStackReserve=   0x00100000;
1206    ImagePeHdr.OptionalHeader.SizeOfStackCommit=    0x00001000;
1207    ImagePeHdr.OptionalHeader.SizeOfHeapReserve=    0x00100000;
1208    ImagePeHdr.OptionalHeader.SizeOfHeapCommit=     0x00001000;
1209    ImagePeHdr.OptionalHeader.LoaderFlags=          0;
1210    ImagePeHdr.OptionalHeader.NumberOfRvaAndSizes=  IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1211
1212    //データ ディクショナリ
1213    ImagePeHdr.OptionalHeader.DataDirectory[0].VirtualAddress=MemPos_ExportSection;
1214    ImagePeHdr.OptionalHeader.DataDirectory[0].Size=FileSize_ExportSection;
1215    ImagePeHdr.OptionalHeader.DataDirectory[1].VirtualAddress=  //IMAGE_IMPORT_DESCRIPTORを指す
1216        MemPos_ImportSection+
1217        LookupSize+ //インポート アドレス テーブル
1218        LookupSize; //ルックアップ テーブル
1219    ImagePeHdr.OptionalHeader.DataDirectory[1].Size=(ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR);
1220    ImagePeHdr.OptionalHeader.DataDirectory[2].VirtualAddress=MemPos_RSrcSection;
1221    ImagePeHdr.OptionalHeader.DataDirectory[2].Size=RSrcSectionSize;
1222    ImagePeHdr.OptionalHeader.DataDirectory[3].VirtualAddress=0;
1223    ImagePeHdr.OptionalHeader.DataDirectory[3].Size=0;
1224    ImagePeHdr.OptionalHeader.DataDirectory[4].VirtualAddress=0;
1225    ImagePeHdr.OptionalHeader.DataDirectory[4].Size=0;
1226    ImagePeHdr.OptionalHeader.DataDirectory[5].VirtualAddress=MemPos_RelocSection;
1227    ImagePeHdr.OptionalHeader.DataDirectory[5].Size=pobj_Reloc->length;
1228    ImagePeHdr.OptionalHeader.DataDirectory[6].VirtualAddress=0;
1229    ImagePeHdr.OptionalHeader.DataDirectory[6].Size=0;
1230    ImagePeHdr.OptionalHeader.DataDirectory[7].VirtualAddress=0;
1231    ImagePeHdr.OptionalHeader.DataDirectory[7].Size=0;
1232    ImagePeHdr.OptionalHeader.DataDirectory[8].VirtualAddress=0;
1233    ImagePeHdr.OptionalHeader.DataDirectory[8].Size=0;
1234    ImagePeHdr.OptionalHeader.DataDirectory[9].VirtualAddress=0;
1235    ImagePeHdr.OptionalHeader.DataDirectory[9].Size=0;
1236    ImagePeHdr.OptionalHeader.DataDirectory[10].VirtualAddress=0;
1237    ImagePeHdr.OptionalHeader.DataDirectory[10].Size=0;
1238    ImagePeHdr.OptionalHeader.DataDirectory[11].VirtualAddress=0;
1239    ImagePeHdr.OptionalHeader.DataDirectory[11].Size=0;
1240    ImagePeHdr.OptionalHeader.DataDirectory[12].VirtualAddress=MemPos_ImportSection;//インポート アドレス テーブル
1241    ImagePeHdr.OptionalHeader.DataDirectory[12].Size=LookupSize;
1242    ImagePeHdr.OptionalHeader.DataDirectory[13].VirtualAddress=0;
1243    ImagePeHdr.OptionalHeader.DataDirectory[13].Size=0;
1244    ImagePeHdr.OptionalHeader.DataDirectory[14].VirtualAddress=0;
1245    ImagePeHdr.OptionalHeader.DataDirectory[14].Size=0;
1246    ImagePeHdr.OptionalHeader.DataDirectory[15].VirtualAddress=0;
1247    ImagePeHdr.OptionalHeader.DataDirectory[15].Size=0;
1248
1249
1250    //コードセクションヘッダ
1251    IMAGE_SECTION_HEADER CodeSectionHeader;
1252    memset((char *)CodeSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1253    lstrcpy((char *)CodeSectionHeader.Name,".text");
1254    CodeSectionHeader.Misc.VirtualSize=         MemSize_CodeSection;
1255    CodeSectionHeader.VirtualAddress=           MemPos_CodeSection; //開始アドレス
1256    CodeSectionHeader.SizeOfRawData=            FileSize_CodeSection;
1257    CodeSectionHeader.PointerToRawData=         FilePos_CodeSection;    //ファイル上の開始アドレス
1258    CodeSectionHeader.PointerToRelocations=     0;
1259    CodeSectionHeader.PointerToLinenumbers=     0;
1260    CodeSectionHeader.NumberOfRelocations=      0;
1261    CodeSectionHeader.NumberOfLinenumbers=      0;
1262    CodeSectionHeader.Characteristics=          IMAGE_SCN_MEM_EXECUTE|
1263                                                IMAGE_SCN_MEM_READ|
1264                                                IMAGE_SCN_CNT_CODE;
1265
1266    //エクスポートセクションヘッダ
1267    IMAGE_SECTION_HEADER ExportSectionHeader;
1268    memset((char *)ExportSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1269    lstrcpy((char *)ExportSectionHeader.Name,".edata");
1270    ExportSectionHeader.Misc.VirtualSize=       MemSize_ExportSection;
1271    ExportSectionHeader.VirtualAddress=         MemPos_ExportSection;   //開始アドレス
1272    ExportSectionHeader.SizeOfRawData=          FileSize_ExportSection; //サイズ
1273    ExportSectionHeader.PointerToRawData=       FilePos_ExportSection;  //ファイル上の開始アドレス
1274    ExportSectionHeader.PointerToRelocations=   0;
1275    ExportSectionHeader.PointerToLinenumbers=   0;
1276    ExportSectionHeader.NumberOfRelocations=    0;
1277    ExportSectionHeader.NumberOfLinenumbers=    0;
1278    ExportSectionHeader.Characteristics=        IMAGE_SCN_CNT_INITIALIZED_DATA|
1279                                                IMAGE_SCN_MEM_READ;
1280
1281    //インポートセクションヘッダ
1282    IMAGE_SECTION_HEADER ImportSectionHeader;
1283    memset((char *)ImportSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1284    lstrcpy((char *)ImportSectionHeader.Name,".idata");
1285    ImportSectionHeader.Misc.VirtualSize=
1286        LookupSize+         //インポートアドレステーブル
1287        LookupSize+         //ルックアップテーブル
1288        (ImportDllNum+1)*sizeof(IMAGE_IMPORT_DESCRIPTOR)+
1289        16*ImportDllNum+    //DLL名
1290        HintSize;           //ヒント名(関数名)テーブル
1291    ImportSectionHeader.VirtualAddress=         MemPos_ImportSection;   //開始アドレス
1292    ImportSectionHeader.SizeOfRawData=          FileSize_ImportSection; //サイズ
1293    ImportSectionHeader.PointerToRawData=       FilePos_ImportSection;  //ファイル上の開始アドレス
1294    ImportSectionHeader.PointerToRelocations=   0;
1295    ImportSectionHeader.PointerToLinenumbers=   0;
1296    ImportSectionHeader.NumberOfRelocations=    0;
1297    ImportSectionHeader.NumberOfLinenumbers=    0;
1298    ImportSectionHeader.Characteristics=        IMAGE_SCN_CNT_INITIALIZED_DATA|
1299                                                IMAGE_SCN_MEM_READ;
1300
1301    //データセクションヘッダ
1302    IMAGE_SECTION_HEADER DataSectionHeader;
1303    memset((char *)DataSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1304    lstrcpy((char *)DataSectionHeader.Name,".sdata");
1305    DataSectionHeader.Misc.VirtualSize=         MemSize_DataSection;
1306    DataSectionHeader.VirtualAddress=           MemPos_DataSection;
1307    DataSectionHeader.SizeOfRawData=            FileSize_DataSection;
1308    DataSectionHeader.PointerToRawData=         FilePos_DataSection;
1309    DataSectionHeader.PointerToRelocations=     0;
1310    DataSectionHeader.PointerToLinenumbers=     0;
1311    DataSectionHeader.NumberOfRelocations=      0;
1312    DataSectionHeader.NumberOfLinenumbers=      0;
1313    DataSectionHeader.Characteristics=          IMAGE_SCN_CNT_INITIALIZED_DATA|
1314                                                IMAGE_SCN_MEM_READ|
1315                                                IMAGE_SCN_MEM_WRITE;
1316
1317    //リライタブルセクションヘッダ
1318    IMAGE_SECTION_HEADER RWSectionHeader;
1319    memset((char *)RWSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1320    lstrcpy((char *)RWSectionHeader.Name,".data");
1321    RWSectionHeader.Misc.VirtualSize=           compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()
1322                                                + compiler.GetObjectModule().meta.GetGlobalVars().GetAllSize();
1323    RWSectionHeader.VirtualAddress=             MemPos_RWSection;
1324    RWSectionHeader.SizeOfRawData=              FileSize_RWSection;
1325    RWSectionHeader.PointerToRawData=           FilePos_RWSection;
1326    RWSectionHeader.PointerToRelocations=       0;
1327    RWSectionHeader.PointerToLinenumbers=       0;
1328    RWSectionHeader.NumberOfRelocations=        0;
1329    RWSectionHeader.NumberOfLinenumbers=        0;
1330    RWSectionHeader.Characteristics=            IMAGE_SCN_CNT_INITIALIZED_DATA|
1331                                                IMAGE_SCN_MEM_READ|
1332                                                IMAGE_SCN_MEM_WRITE;
1333
1334    //リソースセクションヘッダ
1335    IMAGE_SECTION_HEADER RSrcSectionHeader;
1336    memset((char *)RSrcSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1337    lstrcpy((char *)RSrcSectionHeader.Name,".rsrc");
1338    RSrcSectionHeader.Misc.VirtualSize=         RSrcSectionSize;
1339    RSrcSectionHeader.VirtualAddress=           MemPos_RSrcSection;
1340    RSrcSectionHeader.SizeOfRawData=            FileSize_RSrcSection;
1341    RSrcSectionHeader.PointerToRawData=         FilePos_RSrcSection;
1342    RSrcSectionHeader.PointerToRelocations=     0;
1343    RSrcSectionHeader.PointerToLinenumbers=     0;
1344    RSrcSectionHeader.NumberOfRelocations=      0;
1345    RSrcSectionHeader.NumberOfLinenumbers=      0;
1346    RSrcSectionHeader.Characteristics=          IMAGE_SCN_CNT_INITIALIZED_DATA|
1347                                                IMAGE_SCN_MEM_READ;
1348
1349    //リロケーションセクションヘッダ
1350    IMAGE_SECTION_HEADER RelocSectionHeader;
1351    memset((char *)RelocSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1352    lstrcpy((char *)RelocSectionHeader.Name,".reloc");
1353    RelocSectionHeader.Misc.VirtualSize=        pobj_Reloc->length;
1354    RelocSectionHeader.VirtualAddress=          MemPos_RelocSection;    //開始アドレス
1355    RelocSectionHeader.SizeOfRawData=           FileSize_RelocSection;  //サイズ
1356    RelocSectionHeader.PointerToRawData=        FilePos_RelocSection;   //ファイル上の開始アドレス
1357    RelocSectionHeader.PointerToRelocations=    0;
1358    RelocSectionHeader.PointerToLinenumbers=    0;
1359    RelocSectionHeader.NumberOfRelocations=     0;
1360    RelocSectionHeader.NumberOfLinenumbers=     0;
1361    RelocSectionHeader.Characteristics=         IMAGE_SCN_CNT_INITIALIZED_DATA|
1362                                                IMAGE_SCN_MEM_DISCARDABLE|
1363                                                IMAGE_SCN_MEM_READ;
1364
1365    //デバッグセクションヘッダ
1366    IMAGE_SECTION_HEADER DebugSectionHeader;
1367    memset((char *)DebugSectionHeader.Name,0,IMAGE_SIZEOF_SHORT_NAME);
1368    lstrcpy((char *)DebugSectionHeader.Name,".debug");
1369    DebugSectionHeader.Misc.VirtualSize=        pobj_DebugSection->length;
1370    DebugSectionHeader.VirtualAddress=          MemPos_DebugSection;    //開始アドレス
1371    DebugSectionHeader.SizeOfRawData=           FileSize_DebugSection;  //サイズ
1372    DebugSectionHeader.PointerToRawData=        FilePos_DebugSection;   //ファイル上の開始アドレス
1373    DebugSectionHeader.PointerToRelocations=    0;
1374    DebugSectionHeader.PointerToLinenumbers=    0;
1375    DebugSectionHeader.NumberOfRelocations=     0;
1376    DebugSectionHeader.NumberOfLinenumbers=     0;
1377    DebugSectionHeader.Characteristics=         IMAGE_SCN_MEM_DISCARDABLE|
1378                                                IMAGE_SCN_MEM_READ;
1379
1380
1381    hFile=CreateFile(OutputFileName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1382    if(hFile==INVALID_HANDLE_VALUE){
1383        SetError(53,OutputFileName,-1);
1384        goto EndWriteOpcode;
1385    }
1386
1387    //ヘッダ
1388    WriteFile(hFile,(void *)&ImageDosHeader,sizeof(IMAGE_DOS_HEADER),(DWORD *)&i2,NULL);
1389    i=i2;
1390
1391    //Dosスタブ
1392    WriteFile(hFile,DosStubBuffer,DosStubSize,(DWORD *)&i2,NULL);
1393    i+=i2;
1394
1395    //0x0100までNULLを並べる
1396    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,0x0100-i);
1397    WriteFile(hFile,temp2,0x0100-i,(DWORD *)&i2,NULL);
1398    HeapDefaultFree(temp2);
1399    i+=i2;
1400
1401    //PEヘッダ
1402    WriteFile(hFile,&ImagePeHdr,sizeof(IMAGE_NT_HEADERS64),(DWORD *)&i2,NULL);
1403    i+=i2;
1404
1405    //コード セクション ヘッダ
1406    WriteFile(hFile,&CodeSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1407    i+=i2;
1408
1409    if(bUse_ExportSection){
1410        //エクスポート セクション ヘッダ
1411        WriteFile(hFile,&ExportSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1412        i+=i2;
1413    }
1414    if(bUse_ImportSection){
1415        //インポート セクション ヘッダ
1416        WriteFile(hFile,&ImportSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1417        i+=i2;
1418    }
1419    if(bUse_DataSection){
1420        //データ セクション ヘッダ
1421        WriteFile(hFile,&DataSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1422        i+=i2;
1423    }
1424    if(bUse_RWSection){
1425        //リライタブルセクションヘッダ
1426        WriteFile(hFile,&RWSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1427        i+=i2;
1428    }
1429    if(bUse_RSrcSection){
1430        //リソースセクションヘッダ
1431        WriteFile(hFile,&RSrcSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1432        i+=i2;
1433    }
1434    if(bUse_RelocSection){
1435        //リロケーションセクションヘッダ
1436        WriteFile(hFile,&RelocSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1437        i+=i2;
1438    }
1439    if(bUse_DebugSection){
1440        //デバッグセクションヘッダ
1441        WriteFile(hFile,&DebugSectionHeader,sizeof(IMAGE_SECTION_HEADER),(DWORD *)&i2,NULL);
1442        i+=i2;
1443    }
1444
1445    //EXE_HEADER_SIZEまでNULLを並べる
1446    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,EXE_HEADER_SIZE-i);
1447    WriteFile(hFile,temp2,EXE_HEADER_SIZE-i,(DWORD *)&i2,NULL);
1448    HeapDefaultFree(temp2);
1449    i+=i2;
1450
1451    //コード
1452    WriteFile(
1453        hFile,
1454        compiler.linker.GetNativeCode().GetBuffer(),
1455        compiler.linker.GetNativeCode().GetSize(),
1456        (DWORD *)&i2,
1457        NULL
1458    );
1459    i+=i2;
1460
1461    //FilePos_ExportSectionまでNULLを並べる
1462    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_ExportSection-i);
1463    WriteFile(hFile,temp2,FilePos_ExportSection-i,(DWORD *)&i2,NULL);
1464    HeapDefaultFree(temp2);
1465    i+=i2;
1466
1467    if(bUse_ExportSection){
1468        //エクスポート ディレクトリ テーブル
1469        WriteFile(hFile,&ImageExportDirectory,sizeof(IMAGE_EXPORT_DIRECTORY),(DWORD *)&i2,NULL);
1470        i+=i2;
1471
1472        //エクスポート アドレス テーブル
1473        WriteFile(hFile,lpdwExportAddressTable,ExportNum*sizeof(DWORD),(DWORD *)&i2,NULL);
1474        i+=i2;
1475
1476        //エクスポート名ポインタ テーブル
1477        WriteFile(hFile,lpdwExportNamePointerTable,ExportNum*sizeof(DWORD),(DWORD *)&i2,NULL);
1478        i+=i2;
1479
1480        //エクスポート序数テーブル
1481        WriteFile(hFile,lpwExportOrdinalTable,ExportNum*sizeof(WORD),(DWORD *)&i2,NULL);
1482        i+=i2;
1483
1484        //シンボル名
1485        WriteFile(hFile,lpExportNames,ExportNamesLength,(DWORD *)&i2,NULL);
1486        i+=i2;
1487    }
1488
1489    //FilePos_ImportSectionまでNULLを並べる
1490    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_ImportSection-i);
1491    WriteFile(hFile,temp2,FilePos_ImportSection-i,(DWORD *)&i2,NULL);
1492    HeapDefaultFree(temp2);
1493    i+=i2;
1494
1495    if(bUse_ImportSection){
1496        //インポート アドレス テーブル
1497        WriteFile(hFile,pLookupTable,LookupSize,(DWORD *)&i2,NULL);
1498        i+=i2;
1499
1500        //ルックアップ テーブル
1501        WriteFile(hFile,pLookupTable,LookupSize,(DWORD *)&i2,NULL);
1502        i+=i2;
1503
1504        //インポート ディレクトリ テーブル(Nullディレクトリ テーブルを含む)
1505        for(i3=0;i3<(ImportDllNum+1);i3++){
1506            WriteFile(hFile,&pImportDescriptor[i3],sizeof(IMAGE_IMPORT_DESCRIPTOR),(DWORD *)&i2,NULL);
1507            i+=i2;
1508        }
1509
1510        //DLL名
1511        for(i3=0;i3<ImportDllNum;i3++){
1512            WriteFile(hFile,ppDllNames[i3],16,(DWORD *)&i2,NULL);
1513            i+=i2;
1514        }
1515
1516        //ヒント テーブル
1517        WriteFile(hFile,pHintTable,HintSize,(DWORD *)&i2,NULL);
1518        i+=i2;
1519    }
1520
1521    //FilePos_DataSectionまでNULLを並べる
1522    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_DataSection-i);
1523    WriteFile(hFile,temp2,FilePos_DataSection-i,(DWORD *)&i2,NULL);
1524    HeapDefaultFree(temp2);
1525    i+=i2;
1526
1527    if(bUse_DataSection){
1528        //データ テーブル
1529        WriteFile(hFile,compiler.GetObjectModule().dataTable.GetPtr(),compiler.GetObjectModule().dataTable.GetSize(),(DWORD *)&i2,NULL);
1530        i+=i2;
1531    }
1532
1533    //FilePos_RWSectionまでNULLを並べる
1534    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_RWSection-i);
1535    WriteFile(hFile,temp2,FilePos_RWSection-i,(DWORD *)&i2,NULL);
1536    HeapDefaultFree(temp2);
1537    i+=i2;
1538
1539    if(bUse_RWSection){
1540        //リライタブル データ テーブル(グローバル変数の初期バッファ)
1541        char *temp = (char *)calloc( FileSize_RWSection, 1 );
1542        memcpy(
1543            temp,
1544            compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetBuffer(),
1545            compiler.GetObjectModule().meta.GetGlobalVars().initAreaBuffer.GetSize()
1546        );
1547
1548        WriteFile(hFile,temp,FileSize_RWSection,(DWORD *)&i2,NULL);
1549        i+=i2;
1550
1551        free( temp );
1552    }
1553
1554    //FilePos_RSrcSectionまでNULLを並べる
1555    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_RSrcSection-i);
1556    WriteFile(hFile,temp2,FilePos_RSrcSection-i,(DWORD *)&i2,NULL);
1557    HeapDefaultFree(temp2);
1558    i+=i2;
1559
1560    if(bUse_RSrcSection){
1561        //リソースバッファ
1562        WriteFile(hFile,RSrcSectionBuffer,RSrcSectionSize,(DWORD *)&i2,NULL);
1563        i+=i2;
1564    }
1565
1566    //FilePos_RelocSectionまでNULLを並べる
1567    temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FilePos_RelocSection-i);
1568    WriteFile(hFile,temp2,FilePos_RelocSection-i,(DWORD *)&i2,NULL);
1569    HeapDefaultFree(temp2);
1570    i+=i2;
1571
1572    if(bUse_RelocSection){
1573        //リロケーション情報
1574        WriteFile(hFile,pobj_Reloc->buffer,pobj_Reloc->length,(DWORD *)&i2,NULL);
1575        i+=i2;
1576    }
1577
1578    //ファイルアラインメントを考慮
1579    if(i%FILE_ALIGNMENT){
1580        temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FILE_ALIGNMENT-i%FILE_ALIGNMENT);
1581        WriteFile(hFile,temp2,FILE_ALIGNMENT-i%FILE_ALIGNMENT,(DWORD *)&i2,NULL);
1582        HeapDefaultFree(temp2);
1583        i+=i2;
1584    }
1585
1586    if(bUse_DebugSection){
1587        //デバッグセクション
1588        WriteFile(hFile,pobj_DebugSection->buffer,pobj_DebugSection->length,(DWORD *)&i2,NULL);
1589        i+=i2;
1590    }
1591
1592    //ファイルアラインメントを考慮
1593    if(i%FILE_ALIGNMENT){
1594        temp2=(char *)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,FILE_ALIGNMENT-i%FILE_ALIGNMENT);
1595        WriteFile(hFile,temp2,FILE_ALIGNMENT-i%FILE_ALIGNMENT,(DWORD *)&i2,NULL);
1596        HeapDefaultFree(temp2);
1597        i+=i2;
1598    }
1599
1600    //書き込み終了
1601    CloseHandle(hFile);
1602
1603
1604EndWriteOpcode:
1605
1606    //Dosスタブ用のメモリを解放
1607    HeapDefaultFree(DosStubBuffer);
1608
1609    //エクスポート テーブル情報を解放
1610    HeapDefaultFree(lpdwExportAddressTable);
1611    HeapDefaultFree(lpdwExportNamePointerTable);
1612    HeapDefaultFree(lpwExportOrdinalTable);
1613
1614    //インポートDLL情報を解放
1615    HeapDefaultFree(pImportDescriptor);
1616    for(i=0;i<ImportDllNum;i++)
1617        HeapDefaultFree(ppDllNames[i]);
1618    HeapDefaultFree(ppDllNames);
1619
1620    //ルックアップテーブルに関する情報を解放
1621    HeapDefaultFree(pLookupTable);
1622
1623    //ヒントテーブルに関する情報を解放
1624    HeapDefaultFree(pHintTable);
1625
1626    //リソースセクションバッファを解放
1627    HeapDefaultFree(RSrcSectionBuffer);
1628
1629    //デバッグセクションを開放
1630    delete pobj_DebugSection;
1631
1632    //リロケーション情報を解放
1633    delete pobj_Reloc;
1634
1635    //列挙体に関する情報の破棄
1636    CEnumParent::DestroyEnum();
1637
1638    //クラスに関するメモリを解放
1639    compiler.GetObjectModule().meta.GetClasses().Clear();
1640}
Note: See TracBrowser for help on using the repository browser.