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

Last change on this file since 749 was 749, checked in by dai, 15 years ago

「フォルダを開く」コマンドで、ファイル選択を可能にした。

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