Kaydet (Commit) 36e23e05 authored tarafından cvs2svn's avatar cvs2svn

This commit was manufactured by cvs2svn to create branch

'release21-maint'.
üst 1648e53e
from test_support import verbose
import random
# From SF bug #422121: Insecurities in dict comparison.
# Safety of code doing comparisons has been an historical Python weak spot.
# The problem is that comparison of structures written in C *naturally*
# wants to hold on to things like the size of the container, or "the
# biggest" containee so far, across a traversal of the container; but
# code to do containee comparisons can call back into Python and mutate
# the container in arbitrary ways while the C loop is in midstream. If the
# C code isn't extremely paranoid about digging things out of memory on
# each trip, and artificially boosting refcounts for the duration, anything
# from infinite loops to OS crashes can result (yes, I use Windows <wink>).
#
# The other problem is that code designed to provoke a weakness is usually
# white-box code, and so catches only the particular vulnerabilities the
# author knew to protect against. For example, Python's list.sort() code
# went thru many iterations as one "new" vulnerability after another was
# discovered.
#
# So the dict comparison test here uses a black-box approach instead,
# generating dicts of various sizes at random, and performing random
# mutations on them at random times. This proved very effective,
# triggering at least six distinct failure modes the first 20 times I
# ran it. Indeed, at the start, the driver never got beyond 6 iterations
# before the test died.
# The dicts are global to make it easy to mutate tham from within functions.
dict1 = {}
dict2 = {}
# The current set of keys in dict1 and dict2. These are materialized as
# lists to make it easy to pick a dict key at random.
dict1keys = []
dict2keys = []
# Global flag telling maybe_mutate() wether to *consider* mutating.
mutate = 0
# If global mutate is true, consider mutating a dict. May or may not
# mutate a dict even if mutate is true. If it does decide to mutate a
# dict, it picks one of {dict1, dict2} at random, and deletes a random
# entry from it; or, more rarely, adds a random element.
def maybe_mutate():
global mutate
if not mutate:
return
if random.random() < 0.5:
return
if random.random() < 0.5:
target, keys = dict1, dict1keys
else:
target, keys = dict2, dict2keys
if random.random() < 0.2:
# Insert a new key.
mutate = 0 # disable mutation until key inserted
while 1:
newkey = Horrid(random.randrange(100))
if newkey not in target:
break
target[newkey] = Horrid(random.randrange(100))
keys.append(newkey)
mutate = 1
elif keys:
# Delete a key at random.
i = random.randrange(len(keys))
key = keys[i]
del target[key]
# CAUTION: don't use keys.remove(key) here. Or do <wink>. The
# point is that .remove() would trigger more comparisons, and so
# also more calls to this routine. We're mutating often enough
# without that.
del keys[i]
# A horrid class that triggers random mutations of dict1 and dict2 when
# instances are compared.
class Horrid:
def __init__(self, i):
# Comparison outcomes are determined by the value of i.
self.i = i
# An artificial hashcode is selected at random so that we don't
# have any systematic relationship between comparison outcomes
# (based on self.i and other.i) and relative position within the
# hash vector (based on hashcode).
self.hashcode = random.randrange(1000000000)
def __hash__(self):
return self.hashcode
def __cmp__(self, other):
maybe_mutate() # The point of the test.
return cmp(self.i, other.i)
def __repr__(self):
return "Horrid(%d)" % self.i
# Fill dict d with numentries (Horrid(i), Horrid(j)) key-value pairs,
# where i and j are selected at random from the candidates list.
# Return d.keys() after filling.
def fill_dict(d, candidates, numentries):
d.clear()
for i in xrange(numentries):
d[Horrid(random.choice(candidates))] = \
Horrid(random.choice(candidates))
return d.keys()
# Test one pair of randomly generated dicts, each with n entries.
# Note that dict comparison is trivial if they don't have the same number
# of entires (then the "shorter" dict is instantly considered to be the
# smaller one, without even looking at the entries).
def test_one(n):
global mutate, dict1, dict2, dict1keys, dict2keys
# Fill the dicts without mutating them.
mutate = 0
dict1keys = fill_dict(dict1, range(n), n)
dict2keys = fill_dict(dict2, range(n), n)
# Enable mutation, then compare the dicts so long as they have the
# same size.
mutate = 1
if verbose:
print "trying w/ lengths", len(dict1), len(dict2),
while dict1 and len(dict1) == len(dict2):
if verbose:
print ".",
c = cmp(dict1, dict2)
if verbose:
print
# Run test_one n times. At the start (before the bugs were fixed), 20
# consecutive runs of this test each blew up on or before the sixth time
# test_one was run. So n doesn't have to be large to get an interesting
# test.
# OTOH, calling with large n is also interesting, to ensure that the fixed
# code doesn't hold on to refcounts *too* long (in which case memory would
# leak).
def test(n):
for i in xrange(n):
test_one(random.randrange(1, 100))
# See last comment block for clues about good values for n.
test(100)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This is the Python Language Module for BBEdit.
This software is a plugin to Bare Bones Software's BBEdit 6.0.2 (or more), designed to make editing & browsing Python Language files easer.
It parses any file ending in .py (or extentions of your choice.) providing BBEdit with the information BBEdit needs to provide services for python files similar to those it provides for 'C'. Namely: syntax coloring and populating BBEdit's '€' popup menu with file's functions and classes.
This Plug-in needs to be placed in your :BBEdit 6.0:BBEdit Support:Language Modules: folder.
If you wish, I have no objections to redistributing it in whole or in part, modify it, or beating small fury animals to death with rolled up printouts of the source code.
Christopher Stern
cistern@earthlink.net
\ No newline at end of file
"""PythonSlave.py
An application that responds to three types of apple event:
'pyth'/'EXEC': execute direct parameter as Python
'aevt', 'quit': quit
'aevt', 'odoc': perform python scripts
Copyright 1996, Just van Rossum, Letterror
"""
__version__ = "0.1.3"
import FrameWork
import sys
import traceback
import aetools
import string
import AE
import EasyDialogs
import os
import Qd
from Types import *
from Events import charCodeMask, cmdKey
import MacOS
import Evt
def dummyfunc(): pass
modulefilename = dummyfunc.func_code.co_filename
def Interact(timeout = 50000000): # timeout after 10 days...
AE.AEInteractWithUser(timeout)
class PythonSlave(FrameWork.Application):
def __init__(self):
FrameWork.Application.__init__(self)
AE.AEInstallEventHandler('pyth', 'EXEC', ExecHandler)
AE.AEInstallEventHandler('aevt', 'quit', QuitHandler)
AE.AEInstallEventHandler('aevt', 'odoc', OpenDocumentHandler)
def makeusermenus(self):
self.filemenu = m = FrameWork.Menu(self.menubar, "File")
self._quititem = FrameWork.MenuItem(m, "Quit", "Q", self._quit)
def do_kHighLevelEvent(self, event):
(what, message, when, where, modifiers) = event
try:
AE.AEProcessAppleEvent(event)
except AE.Error, detail:
print "Apple Event was not handled, error:", detail
def do_key(self, event):
(what, message, when, where, modifiers) = event
c = chr(message & charCodeMask)
if modifiers & cmdKey and c == '.':
return
FrameWork.Application.do_key(self, event)
def idle(self, event):
Qd.InitCursor()
def quit(self, *args):
raise self
def getabouttext(self):
return "About PythonSlave"
def do_about(self, id, item, window, event):
EasyDialogs.Message("PythonSlave " + __version__ + "\rCopyright 1996, Letterror, JvR")
def ExecHandler(theAppleEvent, theReply):
parameters, args = aetools.unpackevent(theAppleEvent)
if parameters.has_key('----'):
if parameters.has_key('NAME'):
print '--- executing "' + parameters['NAME'] + '" ---'
else:
print '--- executing "<unknown>" ---'
stuff = parameters['----']
MyExec(stuff + "\n") # execute input
print '--- done ---'
return 0
def MyExec(stuff):
stuff = string.splitfields(stuff, '\r') # convert return chars
stuff = string.joinfields(stuff, '\n') # to newline chars
Interact()
saveyield = MacOS.EnableAppswitch(1)
try:
exec stuff in {}
except:
MacOS.EnableAppswitch(saveyield)
traceback.print_exc()
MacOS.EnableAppswitch(saveyield)
def OpenDocumentHandler(theAppleEvent, theReply):
parameters, args = aetools.unpackevent(theAppleEvent)
docs = parameters['----']
if type(docs) <> ListType:
docs = [docs]
for doc in docs:
fss, a = doc.Resolve()
path = fss.as_pathname()
if path <> modulefilename:
MyExecFile(path)
return 0
def MyExecFile(path):
saveyield = MacOS.EnableAppswitch(1)
savewd = os.getcwd()
os.chdir(os.path.split(path)[0])
print '--- Executing file "' + os.path.split(path)[1] + '"'
try:
execfile(path, {"__name__": "__main__"})
except:
traceback.print_exc()
MacOS.EnableAppswitch(saveyield)
MacOS.EnableAppswitch(saveyield)
os.chdir(savewd)
print "--- done ---"
def QuitHandler(theAppleEvent, theReply):
slave.quit()
return 0
slave = PythonSlave()
print "PythonSlave", __version__, "ready."
slave.mainloop()
PythonScript
------------
v0.5 beta 1 24/04/98
author: Bill Bedford, <billb@mousa.demon.co.uk>
This suite of modules is a first attempt at writing a more user friendly
python/appleevent interface. The files in the suite are:
PythonScript
------------
Loads three dictionaries generated by getaete into __dict__'s of three
classes and thus gives us direct assess to all the methods in the aete.
Each method now contains all the information needed to build apple events.
The general usage is
>>>PythonScript.PsScript(SIGNATURE, TIMEOUT, IGNORING)
where
SIGNATURE is the target application
TIMEOUT is in ticks
and IGNORING is a boolean and determines whether the script waits for a reply
from the target before going on to the next event
>>>PythonScript.PyScript(Event, Object, keywdarg1..., keywdarg2...etc)
Object is a appleevent object specifier and is of the form
PythonScript.PsClass.Class1(arg).Class2(arg)ƒ.Property()
All applescript event, class and property names are capitalised to
distinguish them from python methods.
getaete
-------
Reads the aete of the target application and returns it as a list of three
dictionaries, which represent all the events, properties and enumeration in
the aete. (the fourth dictionary, comparisons, has never been implemented
in applescript so I have not used it) It also reads the applescript aeut
and adds any suites that are missing (ie where the application author has
set his suite to inherit from the aeut.) and the applescript suite, which
gives the language methods
printaete
---------
Produces a text file with the aete set out in a human readable form,
similar to the Open Dictionary command in the applescript editor.
baetools, baepack, baetypes
---------------------------
These are direct equivalents of aetools, aepack, aetypes in the standard
distribution. Some methods and classes have been enhanced others are
redundant
PyScriptTest, testeudora
------------------------
A couple of test scripts. Testeudora is an updated version of the one in
the standard distribution.
Still To Do (in no particular order)
-----------
These modules are much slower than applescript. I believe they could be
made faster by rewriting the aete parser in getaete and/or by putting in
some form of persistent storage so that the class dictionaries can be cached.
The parsing of the appleevent replies need rewriting.
Support for the use of scripting additions.
A Python aeut needs to be written, much of the applescript one is redundant
in python.
Probably a few other things I haven't thought of yet.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Preliminary notes/documentation for the calldll module, version 0.2.
====================================================================
Calldll allows you to call random C functions from python without writing any
C code. It is mainly meant to call MacOS toolbox routines for which no Python
wrapper module is available. It is also incomplete, in that only a few argument
types are currently supported. Please let me know which other argument types
you need, and/or whether you have any ideas on a general "escape" allowing people
to pass anything.
The module exports three functions:
- symtable = getlibrary(libraryname)
Get a reference to import library libraryname. "InterfaceLib" is the most commonly
used one, containing most toolbox routines. The symbol table can be used
to lookup routines to be passed to newcall: "symtable.WaitNextEvent" will
return the address of routine WaitNextEvent. and so will "symtable['WaitNextEvent']".
The symtable is a mapping, so you can use keys() and len(...) to inspect it.
- symtable = getdiskfragment(file)
Load the specified file (given by fsspec or filename) and return a reference to
its symboltable.
- callable = newcall(routine, returntype, [argtype, ...])
Return a callable object. You specify the C routine to be called (as explained above),
the type of the return value and the argument types. The resulting object can
be called from Python code in the normal way, and typechecking on arguments is
performed (but, of course, if you specify incorrect argument types in this call
you may well crash your machine). Printing a callable will give you a description
of the (C-) calling sequence.
The C return value can be one of 'None', 'Byte', 'Short', 'Long', 'Pstring' (a pascal
string returned by address, copied to a Python string), 'Cobject' (a wrapper around a void
pointer), 'Handle' (a new handle, returned as a Res.Resource object) or 'OSErr' (which raises
MacOS.Error if non-zero).
Arguments can be any of 'InByte', 'InShort', 'InLong', 'InString' (a python string, with the
address of the data passed to the C routine, so be careful!), 'InPstring' (a python string copied
to a Str255 and passed by address), 'InCobject', 'InHandle', 'OutByte' (storage is allocated for
a single byte, the address passed to C and the resulting value returned to Python), 'OutShort',
'OutLong', 'OutPstring' (again: storage pre-allocated and the address passed to C), 'OutCobject'
(storage for a void * is allocated, this void ** is passed to C and the resulting void * is
encapsulated in the Cobject returned) or 'OutHandle' (ditto, which means that this is usually *not*
what you use, you normally use 'InHandle' because most toolbox calls expect you to preallocate
the handle).
All values to be returned (from the return value and the Out arguments) are collected. If there
aren't any None is returned, if there is one value this value is returned, if there are multiple
values a tuple is returned.
There is test code in testcalldll.py, and a minimal example in samplecalldll.py.
This diff is collapsed.
This diff is collapsed.
import aetools
import Standard_Suite
import Required_Suite
import MacOS
import W
class Toolbox(aetools.TalkTo, Standard_Suite.Standard_Suite):
def LookupTopic(self, _object, _attributes={}, **_arguments):
_code = 'DanR'
_subcode = 'REF '
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise MacOS.Error, aetools.decodeerror(_arguments)
class ToolboxAssi:
def __init__(self):
self.talker = None
self.w = W.Window((200, 100), "Toolbox Assistant")
self.w.button = W.Button((-94, -32, 80, 16), "Lookup", self.lookup)
self.w.prompt = W.TextBox((10, 8, -10, 15), "Enter topic:")
self.w.edit = W.EditText((10, 24, -10, 20))
self.w.setdefaultbutton(self.w.button)
self.w.open()
def lookup(self):
if self.talker is None:
try:
self.talker = Toolbox('ALTV', start = 1)
except:
raise W.AlertError, "Cant find Toolbox Assistant"
lookup = self.w.edit.get()
try:
self.talker.LookupTopic(lookup)
except MacOS.Error, detail:
W.Message("Requested topic not found.\r(%d)" % detail[0])
t = ToolboxAssi()
/***********************************************************
Copyright 1991-1997 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
#ifdef WITHOUT_FRAMEWORKS
#include <Types.h>
#include <Files.h>
#else
#include <Carbon/Carbon.h>
#endif
extern OSErr FindApplicationFromCreator(OSType, FSSpecPtr);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
"""Suite Standard URL suite: Mac URL standard, supported by many apps
Level 1, version 1
Generated from flap:Programma's:Netscape Navigator Folder:Netscape Navigator 3.01
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'GURL'
class Standard_URL_suite:
_argmap_GetURL = {
'to' : 'dest',
'inside' : 'HWIN',
'_from' : 'refe',
}
def GetURL(self, _object, _attributes={}, **_arguments):
"""GetURL: Loads the URL (optionaly to disk)
Required argument: The url
Keyword argument to: file the URL should be loaded into
Keyword argument inside: Window the URL should be loaded to
Keyword argument _from: Refererer, to be sent with the HTTP request
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'GURL'
_subcode = 'GURL'
aetools.keysubst(_arguments, self._argmap_GetURL)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
#
# Indices of types declared in this module
#
_classdeclarations = {
}
_propdeclarations = {
}
_compdeclarations = {
}
_enumdeclarations = {
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
(This file must be converted with BinHex 4.0) :!!"bFh*M8P0&4!#3#!'IKH8!N!3"!!!!!9N!!!"C!!!!4J$k+J!!qLS!!2SU!!$ k+J!!qLS!!2SUq!$k+`!!q[rj%A4XDA0dAf4TB@a[CbjbFh*M-M%Z-5iaFh4KE'a PFQ`!!(*cFQ058d9%!*!BXQ0apJ#3"J'I+J!!qLS!!2SU!!$k+J!!qLS!!2SU!!$ k+J!!qLS!!2SUq!$k+`!!q[rj!$S!!2Vr%$S!!2SV!!$kr!!!qLS!!2SU!!$k+J! !qLS!!2SU!!$k+J!!qLS!!2SU!!$k+[J!qLX!!2Vrq3!k!!$kr`!!qLX!!2Vm!!$ k+J!!qLS!!2SU!*!%2!!#!*!&UJ#J!,i!fJ3#6dX!N!8S!!S!T3$D!*!(#J!+!"` !fBJ18f9XC@0d)'%JGfpbC$S!!!!9!%B!MJ%1!Ai!!`%!!3#3"3)"!!!!!3!!!!& C!!!!@3!!!%B!b9$i%D)!!!!F!%B!!84-6dF!!!!54%P86!!!!"i#!Irr!!!!3!$ *8E`#!Irr!*!&b8rJLZ):
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
** Create the 'vers' version resource from information in the
** Python include files.
*/
#include "Types.r"
#include "patchlevel.h"
/* Invent the Mac version from the Python version */
#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
#define V_RELEASE alpha
#endif
#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
#define V_RELEASE beta
#endif
#ifndef V_RELEASE
#define V_RELEASE final
#endif
resource 'vers' (1) {
PY_MAJOR_VERSION,
(PY_MINOR_VERSION<<4) | (PY_MICRO_VERSION),
V_RELEASE,
PY_RELEASE_SERIAL,
0,
PY_VERSION,
$$Format("%s, Python Software Foundation %s",
PY_VERSION, $$Date)
};
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment