[Cleanup] Removed TARGET_JVM
[mono.git] / mcs / class / System / System.Diagnostics / DiagnosticsConfigurationHandler.cs
1 //
2 // System.Diagnostics.DiagnosticsConfigurationHandler.cs
3 //
4 // Comments from John R. Hicks <angryjohn69@nc.rr.com> original implementation 
5 // can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics
6 //
7 // Authors: 
8 //      John R. Hicks <angryjohn69@nc.rr.com>
9 //      Jonathan Pryor <jonpryor@vt.edu>
10 //
11 // (C) 2002, 2005
12 //
13
14 //
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
22 // 
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
25 // 
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 //
34 using System;
35 using System.Collections;
36 using System.Collections.Specialized;
37 using System.Configuration;
38 using System.Reflection;
39 using System.Threading;
40 #if (XML_DEP)
41 using System.Xml;
42 #endif
43 namespace System.Diagnostics
44 {
45         // It handles following elements in <system.diagnostics> :
46         //      - <sharedListeners> [2.0]
47         //      - <sources>
48         //              - <source>
49         //                      - <listeners> (collection)
50         //      - <switches>
51         //              - <add name=string value=string />
52         //      - <trace autoflush=bool indentsize=int useGlobalLock=bool>
53         //              - <listeners>
54         internal sealed class DiagnosticsConfiguration
55         {
56 #if NO_LOCK_FREE
57                 private static object lock_ = new object();
58 #endif
59                 private static object settings;
60
61                 public static IDictionary Settings {
62                         get {
63 #if !NO_LOCK_FREE
64                                 if (settings == null) {
65                                         object s = ConfigurationSettings.GetConfig ("system.diagnostics");
66                                         if (s == null)
67                                                 throw new Exception ("INTERNAL configuration error: failed to get configuration 'system.diagnostics'");
68                                         Thread.MemoryBarrier ();
69                                         while (Interlocked.CompareExchange (ref settings, s, null) == null) {
70                                                 // do nothing; we're just setting settings.
71                                         }
72                                         Thread.MemoryBarrier ();
73                                 }
74 #else
75                                 lock (lock_) {
76                                         if (settings == null)
77                                                 settings = ConfigurationSettings.GetConfig ("system.diagnostics");
78                                 }
79 #endif
80                                 return (IDictionary) settings;
81                         }
82                 }
83         }
84 #if (XML_DEP)
85         [Obsolete ("This class is obsoleted")]
86         public class DiagnosticsConfigurationHandler : IConfigurationSectionHandler
87         {
88                 TraceImplSettings configValues;
89
90                 delegate void ElementHandler (IDictionary d, XmlNode node);
91
92                 IDictionary elementHandlers = new Hashtable ();
93
94                 public DiagnosticsConfigurationHandler ()
95                 {
96                         elementHandlers ["assert"] = new ElementHandler (AddAssertNode);
97                         elementHandlers ["switches"] = new ElementHandler (AddSwitchesNode);
98                         elementHandlers ["trace"] = new ElementHandler (AddTraceNode);
99                         elementHandlers ["sources"] = new ElementHandler (AddSourcesNode);
100                 }
101
102                 public virtual object Create (object parent, object configContext, XmlNode section)
103                 {
104                         IDictionary d;
105                         if (parent == null)
106                                 d = new Hashtable (CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
107                         else
108                                 d = (IDictionary) ((ICloneable)parent).Clone();
109
110                         if (d.Contains (TraceImplSettings.Key))
111                                 configValues = (TraceImplSettings) d [TraceImplSettings.Key];
112                         else
113                                 d.Add (TraceImplSettings.Key, configValues = new TraceImplSettings ());
114
115                         // process <sharedListeners> first
116                         foreach (XmlNode child in section.ChildNodes) {
117                                 switch (child.NodeType) {
118                                 case XmlNodeType.Element:
119                                         if (child.LocalName != "sharedListeners")
120                                                 continue;
121                                         AddTraceListeners (d, child, GetSharedListeners (d));
122                                         break;
123                                 }
124                         }
125
126                         foreach (XmlNode child in section.ChildNodes) {
127                                 XmlNodeType type = child.NodeType;
128
129                                 switch (type) {
130                                 /* ignore */
131                                 case XmlNodeType.Whitespace:
132                                 case XmlNodeType.Comment:
133                                         continue;
134                                 case XmlNodeType.Element:
135                                         if (child.LocalName == "sharedListeners")
136                                                 continue;
137                                         ElementHandler eh = (ElementHandler) elementHandlers [child.Name];
138                                         if (eh != null)
139                                                 eh (d, child);
140                                         else
141                                                 ThrowUnrecognizedElement (child);
142                                         break;
143                                 default:
144                                         ThrowUnrecognizedElement (child);
145                                         break;
146                                 }
147                         }
148
149                         return d;
150                 }
151
152                 // Remarks: Both attribute are optional
153                 private void AddAssertNode (IDictionary d, XmlNode node)
154                 {
155                         XmlAttributeCollection c = node.Attributes;
156                         string assertuienabled = GetAttribute (c, "assertuienabled", false, node);
157                         string logfilename = GetAttribute (c, "logfilename", false, node);
158                         ValidateInvalidAttributes (c, node);
159                         if (assertuienabled != null) {
160                                 try {
161                                         d ["assertuienabled"] = bool.Parse (assertuienabled);
162                                 }
163                                 catch (Exception e) {
164                                         throw new ConfigurationException ("The `assertuienabled' attribute must be `true' or `false'",
165                                                         e, node);
166                                 }
167                         }
168
169                         if (logfilename != null)
170                                 d ["logfilename"] = logfilename;
171
172                         DefaultTraceListener dtl = (DefaultTraceListener) configValues.Listeners["Default"];
173                         if (dtl != null) {
174                                 if (assertuienabled != null)
175                                         dtl.AssertUiEnabled = (bool) d ["assertuienabled"];
176                                 if (logfilename != null)
177                                         dtl.LogFileName = logfilename;
178                         }
179
180                         if (node.ChildNodes.Count > 0)
181                                 ThrowUnrecognizedElement (node.ChildNodes[0]);
182                 }
183
184                 // name and value attributes are required
185                 // Docs do not define "remove" or "clear" elements, but .NET recognizes
186                 // them
187                 private void AddSwitchesNode (IDictionary d, XmlNode node)
188                 {
189                         // There are no attributes on <switch/>
190                         ValidateInvalidAttributes (node.Attributes, node);
191
192                         IDictionary newNodes = new Hashtable ();
193
194                         foreach (XmlNode child in node.ChildNodes) {
195                                 XmlNodeType t = child.NodeType;
196                                 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
197                                         continue;
198                                 if (t == XmlNodeType.Element) {
199                                         XmlAttributeCollection attributes = child.Attributes;
200                                         string name = null;
201                                         string value = null;
202                                         switch (child.Name) {
203                                                 case "add":
204                                                         name = GetAttribute (attributes, "name", true, child);
205                                                         value = GetAttribute (attributes, "value", true, child);
206                                                         newNodes [name] = GetSwitchValue (name, value);
207                                                         break;
208                                                 case "remove":
209                                                         name = GetAttribute (attributes, "name", true, child);
210                                                         newNodes.Remove (name);
211                                                         break;
212                                                 case "clear":
213                                                         newNodes.Clear ();
214                                                         break;
215                                                 default:
216                                                         ThrowUnrecognizedElement (child);
217                                                         break;
218                                         }
219                                         ValidateInvalidAttributes (attributes, child);
220                                 }
221                                 else
222                                         ThrowUnrecognizedNode (child);
223                         }
224
225                         d [node.Name] = newNodes;
226                 }
227
228                 private static object GetSwitchValue (string name, string value)
229                 {
230                         return value;
231                 }
232
233                 private void AddTraceNode (IDictionary d, XmlNode node)
234                 {
235                         AddTraceAttributes (d, node);
236
237                         foreach (XmlNode child in node.ChildNodes) {
238                                 XmlNodeType t = child.NodeType;
239                                 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
240                                         continue;
241                                 if (t == XmlNodeType.Element) {
242                                         if (child.Name == "listeners")
243                                                 AddTraceListeners (d, child, configValues.Listeners);
244                                         else
245                                                 ThrowUnrecognizedElement (child);
246                                         ValidateInvalidAttributes (child.Attributes, child);
247                                 }
248                                 else
249                                         ThrowUnrecognizedNode (child);
250                         }
251                 }
252
253                 // all attributes are optional
254                 private void AddTraceAttributes (IDictionary d, XmlNode node)
255                 {
256                         XmlAttributeCollection c = node.Attributes;
257                         string autoflushConf = GetAttribute (c, "autoflush", false, node);
258                         string indentsizeConf = GetAttribute (c, "indentsize", false, node);
259                         ValidateInvalidAttributes (c, node);
260                         if (autoflushConf != null) {
261                                 bool autoflush = false;
262                                 try {
263                                         autoflush = bool.Parse (autoflushConf);
264                                         d ["autoflush"] = autoflush;
265                                 } catch (Exception e) {
266                                         throw new ConfigurationException ("The `autoflush' attribute must be `true' or `false'",
267                                                         e, node);
268                                 }
269                                 configValues.AutoFlush = autoflush;
270                         }
271                         if (indentsizeConf != null) {
272                                 int indentsize = 0;
273                                 try {
274                                         indentsize = int.Parse (indentsizeConf);
275                                         d ["indentsize"] = indentsize;
276                                 } catch (Exception e) {
277                                         throw new ConfigurationException ("The `indentsize' attribute must be an integral value.",
278                                                         e, node);
279                                 }
280                                 configValues.IndentSize = indentsize;
281                         }
282                 }
283
284                 private TraceListenerCollection GetSharedListeners (IDictionary d)
285                 {
286                         TraceListenerCollection shared_listeners = d ["sharedListeners"] as TraceListenerCollection;
287                         if (shared_listeners == null) {
288                                 shared_listeners = new TraceListenerCollection (false);
289                                 d ["sharedListeners"] = shared_listeners;
290                         }
291                         return shared_listeners;
292                 }
293
294                 private void AddSourcesNode (IDictionary d, XmlNode node)
295                 {
296                         // FIXME: are there valid attributes?
297                         ValidateInvalidAttributes (node.Attributes, node);
298                         Hashtable sources = d ["sources"] as Hashtable;
299                         if (sources == null) {
300                                 sources = new Hashtable ();
301                                 d ["sources"] = sources;
302                         }
303
304                         foreach (XmlNode child in node.ChildNodes) {
305                                 XmlNodeType t = child.NodeType;
306                                 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
307                                         continue;
308                                 if (t == XmlNodeType.Element) {
309                                         if (child.Name == "source")
310                                                 AddTraceSource (d, sources, child);
311                                         else
312                                                 ThrowUnrecognizedElement (child);
313 //                                      ValidateInvalidAttributes (child.Attributes, child);
314                                 }
315                                 else
316                                         ThrowUnrecognizedNode (child);
317                         }
318                 }
319
320                 private void AddTraceSource (IDictionary d, Hashtable sources, XmlNode node)
321                 {
322                         string name = null;
323                         SourceLevels levels = SourceLevels.Error;
324                         StringDictionary atts = new StringDictionary ();
325                         foreach (XmlAttribute a in node.Attributes) {
326                                 switch (a.Name) {
327                                 case "name":
328                                         name = a.Value;
329                                         break;
330                                 case "switchValue":
331                                         levels = (SourceLevels) Enum.Parse (typeof (SourceLevels), a.Value);
332                                         break;
333                                 default:
334                                         atts [a.Name] = a.Value;
335                                         break;
336                                 }
337                         }
338                         if (name == null)
339                                 throw new ConfigurationException ("Mandatory attribute 'name' is missing in 'source' element.");
340
341                         // ignore duplicate ones (no error occurs)
342                         if (sources.ContainsKey (name))
343                                 return;
344
345                         TraceSourceInfo sinfo = new TraceSourceInfo (name, levels, configValues);
346                         sources.Add (sinfo.Name, sinfo);
347                         
348                         foreach (XmlNode child in node.ChildNodes) {
349                                 XmlNodeType t = child.NodeType;
350                                 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
351                                         continue;
352                                 if (t == XmlNodeType.Element) {
353                                         if (child.Name == "listeners")
354                                                 AddTraceListeners (d, child, sinfo.Listeners);
355                                         else
356                                                 ThrowUnrecognizedElement (child);
357                                         ValidateInvalidAttributes (child.Attributes, child);
358                                 }
359                                 else
360                                         ThrowUnrecognizedNode (child);
361                         }
362                 }
363
364                 // only defines "add" and "remove", but "clear" also works
365                 // for add, "name" is required; initializeData is optional; "type" is required in 1.x, optional in 2.0.
366                 private void AddTraceListeners (IDictionary d, XmlNode listenersNode, TraceListenerCollection listeners)
367                 {
368                         // There are no attributes on <listeners/>
369                         ValidateInvalidAttributes (listenersNode.Attributes, listenersNode);
370
371                         foreach (XmlNode child in listenersNode.ChildNodes) {
372                                 XmlNodeType t = child.NodeType;
373                                 if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
374                                         continue;
375                                 if (t == XmlNodeType.Element) {
376                                         XmlAttributeCollection attributes = child.Attributes;
377                                         string name = null;
378                                         switch (child.Name) {
379                                                 case "add":
380                                                         AddTraceListener (d, child, attributes, listeners);
381                                                         break;
382                                                 case "remove":
383                                                         name = GetAttribute (attributes, "name", true, child);
384                                                         RemoveTraceListener (name);
385                                                         break;
386                                                 case "clear":
387                                                         configValues.Listeners.Clear ();
388                                                         break;
389                                                 default:
390                                                         ThrowUnrecognizedElement (child);
391                                                         break;
392                                         }
393                                         ValidateInvalidAttributes (attributes, child);
394                                 }
395                                 else
396                                         ThrowUnrecognizedNode (child);
397                         }
398                 }
399
400                 private void AddTraceListener (IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
401                 {
402                         string name = GetAttribute (attributes, "name", true, child);
403                         string type = null;
404
405 #if CONFIGURATION_DEP
406                         type = GetAttribute (attributes, "type", false, child);
407                         if (type == null) {
408                                 // indicated by name.
409                                 TraceListener shared = GetSharedListeners (d) [name];
410                                 if (shared == null)
411                                         throw new ConfigurationException (String.Format ("Shared trace listener {0} does not exist.", name));
412                                 if (attributes.Count != 0)
413                                         throw new ConfigurationErrorsException (string.Format (
414                                                 "Listener '{0}' references a shared " +
415                                                 "listener and can only have a 'Name' " +
416                                                 "attribute.", name));
417                                 listeners.Add (shared, configValues);
418                                 return;
419                         }
420 #else
421                         type = GetAttribute (attributes, "type", true, child);
422 #endif
423
424                         Type t = Type.GetType (type);
425                         if (t == null)
426                                 throw new ConfigurationException (string.Format ("Invalid Type Specified: {0}", type));
427
428                         object[] args;
429                         Type[] types;
430
431                         string initializeData = GetAttribute (attributes, "initializeData", false, child);
432                         if (initializeData != null) {
433                                 args = new object[] { initializeData };
434                                 types = new Type[] { typeof(string) };
435                         } else {
436                                 args = null;
437                                 types = Type.EmptyTypes;
438                         }
439
440                         BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
441                         if (t.Assembly == GetType ().Assembly)
442                                 flags |= BindingFlags.NonPublic;
443
444                         ConstructorInfo ctor = t.GetConstructor (flags, null, types, null);
445                         if (ctor == null) 
446                                 throw new ConfigurationException ("Couldn't find constructor for class " + type);
447                         
448                         TraceListener l = (TraceListener) ctor.Invoke (args);
449                         l.Name = name;
450
451 #if CONFIGURATION_DEP
452                         string trace = GetAttribute (attributes, "traceOutputOptions", false, child);
453                         if (trace != null) {
454                                 if (trace != trace.Trim ())
455                                         throw new ConfigurationErrorsException (string.Format (
456                                                 "Invalid value '{0}' for 'traceOutputOptions'.",
457                                                 trace), child);
458
459                                 TraceOptions trace_options;
460         
461                                 try {
462                                         trace_options = (TraceOptions) Enum.Parse (
463                                                 typeof (TraceOptions), trace);
464                                 } catch (ArgumentException) {
465                                         throw new ConfigurationErrorsException (string.Format (
466                                                 "Invalid value '{0}' for 'traceOutputOptions'.",
467                                                 trace), child);
468                                 }
469
470                                 l.TraceOutputOptions = trace_options;
471                         }
472
473                         string [] supported_attributes = l.GetSupportedAttributes ();
474                         if (supported_attributes != null) {
475                                 for (int i = 0; i < supported_attributes.Length; i++) {
476                                         string key = supported_attributes [i];
477                                         string value = GetAttribute (attributes, key, false, child);
478                                         if (value != null)
479                                                 l.Attributes.Add (key, value);
480                                 }
481                         }
482 #endif
483
484                         listeners.Add (l, configValues);
485                 }
486
487                 private void RemoveTraceListener (string name)
488                 {
489                         try {
490                                 configValues.Listeners.Remove (name);
491                         }
492                         catch (ArgumentException) {
493                                 // The specified listener wasn't in the collection
494                                 // Ignore this; .NET does.
495                         }
496                         catch (Exception e) {
497                                 throw new ConfigurationException (
498                                                 string.Format ("Unknown error removing listener: {0}", name),
499                                                 e);
500                         }
501                 }
502
503                 private string GetAttribute (XmlAttributeCollection attrs, string attr, bool required, XmlNode node)
504                 {
505                         XmlAttribute a = attrs[attr];
506
507                         string r = null;
508
509                         if (a != null) {
510                                 r = a.Value;
511                                 if (required)
512                                         ValidateAttribute (attr, r, node);
513                                 attrs.Remove (a);
514                         }
515                         else if (required)
516                                 ThrowMissingAttribute (attr, node);
517
518                         return r;
519                 }
520
521                 private void ValidateAttribute (string attribute, string value, XmlNode node)
522                 {
523                         if (value == null || value.Length == 0)
524                                 throw new ConfigurationException (string.Format ("Required attribute '{0}' cannot be empty.", attribute), node);
525                 }
526
527                 private void ValidateInvalidAttributes (XmlAttributeCollection c, XmlNode node)
528                 {
529                         if (c.Count != 0)
530                                 ThrowUnrecognizedAttribute (c[0].Name, node);
531                 }
532
533                 private void ThrowMissingAttribute (string attribute, XmlNode node)
534                 {
535                         throw new ConfigurationException (string.Format ("Required attribute '{0}' not found.", attribute), node);
536                 }
537
538                 private void ThrowUnrecognizedNode (XmlNode node)
539                 {
540                         throw new ConfigurationException (
541                                         string.Format ("Unrecognized node `{0}'; nodeType={1}", node.Name, node.NodeType),
542                                         node);
543                 }
544
545                 private void ThrowUnrecognizedElement (XmlNode node)
546                 {
547                         throw new ConfigurationException (
548                                         string.Format ("Unrecognized element '{0}'.", node.Name),
549                                         node);
550                 }
551
552                 private void ThrowUnrecognizedAttribute (string attribute, XmlNode node)
553                 {
554                         throw new ConfigurationException (
555                                         string.Format ("Unrecognized attribute '{0}' on element <{1}/>.", attribute, node.Name),
556                                         node);
557                 }
558         }
559 #endif
560 }
561