VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/python/server/policy.py@ 59769

最後變更 在這個檔案從59769是 59769,由 vboxsync 提交於 9 年 前

PyXPCOM: port to make it compatible with Python 3 (minimum supported version is 2.6 like for all other Python files now)
Frontends/VBoxShell, Installer/common/vboxapisetup.py, Main/glue/vboxapi.py, Main/webservice/websrv-python.xsl: make it compatible with Python 3

  • 屬性 svn:eol-style 設為 native
檔案大小: 16.5 KB
 
1# ***** BEGIN LICENSE BLOCK *****
2# Version: MPL 1.1/GPL 2.0/LGPL 2.1
3#
4# The contents of this file are subject to the Mozilla Public License Version
5# 1.1 (the "License"); you may not use this file except in compliance with
6# the License. You may obtain a copy of the License at
7# http://www.mozilla.org/MPL/
8#
9# Software distributed under the License is distributed on an "AS IS" basis,
10# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11# for the specific language governing rights and limitations under the
12# License.
13#
14# The Original Code is Python XPCOM language bindings.
15#
16# The Initial Developer of the Original Code is
17# ActiveState Tool Corp.
18# Portions created by the Initial Developer are Copyright (C) 2001
19# the Initial Developer. All Rights Reserved.
20#
21# Contributor(s):
22# Mark Hammond <[email protected]> (original author)
23#
24# Alternatively, the contents of this file may be used under the terms of
25# either the GNU General Public License Version 2 or later (the "GPL"), or
26# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27# in which case the provisions of the GPL or the LGPL are applicable instead
28# of those above. If you wish to allow use of your version of this file only
29# under the terms of either the GPL or the LGPL, and not to allow others to
30# use your version of this file under the terms of the MPL, indicate your
31# decision by deleting the provisions above and replace them with the notice
32# and other provisions required by the GPL or the LGPL. If you do not delete
33# the provisions above, a recipient may use your version of this file under
34# the terms of any one of the MPL, the GPL or the LGPL.
35#
36# ***** END LICENSE BLOCK *****
37
38from xpcom import xpcom_consts, _xpcom, client, nsError, logger
39from xpcom import ServerException, COMException
40import xpcom
41import xpcom.server
42import operator
43import types
44import logging
45import sys
46
47
48IID_nsISupports = _xpcom.IID_nsISupports
49IID_nsIVariant = _xpcom.IID_nsIVariant
50XPT_MD_IS_GETTER = xpcom_consts.XPT_MD_IS_GETTER
51XPT_MD_IS_SETTER = xpcom_consts.XPT_MD_IS_SETTER
52
53VARIANT_INT_TYPES = xpcom_consts.VTYPE_INT8, xpcom_consts.VTYPE_INT16, xpcom_consts.VTYPE_INT32, \
54 xpcom_consts.VTYPE_UINT8, xpcom_consts.VTYPE_UINT16, xpcom_consts.VTYPE_INT32
55VARIANT_LONG_TYPES = xpcom_consts.VTYPE_INT64, xpcom_consts.VTYPE_UINT64
56VARIANT_FLOAT_TYPES = xpcom_consts.VTYPE_FLOAT, xpcom_consts.VTYPE_DOUBLE
57VARIANT_STRING_TYPES = xpcom_consts.VTYPE_CHAR, xpcom_consts.VTYPE_CHAR_STR, xpcom_consts.VTYPE_STRING_SIZE_IS, \
58 xpcom_consts.VTYPE_CSTRING
59VARIANT_UNICODE_TYPES = xpcom_consts.VTYPE_WCHAR, xpcom_consts.VTYPE_DOMSTRING, xpcom_consts.VTYPE_WSTRING_SIZE_IS, \
60 xpcom_consts.VTYPE_ASTRING
61
62_supports_primitives_map_ = {} # Filled on first use.
63
64_interface_sequence_types_ = tuple, list
65if sys.version_info[0] <= 2:
66 _string_types_ = str, unicode
67else:
68 _string_types_ = bytes, str
69XPTI_GetInterfaceInfoManager = _xpcom.XPTI_GetInterfaceInfoManager
70
71def _GetNominatedInterfaces(obj):
72 ret = getattr(obj, "_com_interfaces_", None)
73 if ret is None: return None
74 # See if the user only gave one.
75 if type(ret) not in _interface_sequence_types_:
76 ret = [ret]
77 real_ret = []
78 # For each interface, walk to the root of the interface tree.
79 iim = XPTI_GetInterfaceInfoManager()
80 for interface in ret:
81 # Allow interface name or IID.
82 interface_info = None
83 if type(interface) in _string_types_:
84 try:
85 interface_info = iim.GetInfoForName(interface)
86 except COMException:
87 pass
88 if interface_info is None:
89 # Allow a real IID
90 interface_info = iim.GetInfoForIID(interface)
91 real_ret.append(interface_info.GetIID())
92 parent = interface_info.GetParent()
93 while parent is not None:
94 parent_iid = parent.GetIID()
95 if parent_iid == IID_nsISupports:
96 break
97 real_ret.append(parent_iid)
98 parent = parent.GetParent()
99 return real_ret
100
101##
102## ClassInfo support
103##
104## We cache class infos by class
105class_info_cache = {}
106
107def GetClassInfoForObject(ob):
108 if xpcom.server.tracer_unwrap is not None:
109 ob = xpcom.server.tracer_unwrap(ob)
110 klass = ob.__class__
111 ci = class_info_cache.get(klass)
112 if ci is None:
113 ci = DefaultClassInfo(klass)
114 ci = xpcom.server.WrapObject(ci, _xpcom.IID_nsIClassInfo, bWrapClient = 0)
115 class_info_cache[klass] = ci
116 return ci
117
118class DefaultClassInfo:
119 _com_interfaces_ = _xpcom.IID_nsIClassInfo
120 def __init__(self, klass):
121 self.klass = klass
122 self.contractID = getattr(klass, "_reg_contractid_", None)
123 self.classDescription = getattr(klass, "_reg_desc_", None)
124 self.classID = getattr(klass, "_reg_clsid_", None)
125 self.implementationLanguage = 3 # Python - avoid lookups just for this
126 self.flags = 0 # what to do here??
127 self.interfaces = None
128
129 def get_classID(self):
130 if self.classID is None:
131 raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED, "Class '%r' has no class ID" % (self.klass,))
132 return self.classID
133
134 def getInterfaces(self):
135 if self.interfaces is None:
136 self.interfaces = _GetNominatedInterfaces(self.klass)
137 return self.interfaces
138
139 def getHelperForLanguage(self, language):
140 return None # Not sure what to do here.
141
142class DefaultPolicy:
143 def __init__(self, instance, iid):
144 self._obj_ = instance
145 self._nominated_interfaces_ = ni = _GetNominatedInterfaces(instance)
146 self._iid_ = iid
147 if ni is None:
148 raise ValueError("The object '%r' can not be used as a COM object" % (instance,))
149 # This is really only a check for the user
150 if __debug__:
151 if iid != IID_nsISupports and iid not in ni:
152 # The object may delegate QI.
153 delegate_qi = getattr(instance, "_query_interface_", None)
154 # Perform the actual QI and throw away the result - the _real_
155 # QI performed by the framework will set things right!
156 if delegate_qi is None or not delegate_qi(iid):
157 raise ServerException(nsError.NS_ERROR_NO_INTERFACE)
158 # Stuff for the magic interface conversion.
159 self._interface_info_ = None
160 self._interface_iid_map_ = {} # Cache - Indexed by (method_index, param_index)
161
162 def _QueryInterface_(self, com_object, iid):
163 # Framework allows us to return a single boolean integer,
164 # or a COM object.
165 if iid in self._nominated_interfaces_:
166 # We return the underlying object re-wrapped
167 # in a new gateway - which is desirable, as one gateway should only support
168 # one interface (this wont affect the users of this policy - we can have as many
169 # gateways as we like pointing to the same Python objects - the users never
170 # see what object the call came in from.
171 # NOTE: We could have simply returned the instance and let the framework
172 # do the auto-wrap for us - but this way we prevent a round-trip back into Python
173 # code just for the autowrap.
174 return xpcom.server.WrapObject(self._obj_, iid, bWrapClient = 0)
175
176 # Always support nsIClassInfo
177 if iid == _xpcom.IID_nsIClassInfo:
178 return GetClassInfoForObject(self._obj_)
179
180 # See if the instance has a QI
181 # use lower-case "_query_interface_" as win32com does, and it doesnt really matter.
182 delegate = getattr(self._obj_, "_query_interface_", None)
183 if delegate is not None:
184 # The COM object itself doesnt get passed to the child
185 # (again, as win32com doesnt). It is rarely needed
186 # (in win32com, we dont even pass it to the policy, although we have identified
187 # one place where we should - for marshalling - so I figured I may as well pass it
188 # to the policy layer here, but no all the way down to the object.
189 return delegate(iid)
190 # Finally see if we are being queried for one of the "nsISupports primitives"
191 if not _supports_primitives_map_:
192 iim = _xpcom.XPTI_GetInterfaceInfoManager()
193 for (iid_name, attr, cvt) in _supports_primitives_data_:
194 special_iid = iim.GetInfoForName(iid_name).GetIID()
195 _supports_primitives_map_[special_iid] = (attr, cvt)
196 attr, cvt = _supports_primitives_map_.get(iid, (None,None))
197 if attr is not None and hasattr(self._obj_, attr):
198 return xpcom.server.WrapObject(SupportsPrimitive(iid, self._obj_, attr, cvt), iid, bWrapClient = 0)
199 # Out of clever things to try!
200 return None # We dont support this IID.
201
202 def _MakeInterfaceParam_(self, interface, iid, method_index, mi, param_index):
203 # Wrap a "raw" interface object in a nice object. The result of this
204 # function will be passed to one of the gateway methods.
205 if iid is None:
206 # look up the interface info - this will be true for all xpcom called interfaces.
207 if self._interface_info_ is None:
208 import xpcom.xpt
209 self._interface_info_ = xpcom.xpt.Interface( self._iid_ )
210 iid = self._interface_iid_map_.get( (method_index, param_index))
211 if iid is None:
212 iid = self._interface_info_.GetIIDForParam(method_index, param_index)
213 self._interface_iid_map_[(method_index, param_index)] = iid
214 # handle nsIVariant
215 if iid == IID_nsIVariant:
216 interface = interface.QueryInterface(iid)
217 dt = interface.dataType
218 if dt in VARIANT_INT_TYPES:
219 return interface.getAsInt32()
220 if dt in VARIANT_LONG_TYPES:
221 return interface.getAsInt64()
222 if dt in VARIANT_FLOAT_TYPES:
223 return interface.getAsFloat()
224 if dt in VARIANT_STRING_TYPES:
225 return interface.getAsStringWithSize()
226 if dt in VARIANT_UNICODE_TYPES:
227 return interface.getAsWStringWithSize()
228 if dt == xpcom_consts.VTYPE_BOOL:
229 return interface.getAsBool()
230 if dt == xpcom_consts.VTYPE_INTERFACE:
231 return interface.getAsISupports()
232 if dt == xpcom_consts.VTYPE_INTERFACE_IS:
233 return interface.getAsInterface()
234 if dt == xpcom_consts.VTYPE_EMPTY or dt == xpcom_consts.VTYPE_VOID:
235 return None
236 if dt == xpcom_consts.VTYPE_ARRAY:
237 return interface.getAsArray()
238 if dt == xpcom_consts.VTYPE_EMPTY_ARRAY:
239 return []
240 if dt == xpcom_consts.VTYPE_ID:
241 return interface.getAsID()
242 # all else fails...
243 logger.warning("Warning: nsIVariant type %d not supported - returning a string", dt)
244 try:
245 return interface.getAsString()
246 except COMException:
247 logger.exception("Error: failed to get Variant as a string - returning variant object")
248 return interface
249
250 return client.Component(interface, iid)
251
252 def _CallMethod_(self, com_object, index, info, params):
253 #print "_CallMethod_", index, info, params
254 flags, name, param_descs, ret = info
255 assert ret[1][0] == xpcom_consts.TD_UINT32, "Expected an nsresult (%s)" % (ret,)
256 if XPT_MD_IS_GETTER(flags):
257 # Look for a function of that name
258 func = getattr(self._obj_, "get_" + name, None)
259 if func is None:
260 assert len(param_descs)==1 and len(params)==0, "Can only handle a single [out] arg for a default getter"
261 ret = getattr(self._obj_, name) # Let attribute error go here!
262 else:
263 ret = func(*params)
264 return 0, ret
265 elif XPT_MD_IS_SETTER(flags):
266 # Look for a function of that name
267 func = getattr(self._obj_, "set_" + name, None)
268 if func is None:
269 assert len(param_descs)==1 and len(params)==1, "Can only handle a single [in] arg for a default setter"
270 setattr(self._obj_, name, params[0]) # Let attribute error go here!
271 else:
272 func(*params)
273 return 0
274 else:
275 # A regular method.
276 func = getattr(self._obj_, name)
277 return 0, func(*params)
278
279 def _doHandleException(self, func_name, exc_info):
280 exc_val = exc_info[1]
281 is_server_exception = isinstance(exc_val, ServerException)
282 if is_server_exception:
283 # When a component raised an explicit COM exception, it is
284 # considered 'normal' - however, we still write a debug log
285 # record to help track these otherwise silent exceptions.
286
287 # Note that Python 2.3 does not allow an explicit exc_info tuple
288 # and passing 'True' will not work as there is no exception pending.
289 # Trick things!
290 if logger.isEnabledFor(logging.DEBUG):
291 try:
292 raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
293 except:
294 logger.debug("'%s' raised COM Exception %s",
295 func_name, exc_val, exc_info = 1)
296 return exc_val.errno
297 # Unhandled exception - always print a warning and the traceback.
298 # As above, trick the logging module to handle Python 2.3
299 try:
300 raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
301 except:
302 logger.exception("Unhandled exception calling '%s'", func_name)
303 return nsError.NS_ERROR_FAILURE
304
305 # Called whenever an unhandled Python exception is detected as a result
306 # of _CallMethod_ - this exception may have been raised during the _CallMethod_
307 # invocation, or after its return, but when unpacking the results
308 # eg, type errors, such as a Python integer being used as a string "out" param.
309 def _CallMethodException_(self, com_object, index, info, params, exc_info):
310 # Later we may want to have some smart "am I debugging" flags?
311 # Or maybe just delegate to the actual object - it's probably got the best
312 # idea what to do with them!
313 flags, name, param_descs, ret = info
314 exc_typ, exc_val, exc_tb = exc_info
315 # use the xpt module to get a better repr for the method.
316 # But if we fail, ignore it!
317 try:
318 import xpcom.xpt
319 m = xpcom.xpt.Method(info, index, None)
320 func_repr = m.Describe().lstrip()
321 except COMException:
322 func_repr = "%s(%r)" % (name, param_descs)
323 except:
324 # any other errors are evil!? Log it
325 self._doHandleException("<building method repr>", sys.exc_info())
326 # And fall through to logging the original error.
327 return self._doHandleException(func_repr, exc_info)
328
329 # Called whenever a gateway fails due to anything other than _CallMethod_.
330 # Really only used for the component loader etc objects, so most
331 # users should never see exceptions triggered here.
332 def _GatewayException_(self, name, exc_info):
333 return self._doHandleException(name, exc_info)
334
335_supports_primitives_data_ = [
336 ("nsISupportsCString", "__str__", str),
337 ("nsISupportsString", "__unicode__", str),
338 ("nsISupportsPRUint64", "__long__", int),
339 ("nsISupportsPRInt64", "__long__", int),
340 ("nsISupportsPRUint32", "__int__", int),
341 ("nsISupportsPRInt32", "__int__", int),
342 ("nsISupportsPRUint16", "__int__", int),
343 ("nsISupportsPRInt16", "__int__", int),
344 ("nsISupportsPRUint8", "__int__", int),
345 ("nsISupportsPRBool", "__nonzero__", operator.truth),
346 ("nsISupportsDouble", "__float__", float),
347 ("nsISupportsFloat", "__float__", float),
348]
349
350# Support for the nsISupports primitives:
351class SupportsPrimitive:
352 _com_interfaces_ = ["nsISupports"]
353 def __init__(self, iid, base_ob, attr_name, converter):
354 self.iid = iid
355 self.base_ob = base_ob
356 self.attr_name = attr_name
357 self.converter = converter
358 def _query_interface_(self, iid):
359 if iid == self.iid:
360 return 1
361 return None
362 def get_data(self):
363 method = getattr(self.base_ob, self.attr_name)
364 val = method()
365 return self.converter(val)
366 def set_data(self, val):
367 raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED)
368 def toString(self):
369 return str(self.get_data())
370
371def _shutdown():
372 class_info_cache.clear()
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette