source: dev/trunk/ab5.0/abdev/compiler_x86/MakePeHdr.cpp @ 636

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

libファイルを跨ったテンプレート展開に対応。

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