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

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

UserProcクラスによるコンパイル中関数管理用メソッドを除去(すべてCompilerクラス内で処理するようにした)。

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