Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ictool.cs « ictool « tools « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9b4e0dd44729a6dad5ed973368749b12524d2f37 (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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//
// file:	ictool.cs
// author:	Dan Lewis (dihlewis@yahoo.co.uk)
// 		(C) 2002
//
// description:
//
// Tool for generating C prototypes and structures suitable for use by the runtime
// from a list of supplied assemblies. See ictool-config.xml for configuration details.
//

using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Collections;

public class ICTool {
	public static void Main (string[] args) {
		string filename = "ictool-config.xml";
		if (args.Length == 1) {
			filename = args[0];
		}
		else if (args.Length > 1) {
			Console.Error.WriteLine ("Usage: ictool.exe [config.xml]");
			Environment.Exit (-1);
		}

		try {
			Stream config = File.OpenRead (filename);
			Configure (config);
		}
		catch (Exception e) {
			Console.Error.WriteLine ("Error: could not read configuration file.");
			Console.Error.WriteLine (e);
			Environment.Exit (-1);
		}

		EmitPrototypes ();
		EmitStructures ();
	}

	// private

	private static void EmitPrototypes () {
		StreamWriter methods_file = GetOutputFile ("methods");
		StreamWriter map_file = GetOutputFile ("map");

		// includes

		methods_file.WriteLine ("#include \"{0}\"\n", output_files["types"]);
		map_file.WriteLine ("#include \"{0}\"\n", output_files["methods"]);

		map_file.Write (
			"static gpointer icall_map [] = {\n\t"
		);

		ArrayList map_lines = new ArrayList ();

		BindingFlags binding =
			BindingFlags.DeclaredOnly |
			BindingFlags.Instance |
			BindingFlags.Static |
			BindingFlags.Public |
			BindingFlags.NonPublic;

		foreach (Type type in types.Values) {
			bool has_icall = false;
			MethodInfo[] methods = type.GetMethods (binding);

			foreach (MethodInfo method in methods) {
				if (IsInternalCall (method)) {
					has_icall = true;
					break;
				}
			}

			if (!has_icall)
				continue;

			methods_file.WriteLine ("\n/* {0} */\n", type.FullName);
			//map_lines.Add (String.Format ("\n/* {0} */\n", type.FullName));
			
			foreach (MethodInfo method in methods) {
				if (!IsInternalCall (method))
					continue;

				// function name

				string func_name = String.Format ("ves_icall_{0}_{1}",
					
					type.FullName,
					method.Name
				);

				func_name = func_name.Replace ('.', '_');

				// map file

				map_lines.Add (String.Format (
					"\"{0}::{1}\", {2}",

					type.FullName.Replace ('.', '_'),
					method.Name,
					func_name
				));

				// methods file

				ArrayList args = new ArrayList ();

				// FIXME: return types that are structs need to be inserted
				// into the argument list as a destination pointer

				// object/value instance pointer
				
				if (IsInstanceMethod (method)) {
					args.Add (String.Format (
						"{0}{1}",

						peer_map.GetPeer (method.DeclaringType).GetTypedef (1),
						"this"
					));
				}

				// arguments

				foreach (ParameterInfo param in method.GetParameters ()) {
					Type arg_type = param.ParameterType;

					int refs = 0;
					if (arg_type.IsByRef) {
						arg_type = arg_type.GetElementType ();
						++ refs;
					}

					Peer arg_peer = peer_map.GetPeer (arg_type);
					if (!arg_peer.IsValueType)
						++ refs;

					args.Add (String.Format ("{0}{1}", arg_peer.GetTypedef (refs), param.Name));
				}

				Peer ret = peer_map.GetPeer (method.ReturnType);
				methods_file.WriteLine ("static {0}", ret.GetTypedef (ret.IsValueType ? 0 : 1));
				methods_file.WriteLine ("{0} ({1});",
					
					func_name,
					Join (", ", args)
				);
				methods_file.WriteLine ();
			}

		}

		methods_file.Close ();

		// write map file and close it

		map_file.Write (
			"{0}\n}};\n", Join (",\n\t", map_lines)
		);

		map_file.Close ();
	}

	private static bool IsInternalCall (MethodInfo meth) {
		return (meth.GetMethodImplementationFlags () & MethodImplAttributes.InternalCall) != 0;
	}

	private static bool IsInstanceMethod (MethodInfo meth) {
		return (meth.CallingConvention & CallingConventions.HasThis) != 0;
	}

	private static void EmitStructures () {
		StreamWriter file = GetOutputFile ("types");

		// build dependency graph
		
		DependencyGraph dg = new DependencyGraph ();
		foreach (Peer peer in peer_map.Peers) {
			dg.AddNode (peer);

			// peer depends on nearest base

			if (peer.NearestBase != null)
				dg.AddEdge (peer.NearestBase, peer);

			// peer depends on any value types used for fields

			foreach (PeerField field in peer.Fields) {
				if (field.Peer.IsValueType)
					dg.AddEdge (field.Peer, peer);
			}
		}

		// write structures in order

		foreach (Peer peer in dg.TopologicalSort ()) {
			if (peer.IsOpaque)
				continue;

			if (peer.IsEnum) {
				file.WriteLine ("typedef {0} {1};", peer.UnderlyingPeer.Name, peer.Name);
				file.WriteLine ("enum _{0} {{", peer.Name);

				ArrayList enum_lines = new ArrayList ();
				foreach (string name in peer.EnumConstants.Keys) {
					enum_lines.Add (String.Format ("\t{0}_{1} = {2}",
						peer.Name,
						name,
						peer.EnumConstants[name]
					));
				}
				
				file.WriteLine ("{0}\n}};\n", Join (",\n", enum_lines));
			}
			else {
				file.WriteLine ("typedef struct _{0} {{", peer.Name);

				// base type
				
				if (peer.NearestBase != null) {
					file.WriteLine ("\t{0} __base;", peer.NearestBase.Name);
					file.WriteLine ();
				}

				// fields
				
				foreach (PeerField field in peer.Fields) {
					bool use_struct = true;
					if (field.Peer.IsValueType || field.Peer.IsOpaque)
						use_struct = false;
				
					file.WriteLine ("\t{0}{1}{2};",
						use_struct ? "struct _" : "",
						field.Peer.GetTypedef (field.Peer.IsValueType ? 0 : 1),
						field.Name
					);
				}

				file.WriteLine ("}} {0};\n", peer.Name);
			}
		}
	}

	private static void LoadAssemblies () {
		types = new Hashtable ();

		foreach (string filename in assemblies) {
			Assembly assembly;

			// find assembly

			FileInfo info = null;
			foreach (string path in assembly_paths) {
				info = new FileInfo (Path.Combine (path, filename));
				if (info.Exists)
					break;
			}

			if (!info.Exists) {
				Console.Error.WriteLine ("Error: assembly {0} not found.", filename);
				Environment.Exit (-1);
			}

			// load assembly

			assembly = Assembly.LoadFrom (info.FullName);

			// load types

			ArrayList loaded_types;
			
			try {
				loaded_types = new ArrayList (assembly.GetTypes ());
			}
			catch (ReflectionTypeLoadException e) {
				loaded_types = new ArrayList ();
				foreach (Type type in e.Types) {
					if (type != null)
						loaded_types.Add (type);
				}

				foreach (Exception f in e.LoaderExceptions) {
					if (f is TypeLoadException) {
						Console.Error.WriteLine ("Warning: {0} could not be loaded from assembly {1}.",
							((TypeLoadException)f).TypeName,
							filename
						);
					}
					else
						Console.Error.WriteLine (f);
				}
			}

			// add to type dictionary

			foreach (Type type in loaded_types) {
				if (!types.Contains (type.FullName))
					types.Add (type.FullName, type);
			}
		}
	}

	private static void Configure (Stream input) {
		XmlDocument doc = new XmlDocument ();
		doc.Load (input);

		// assemblies

		assembly_paths = new ArrayList ();
		assembly_paths.Add (".");

		foreach (XmlNode node in doc.SelectNodes ("config/assemblypath")) {
			assembly_paths.Add (node.Attributes["path"].Value);
		}

		assemblies = new ArrayList ();
		foreach (XmlNode node in doc.SelectNodes ("config/assembly")) {
			assemblies.Add (node.Attributes["file"].Value);
		}

		LoadAssemblies ();

		// outputfiles

		output_path = ".";
		XmlNode path_node = doc.SelectSingleNode ("config/outputpath");
		if (path_node != null)
			output_path = path_node.Attributes["path"].Value;

		output_files = new Hashtable ();
		output_includes = new Hashtable ();
		foreach (XmlNode node in doc.SelectNodes ("config/outputfile")) {
			string name = node.Attributes["name"].Value;
			output_files.Add (name, node.Attributes["file"].Value);

			foreach (XmlNode child in node.ChildNodes) {
				if (child.Name == "include")
					output_includes[name] = child.InnerText;
			}
		}

		// typemap

		peer_map = new PeerMap ();
		foreach (XmlNode node in doc.SelectNodes ("config/typemap/namespace")) {
			string ns = node.Attributes["name"].Value;

			foreach (XmlNode child in node.ChildNodes) {
				if (child.Name == "type") {
					string name = child.Attributes["name"].Value;
					string peer_name = child.Attributes["peer"].Value;

					bool opaque = false;
					if (child.Attributes["opaque"] != null && child.Attributes["opaque"].Value == "true")
						opaque = true;

					String fullname = String.Format ("{0}.{1}", ns, name);
					
					Type type;
					if (child.Attributes["default"] != null && child.Attributes["default"].Value == "true")
						type = Type.GetType (fullname);
					else
						type = (Type)types [fullname];

					if (type != null)
						peer_map.Add (new Peer (type, peer_name, opaque));
				}
			}
		}

		peer_map.ResolvePeers ();
	}

	private static StreamWriter GetOutputFile (string name) {
		string filename = Path.Combine (output_path, (string)output_files[name]);
		StreamWriter file = File.CreateText (filename);
		file.AutoFlush = true;

		file.Write (

// (verbatim string)
		
@"/**
 *  {0}
 *
 *  This file was automatically generated on {1} by ictool.exe from
 *  the following assemblies:
 *    {2}
 */
 
",

			output_files[name],
			DateTime.Now.ToString ("d"),
			Join (", ", assemblies)
		);

		if (output_includes.Contains (name)) {
			file.WriteLine (output_includes [name]);
			file.WriteLine ();
		}

		return file;
	}

	private static string Join (string separator, ICollection values) {
		// note to microsoft: please implement this in String :)

		string[] strs = new string[values.Count];

		int i = 0;
		foreach (object value in values)
			strs[i ++] = value.ToString ();

		return String.Join (separator, strs);
	}
	
	private static ArrayList assembly_paths;
	private static ArrayList assemblies;
	private static string output_path;
	private static Hashtable output_files;
	private static Hashtable output_includes;
	private static PeerMap peer_map;
	private static Hashtable types;
}