source: dev/trunk/ab5.0/abdev/compiler_x64/MakePeHdr.cpp @ 528

Last change on this file since 528 was 528, checked in by dai_9181, 15 years ago

[522][527]を64bit版にマージ。

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