aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Grid/ScriptEngine/DotNetEngine/Compiler/LSO/Engine.cs
blob: f3f4beab2973b9b4726027e00b7324cb81b1b398 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of the OpenSim Project nor the
*       names of its contributors may be used to endorse or promote products
*       derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* 
*/
/* Original code: Tedd Hansen */
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading;

namespace OpenSim.Grid.ScriptEngine.DotNetEngine.Compiler.LSO
{
    public class Engine
    {
        //private string LSO_FileName = @"LSO\AdditionTest.lso";
        private string LSO_FileName; // = @"LSO\CloseToDefault.lso";
        private AppDomain appDomain;

        public string Compile(string LSOFileName)
        {
            LSO_FileName = LSOFileName;


            //appDomain = AppDomain.CreateDomain("AlternateAppDomain");
            appDomain = Thread.GetDomain();

            // Create Assembly Name
            AssemblyName asmName = new AssemblyName();
            asmName.Name = Path.GetFileNameWithoutExtension(LSO_FileName);
            //asmName.Name = "TestAssembly";

            string DLL_FileName = asmName.Name + ".dll";
            string DLL_FileName_WithPath = Path.GetDirectoryName(LSO_FileName) + @"\" + DLL_FileName;

            Common.SendToLog("LSO File Name: " + Path.GetFileName(LSO_FileName));
            Common.SendToLog("Assembly name: " + asmName.Name);
            Common.SendToLog("Assembly File Name: " + asmName.Name + ".dll");
            Common.SendToLog("Starting processing of LSL ByteCode...");
            Common.SendToLog("");


            // Create Assembly
            AssemblyBuilder asmBuilder = appDomain.DefineDynamicAssembly(
                asmName,
                AssemblyBuilderAccess.RunAndSave
                );
            //// Create Assembly
            //AssemblyBuilder asmBuilder =
            //    Thread.GetDomain().DefineDynamicAssembly
            //(asmName, AssemblyBuilderAccess.RunAndSave);

            // Create a module (and save to disk)
            ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule
                (asmName.Name,
                 DLL_FileName);

            //Common.SendToDebug("asmName.Name is still \"" + asmName.Name + "\"");
            // Create a Class (/Type)
            TypeBuilder typeBuilder = modBuilder.DefineType(
                "LSL_ScriptObject",
                TypeAttributes.Public | TypeAttributes.BeforeFieldInit,
                typeof (LSL_BaseClass));
            //,
            //                        typeof());
            //, typeof(LSL_BuiltIn_Commands_Interface));
            //,
            //                        typeof(object),
            //                        new Type[] { typeof(LSL_CLRInterface.LSLScript) });


            /*
             * Generate the IL itself
             */

            LSO_Parser LSOP = new LSO_Parser(LSO_FileName, typeBuilder);
            LSOP.OpenFile();
            LSOP.Parse();

            // Constructor has to be created AFTER LSO_Parser because of accumulated variables
            if (Common.IL_CreateConstructor)
                IL_CREATE_CONSTRUCTOR(typeBuilder, LSOP);

            LSOP.CloseFile();
            /*
             * Done generating. Create a type and run it.
             */


            Common.SendToLog("Attempting to compile assembly...");
            // Compile it
            Type type = typeBuilder.CreateType();
            Common.SendToLog("Compilation successful!");

            Common.SendToLog("Saving assembly: " + DLL_FileName);
            asmBuilder.Save(DLL_FileName);

            Common.SendToLog("Returning assembly filename: " + DLL_FileName);


            return DLL_FileName;


            //Common.SendToLog("Creating an instance of new assembly...");
            //// Create an instance we can play with
            ////LSLScript hello = (LSLScript)Activator.CreateInstance(type);
            ////LSL_CLRInterface.LSLScript MyScript = (LSL_CLRInterface.LSLScript)Activator.CreateInstance(type);
            //object MyScript = (object)Activator.CreateInstance(type);


            //System.Reflection.MemberInfo[] Members = type.GetMembers();

            //Common.SendToLog("Members of assembly " + type.ToString() + ":");
            //foreach (MemberInfo member in Members)
            //    Common.SendToLog(member.ToString());


            //// Play with it
            ////MyScript.event_state_entry("Test");
            //object[] args = { null };
            ////System.Collections.Generic.List<string> Functions = (System.Collections.Generic.List<string>)type.InvokeMember("GetFunctions", BindingFlags.InvokeMethod, null, MyScript, null);

            //string[] ret = { };
            //if (Common.IL_CreateFunctionList)
            //    ret = (string[])type.InvokeMember("GetFunctions", BindingFlags.InvokeMethod, null, MyScript, null);

            //foreach (string s in ret)
            //{
            //    Common.SendToLog("");
            //    Common.SendToLog("*** Executing LSL Server Event: " + s);
            //    //object test = type.GetMember(s);
            //    //object runner = type.InvokeMember(s, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, MyScript, args);
            //    //runner();
            //    //objBooks_Late = type.InvokeMember(s, BindingFlags.CreateInstance, null, objApp_Late, null);
            //    type.InvokeMember(s, BindingFlags.InvokeMethod, null, MyScript, new object[] { "Test" });

            //}
        }


        private static void IL_CREATE_CONSTRUCTOR(TypeBuilder typeBuilder, LSO_Parser LSOP)
        {
            Common.SendToDebug("IL_CREATE_CONSTRUCTOR()");
            //ConstructorBuilder constructor = typeBuilder.DefineConstructor(
            //            MethodAttributes.Public,
            //            CallingConventions.Standard, 
            //            new Type[0]);
            ConstructorBuilder constructor = typeBuilder.DefineConstructor(
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName,
                CallingConventions.Standard,
                new Type[0]);

            //Define the reflection ConstructorInfor for System.Object
            ConstructorInfo conObj = typeof (LSL_BaseClass).GetConstructor(new Type[0]);

            //call constructor of base object
            ILGenerator il = constructor.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, conObj);


            //Common.SendToDebug("IL_CREATE_CONSTRUCTOR: Creating global: UInt32 State = 0;");
            //string FieldName;
            //// Create state object
            //FieldName = "State";
            //FieldBuilder State_fb = typeBuilder.DefineField(
            //    FieldName, 
            //    typeof(UInt32), 
            //    FieldAttributes.Public);
            //il.Emit(OpCodes.Ldarg_0);
            //il.Emit(OpCodes.Ldc_I4, 0);
            //il.Emit(OpCodes.Stfld, State_fb);


            //Common.SendToDebug("IL_CREATE_CONSTRUCTOR: Creating global: LSL_BuiltIn_Commands_TestImplementation LSL_BuiltIns = New LSL_BuiltIn_Commands_TestImplementation();");
            ////Type objType1 = typeof(object);
            //Type objType1 = typeof(LSL_BuiltIn_Commands_TestImplementation);

            //FieldName = "LSL_BuiltIns";
            //FieldBuilder LSL_BuiltIns_fb = typeBuilder.DefineField(
            //    FieldName, 
            //    objType1, 
            //    FieldAttributes.Public);

            ////LSL_BuiltIn_Commands_TestImplementation _ti = new LSL_BuiltIn_Commands_TestImplementation();
            //il.Emit(OpCodes.Ldarg_0);
            ////il.Emit(OpCodes.Ldstr, "Test 123");
            //il.Emit(OpCodes.Newobj, objType1.GetConstructor(new Type[] { }));
            //il.Emit(OpCodes.Stfld, LSL_BuiltIns_fb);

            foreach (UInt32 pos in LSOP.StaticBlocks.Keys)
            {
                LSO_Struct.StaticBlock sb;
                LSOP.StaticBlocks.TryGetValue(pos, out sb);

                if (sb.ObjectType > 0 && sb.ObjectType < 8)
                {
                    // We don't want void or null's

                    il.Emit(OpCodes.Ldarg_0);
                    // Push position to stack
                    il.Emit(OpCodes.Ldc_I4, pos);
                    //il.Emit(OpCodes.Box, typeof(UInt32));


                    Type datatype = null;

                    // Push data to stack
                    Common.SendToDebug("Adding to static (" + pos + ") type: " +
                                       ((LSO_Enums.Variable_Type_Codes) sb.ObjectType).ToString() + " (" + sb.ObjectType +
                                       ")");
                    switch ((LSO_Enums.Variable_Type_Codes) sb.ObjectType)
                    {
                        case LSO_Enums.Variable_Type_Codes.Float:
                        case LSO_Enums.Variable_Type_Codes.Integer:
                            //UInt32
                            il.Emit(OpCodes.Ldc_I4, BitConverter.ToUInt32(sb.BlockVariable, 0));
                            datatype = typeof (UInt32);
                            il.Emit(OpCodes.Box, datatype);
                            break;
                        case LSO_Enums.Variable_Type_Codes.String:
                        case LSO_Enums.Variable_Type_Codes.Key:
                            //String
                            LSO_Struct.HeapBlock hb =
                                LSOP.GetHeap(LSOP.myHeader.HR + BitConverter.ToUInt32(sb.BlockVariable, 0) - 1);
                            il.Emit(OpCodes.Ldstr, Encoding.UTF8.GetString(hb.Data));
                            datatype = typeof (string);
                            break;
                        case LSO_Enums.Variable_Type_Codes.Vector:
                            datatype = typeof (LSO_Enums.Vector);
                            //TODO: Not implemented
                            break;
                        case LSO_Enums.Variable_Type_Codes.Rotation:
                            //Object
                            //TODO: Not implemented
                            datatype = typeof (LSO_Enums.Rotation);
                            break;
                        default:
                            datatype = typeof (object);
                            break;
                    }


                    // Make call
                    il.Emit(OpCodes.Call,
                            typeof (LSL_BaseClass).GetMethod("AddToStatic", new Type[] {typeof (UInt32), datatype}));
                }
            }


            ////il.Emit(OpCodes.Newobj, typeof(UInt32));
            //il.Emit(OpCodes.Starg_0);
            //// Create LSL function library
            //FieldBuilder LSL_BuiltIns_fb = typeBuilder.DefineField("LSL_BuiltIns", typeof(LSL_BuiltIn_Commands_Interface), FieldAttributes.Public);
            //il.Emit(OpCodes.Newobj, typeof(LSL_BuiltIn_Commands_Interface));
            //il.Emit(OpCodes.Stloc_1);

            il.Emit(OpCodes.Ret);
        }


        // End of class
    }
}