[pypy-commit] pypy reflex-support: merge default into branch

wlav noreply at buildbot.pypy.org
Thu Jun 7 22:49:54 CEST 2012


Author: Wim Lavrijsen <WLavrijsen at lbl.gov>
Branch: reflex-support
Changeset: r55488:092b32a5c9c8
Date: 2012-06-07 13:50 -0700
http://bitbucket.org/pypy/pypy/changeset/092b32a5c9c8/

Log:	merge default into branch

diff --git a/lib-python/2.7/ctypes/__init__.py b/lib-python/2.7/ctypes/__init__.py
--- a/lib-python/2.7/ctypes/__init__.py
+++ b/lib-python/2.7/ctypes/__init__.py
@@ -351,7 +351,10 @@
         self._FuncPtr = _FuncPtr
 
         if handle is None:
-            self._handle = _ffi.CDLL(name, mode)
+            if flags & _FUNCFLAG_CDECL:
+                self._handle = _ffi.CDLL(name, mode)
+            else:
+                self._handle = _ffi.WinDLL(name, mode)
         else:
             self._handle = handle
 
diff --git a/lib-python/2.7/pickle.py b/lib-python/2.7/pickle.py
--- a/lib-python/2.7/pickle.py
+++ b/lib-python/2.7/pickle.py
@@ -638,7 +638,7 @@
             # else tmp is empty, and we're done
 
     def save_dict(self, obj):
-        modict_saver = self._pickle_moduledict(obj)
+        modict_saver = self._pickle_maybe_moduledict(obj)
         if modict_saver is not None:
             return self.save_reduce(*modict_saver)
 
@@ -691,26 +691,20 @@
                 write(SETITEM)
             # else tmp is empty, and we're done
 
-    def _pickle_moduledict(self, obj):
+    def _pickle_maybe_moduledict(self, obj):
         # save module dictionary as "getattr(module, '__dict__')"
+        try:
+            name = obj['__name__']
+            if type(name) is not str:
+                return None
+            themodule = sys.modules[name]
+            if type(themodule) is not ModuleType:
+                return None
+            if themodule.__dict__ is not obj:
+                return None
+        except (AttributeError, KeyError, TypeError):
+            return None
 
-        # build index of module dictionaries
-        try:
-            modict = self.module_dict_ids
-        except AttributeError:
-            modict = {}
-            from sys import modules
-            for mod in modules.values():
-                if isinstance(mod, ModuleType):
-                    modict[id(mod.__dict__)] = mod
-            self.module_dict_ids = modict
-
-        thisid = id(obj)
-        try:
-            themodule = modict[thisid]
-        except KeyError:
-            return None
-        from __builtin__ import getattr
         return getattr, (themodule, '__dict__')
 
 
diff --git a/lib_pypy/_ctypes/basics.py b/lib_pypy/_ctypes/basics.py
--- a/lib_pypy/_ctypes/basics.py
+++ b/lib_pypy/_ctypes/basics.py
@@ -47,10 +47,6 @@
         else:
             return self.from_param(as_parameter)
 
-    def get_ffi_param(self, value):
-        cdata = self.from_param(value)
-        return cdata, cdata._to_ffi_param()
-
     def get_ffi_argtype(self):
         if self._ffiargtype:
             return self._ffiargtype
diff --git a/lib_pypy/_ctypes/function.py b/lib_pypy/_ctypes/function.py
--- a/lib_pypy/_ctypes/function.py
+++ b/lib_pypy/_ctypes/function.py
@@ -391,7 +391,7 @@
         address = self._get_address()
         ffiargs = [argtype.get_ffi_argtype() for argtype in argtypes]
         ffires = restype.get_ffi_argtype()
-        return _ffi.FuncPtr.fromaddr(address, '', ffiargs, ffires)
+        return _ffi.FuncPtr.fromaddr(address, '', ffiargs, ffires, self._flags_)
 
     def _getfuncptr(self, argtypes, restype, thisarg=None):
         if self._ptr is not None and (argtypes is self._argtypes_ or argtypes == self._argtypes_):
@@ -412,7 +412,7 @@
             ptr = thisarg[0][self._com_index - 0x1000]
             ffiargs = [argtype.get_ffi_argtype() for argtype in argtypes]
             ffires = restype.get_ffi_argtype()
-            return _ffi.FuncPtr.fromaddr(ptr, '', ffiargs, ffires)
+            return _ffi.FuncPtr.fromaddr(ptr, '', ffiargs, ffires, self._flags_)
         
         cdll = self.dll._handle
         try:
@@ -444,10 +444,6 @@
 
     @classmethod
     def _conv_param(cls, argtype, arg):
-        if isinstance(argtype, _CDataMeta):
-            cobj, ffiparam = argtype.get_ffi_param(arg)
-            return cobj, ffiparam, argtype
-        
         if argtype is not None:
             arg = argtype.from_param(arg)
         if hasattr(arg, '_as_parameter_'):
diff --git a/lib_pypy/ctypes_support.py b/lib_pypy/ctypes_support.py
--- a/lib_pypy/ctypes_support.py
+++ b/lib_pypy/ctypes_support.py
@@ -12,6 +12,8 @@
 if sys.platform == 'win32':
     import _ffi
     standard_c_lib = ctypes.CDLL('msvcrt', handle=_ffi.get_libc())
+elif sys.platform == 'cygwin':
+    standard_c_lib = ctypes.CDLL(ctypes.util.find_library('cygwin'))
 else:
     standard_c_lib = ctypes.CDLL(ctypes.util.find_library('c'))
 
diff --git a/pypy/bin/rpython b/pypy/bin/rpython
old mode 100644
new mode 100755
diff --git a/pypy/doc/coding-guide.rst b/pypy/doc/coding-guide.rst
--- a/pypy/doc/coding-guide.rst
+++ b/pypy/doc/coding-guide.rst
@@ -610,10 +610,6 @@
     >>>> cPickle.__file__
     '/home/hpk/pypy-dist/lib_pypy/cPickle..py'
 
-    >>>> import opcode
-    >>>> opcode.__file__
-    '/home/hpk/pypy-dist/lib-python/modified-2.7/opcode.py'
-
     >>>> import os
     >>>> os.__file__
     '/home/hpk/pypy-dist/lib-python/2.7/os.py'
@@ -639,13 +635,9 @@
 
     contains pure Python reimplementation of modules.
 
-*lib-python/modified-2.7/*
-
-    The files and tests that we have modified from the CPython library.
-
 *lib-python/2.7/*
 
-    The unmodified CPython library. **Never ever check anything in there**.
+    The modified CPython library.
 
 .. _`modify modules`:
 
@@ -658,16 +650,9 @@
 by default and CPython has a number of places where it relies
 on some classes being old-style.
 
-If you want to change a module or test contained in ``lib-python/2.7``
-then make sure that you copy the file to our ``lib-python/modified-2.7``
-directory first.  In mercurial commandline terms this reads::
-
-    $ hg cp lib-python/2.7/somemodule.py lib-python/modified-2.7/
-
-and subsequently you edit and commit
-``lib-python/modified-2.7/somemodule.py``.  This copying operation is
-important because it keeps the original CPython tree clean and makes it
-obvious what we had to change.
+We just maintain those changes in place,
+to see what is changed we have a branch called `vendot/stdlib`
+wich contains the unmodified cpython stdlib
 
 .. _`mixed module mechanism`:
 .. _`mixed modules`:
diff --git a/pypy/doc/cppyy.rst b/pypy/doc/cppyy.rst
--- a/pypy/doc/cppyy.rst
+++ b/pypy/doc/cppyy.rst
@@ -361,6 +361,11 @@
   If a pointer is a global variable, the C++ side can replace the underlying
   object and the python side will immediately reflect that.
 
+* **PyObject***: Arguments and return types of ``PyObject*`` can be used, and
+  passed on to CPython API calls.
+  Since these CPython-like objects need to be created and tracked (this all
+  happens through ``cpyext``) this interface is not particularly fast.
+
 * **static data members**: Are represented as python property objects on the
   class and the meta-class.
   Both read and write access is as expected.
diff --git a/pypy/doc/cpython_differences.rst b/pypy/doc/cpython_differences.rst
--- a/pypy/doc/cpython_differences.rst
+++ b/pypy/doc/cpython_differences.rst
@@ -324,5 +324,10 @@
   type and vice versa. For builtin types, a dictionary will be returned that
   cannot be changed (but still looks and behaves like a normal dictionary).
 
+* the ``__len__`` or ``__length_hint__`` special methods are sometimes
+  called by CPython to get a length estimate to preallocate internal arrays.
+  So far, PyPy never calls ``__len__`` for this purpose, and never calls
+  ``__length_hint__`` at all.
+
 
 .. include:: _ref.txt
diff --git a/pypy/doc/getting-started-python.rst b/pypy/doc/getting-started-python.rst
--- a/pypy/doc/getting-started-python.rst
+++ b/pypy/doc/getting-started-python.rst
@@ -220,7 +220,6 @@
    ./include/
    ./lib_pypy/
    ./lib-python/2.7
-   ./lib-python/modified-2.7
    ./site-packages/
 
 The hierarchy shown above is relative to a PREFIX directory.  PREFIX is
diff --git a/pypy/doc/release-1.9.0.rst b/pypy/doc/release-1.9.0.rst
new file mode 100644
--- /dev/null
+++ b/pypy/doc/release-1.9.0.rst
@@ -0,0 +1,107 @@
+====================
+PyPy 1.9 - Yard Wolf
+====================
+
+We're pleased to announce the 1.9 release of PyPy. This release brings mostly
+bugfixes, performance improvements, other small improvements and overall
+progress on the `numpypy`_ effort.
+It also brings an improved situation on windows and OS X.
+
+You can download the PyPy 1.9 release here:
+
+    http://pypy.org/download.html 
+
+.. _`numpypy`: http://pypy.org/numpydonate.html
+
+
+What is PyPy?
+=============
+
+PyPy is a very compliant Python interpreter, almost a drop-in replacement for
+CPython 2.7. It's fast (`pypy 1.9 and cpython 2.7.2`_ performance comparison)
+due to its integrated tracing JIT compiler.
+
+This release supports x86 machines running Linux 32/64, Mac OS X 64 or
+Windows 32.  Windows 64 work is still stalling, we would welcome a volunteer
+to handle that.
+
+.. _`pypy 1.9 and cpython 2.7.2`: http://speed.pypy.org
+
+
+Thanks to our donators
+======================
+
+But first of all, we would like to say thank you to all people who
+donated some money to one of our four calls:
+
+  * `NumPy in PyPy`_ (got so far $44502 out of $60000, 74%)
+
+  * `Py3k (Python 3)`_ (got so far $43563 out of $105000, 41%)
+
+  * `Software Transactional Memory`_ (got so far $21791 of $50400, 43%)
+
+  * as well as our general PyPy pot.
+
+Thank you all for proving that it is indeed possible for a small team of
+programmers to get funded like that, at least for some
+time.  We want to include this thank you in the present release
+announcement even though most of the work is not finished yet.  More
+precisely, neither Py3k nor STM are ready to make it an official release
+yet: people interested in them need to grab and (attempt to) translate
+PyPy from the corresponding branches (respectively ``py3k`` and
+``stm-thread``).
+
+.. _`NumPy in PyPy`: http://pypy.org/numpydonate.html
+.. _`Py3k (Python 3)`: http://pypy.org/py3donate.html
+.. _`Software Transactional Memory`: http://pypy.org/tmdonate.html
+
+Highlights
+==========
+
+* This release still implements Python 2.7, the standard library has been
+  upgraded to CPython 2.7.2.
+
+* Many bugs were corrected for Windows 32 bit.  This includes new
+  functionality to test the validity of file descriptors; and
+  correct handling of the calling convensions for ctypes.  (Still not
+  much progress on Win64.) A lot of work on this has been done by Matti Picus
+  and Amaury Forgeot d'Arc.
+
+* Improvements in ``cpyext``, our emulator for CPython C extension modules.
+  For example PyOpenSSL should now work.
+
+* Sets now have strategies just like dictionaries. This means for example
+  that a set containing only ints will be more compact (and faster).
+
+* A lot of progress on various aspects of ``numpypy``. See `numpy-status`_
+  page for the automatic report.
+
+* It is now possible to create and manipulate C-like structures using the
+  PyPy-only ``_ffi`` module.  The advantage over using e.g. ``ctypes`` is that
+  ``_ffi`` is very JIT-friendly, and getting/setting of fields is translated
+  to few assembler instructions by the JIT. However, this is mostly intended
+  as a low-level backend to be used by more user-friendly FFI packages, and
+  the API might change in the future. Use it at your own risk.
+
+* The non-x86 backends for the JIT are progressing but are still not
+  merged (ARMv7 and PPC64).
+
+* JIT hooks for inspecting the created assembler code has been improved.
+  See `JIT hooks documentation`_ for details.
+
+* ``select.kqueue`` has been added.
+
+* Handling of keyword arguments has been drastically improved in the best-case
+  scenario.
+
+* List comprehension has been improved.
+
+JitViewer
+=========
+
+There is a corresponding 1.9 release of JitViewer which is guaranteed to work
+with PyPy 1.9. See `JitViewer docs`_ for details.
+
+.. _`numpy status`: http://buildbot.pypy.org/numpy-status/latest.html
+.. _`JitViewer docs`: http://bitbucket.org/pypy/jitviewer
+.. _`JIT hooks documentation`: http://doc.pypy.org/en/latest/jit-hooks.html
diff --git a/pypy/doc/test/test_whatsnew.py b/pypy/doc/test/test_whatsnew.py
--- a/pypy/doc/test/test_whatsnew.py
+++ b/pypy/doc/test/test_whatsnew.py
@@ -16,6 +16,7 @@
             startrev = parseline(line)
         elif line.startswith('.. branch:'):
             branches.add(parseline(line))
+    branches.discard('default')
     return startrev, branches
 
 def get_merged_branches(path, startrev, endrev):
@@ -51,6 +52,10 @@
 .. branch: hello
 
 qqq www ttt
+
+.. branch: default
+
+"default" should be ignored and not put in the set of documented branches
 """
     startrev, branches = parse_doc(s)
     assert startrev == '12345'
diff --git a/pypy/doc/whatsnew-1.9.rst b/pypy/doc/whatsnew-1.9.rst
--- a/pypy/doc/whatsnew-1.9.rst
+++ b/pypy/doc/whatsnew-1.9.rst
@@ -5,8 +5,12 @@
 .. this is the revision just after the creation of the release-1.8.x branch
 .. startrev: a4261375b359
 
+.. branch: default
+* Working hash function for numpy types.
+
 .. branch: array_equal
 .. branch: better-jit-hooks-2
+Improved jit hooks
 .. branch: faster-heapcache
 .. branch: faster-str-decode-escape
 .. branch: float-bytes
@@ -16,9 +20,14 @@
 .. branch: jit-frame-counter
 Put more debug info into resops.
 .. branch: kill-geninterp
+Kill "geninterp", an old attempt to statically turn some fixed
+app-level code to interp-level.
 .. branch: kqueue
 Finished select.kqueue.
 .. branch: kwargsdict-strategy
+Special dictionary strategy for dealing with \*\*kwds. Now having a simple
+proxy ``def f(*args, **kwds): return x(*args, **kwds`` should not make
+any allocations at all.
 .. branch: matrixmath-dot
 numpypy can now handle matrix multiplication.
 .. branch: merge-2.7.2
@@ -29,13 +38,19 @@
 cpyext: Better support for PyEval_SaveThread and other PyTreadState_*
 functions.
 .. branch: numppy-flatitter
+flatitier for numpy
 .. branch: numpy-back-to-applevel
+reuse more of original numpy
 .. branch: numpy-concatenate
+concatenation support for numpy
 .. branch: numpy-indexing-by-arrays-bool
+indexing by bool arrays
 .. branch: numpy-record-dtypes
+record dtypes on numpy has been started
 .. branch: numpy-single-jitdriver
 .. branch: numpy-ufuncs2
 .. branch: numpy-ufuncs3
+various refactorings regarding numpy
 .. branch: numpypy-issue1137
 .. branch: numpypy-out
 The "out" argument was added to most of the numypypy functions.
@@ -43,8 +58,13 @@
 .. branch: numpypy-ufuncs
 .. branch: pytest
 .. branch: safe-getargs-freelist
+CPyext improvements. For example PyOpenSSL should now work
 .. branch: set-strategies
+Sets now have strategies just like dictionaries. This means a set
+containing only ints will be more compact (and faster)
 .. branch: speedup-list-comprehension
+The simplest case of list comprehension is preallocating the correct size
+of the list. This speeds up select benchmarks quite significantly.
 .. branch: stdlib-unification
 The directory "lib-python/modified-2.7" has been removed, and its
 content merged into "lib-python/2.7".
@@ -64,8 +84,11 @@
 _invalid_parameter_handler
 .. branch: win32-kill
 Add os.kill to windows even if translating python does not have os.kill
+.. branch: win_ffi
+Handle calling conventions for the _ffi and ctypes modules
 .. branch: win64-stage1
 .. branch: zlib-mem-pressure
+Memory "leaks" associated with zlib are fixed.
 
 .. branch: ffistruct
 The ``ffistruct`` branch adds a very low level way to express C structures
diff --git a/pypy/jit/backend/llsupport/gc.py b/pypy/jit/backend/llsupport/gc.py
--- a/pypy/jit/backend/llsupport/gc.py
+++ b/pypy/jit/backend/llsupport/gc.py
@@ -577,7 +577,6 @@
     def __init__(self, gc_ll_descr):
         self.llop1 = gc_ll_descr.llop1
         self.WB_FUNCPTR = gc_ll_descr.WB_FUNCPTR
-        self.WB_ARRAY_FUNCPTR = gc_ll_descr.WB_ARRAY_FUNCPTR
         self.fielddescr_tid = gc_ll_descr.fielddescr_tid
         #
         GCClass = gc_ll_descr.GCClass
@@ -592,6 +591,11 @@
             self.jit_wb_card_page_shift = GCClass.JIT_WB_CARD_PAGE_SHIFT
             self.jit_wb_cards_set_byteofs, self.jit_wb_cards_set_singlebyte = (
                 self.extract_flag_byte(self.jit_wb_cards_set))
+            #
+            # the x86 backend uses the following "accidental" facts to
+            # avoid one instruction:
+            assert self.jit_wb_cards_set_byteofs == self.jit_wb_if_flag_byteofs
+            assert self.jit_wb_cards_set_singlebyte == -0x80
         else:
             self.jit_wb_cards_set = 0
 
@@ -615,7 +619,7 @@
         # returns a function with arguments [array, index, newvalue]
         llop1 = self.llop1
         funcptr = llop1.get_write_barrier_from_array_failing_case(
-            self.WB_ARRAY_FUNCPTR)
+            self.WB_FUNCPTR)
         funcaddr = llmemory.cast_ptr_to_adr(funcptr)
         return cpu.cast_adr_to_int(funcaddr)    # this may return 0
 
@@ -699,9 +703,7 @@
 
     def _setup_write_barrier(self):
         self.WB_FUNCPTR = lltype.Ptr(lltype.FuncType(
-            [llmemory.Address, llmemory.Address], lltype.Void))
-        self.WB_ARRAY_FUNCPTR = lltype.Ptr(lltype.FuncType(
-            [llmemory.Address, lltype.Signed, llmemory.Address], lltype.Void))
+            [llmemory.Address], lltype.Void))
         self.write_barrier_descr = WriteBarrierDescr(self)
 
     def _make_functions(self, really_not_translated):
@@ -859,8 +861,7 @@
             # the GC, and call it immediately
             llop1 = self.llop1
             funcptr = llop1.get_write_barrier_failing_case(self.WB_FUNCPTR)
-            funcptr(llmemory.cast_ptr_to_adr(gcref_struct),
-                    llmemory.cast_ptr_to_adr(gcref_newptr))
+            funcptr(llmemory.cast_ptr_to_adr(gcref_struct))
 
     def can_use_nursery_malloc(self, size):
         return size < self.max_size_of_young_obj
diff --git a/pypy/jit/backend/llsupport/test/test_gc.py b/pypy/jit/backend/llsupport/test/test_gc.py
--- a/pypy/jit/backend/llsupport/test/test_gc.py
+++ b/pypy/jit/backend/llsupport/test/test_gc.py
@@ -276,8 +276,8 @@
                             repr(offset_to_length), p))
         return p
 
-    def _write_barrier_failing_case(self, adr_struct, adr_newptr):
-        self.record.append(('barrier', adr_struct, adr_newptr))
+    def _write_barrier_failing_case(self, adr_struct):
+        self.record.append(('barrier', adr_struct))
 
     def get_write_barrier_failing_case(self, FPTRTYPE):
         return llhelper(FPTRTYPE, self._write_barrier_failing_case)
@@ -402,7 +402,7 @@
         #
         s_hdr.tid |= gc_ll_descr.GCClass.JIT_WB_IF_FLAG
         gc_ll_descr.do_write_barrier(s_gcref, r_gcref)
-        assert self.llop1.record == [('barrier', s_adr, r_adr)]
+        assert self.llop1.record == [('barrier', s_adr)]
 
     def test_gen_write_barrier(self):
         gc_ll_descr = self.gc_ll_descr
diff --git a/pypy/jit/backend/test/runner_test.py b/pypy/jit/backend/test/runner_test.py
--- a/pypy/jit/backend/test/runner_test.py
+++ b/pypy/jit/backend/test/runner_test.py
@@ -1835,12 +1835,12 @@
         assert not excvalue
 
     def test_cond_call_gc_wb(self):
-        def func_void(a, b):
-            record.append((a, b))
+        def func_void(a):
+            record.append(a)
         record = []
         #
         S = lltype.GcStruct('S', ('tid', lltype.Signed))
-        FUNC = self.FuncType([lltype.Ptr(S), lltype.Ptr(S)], lltype.Void)
+        FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
         func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
         funcbox = self.get_funcbox(self.cpu, func_ptr)
         class WriteBarrierDescr(AbstractDescr):
@@ -1866,26 +1866,25 @@
                                    [BoxPtr(sgcref), ConstPtr(tgcref)],
                                    'void', descr=WriteBarrierDescr())
             if cond:
-                assert record == [(s, t)]
+                assert record == [s]
             else:
                 assert record == []
 
     def test_cond_call_gc_wb_array(self):
-        def func_void(a, b, c):
-            record.append((a, b, c))
+        def func_void(a):
+            record.append(a)
         record = []
         #
         S = lltype.GcStruct('S', ('tid', lltype.Signed))
-        FUNC = self.FuncType([lltype.Ptr(S), lltype.Signed, lltype.Ptr(S)],
-                             lltype.Void)
+        FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
         func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
         funcbox = self.get_funcbox(self.cpu, func_ptr)
         class WriteBarrierDescr(AbstractDescr):
             jit_wb_if_flag = 4096
             jit_wb_if_flag_byteofs = struct.pack("i", 4096).index('\x10')
             jit_wb_if_flag_singlebyte = 0x10
-            jit_wb_cards_set = 0
-            def get_write_barrier_from_array_fn(self, cpu):
+            jit_wb_cards_set = 0       # <= without card marking
+            def get_write_barrier_fn(self, cpu):
                 return funcbox.getint()
         #
         for cond in [False, True]:
@@ -1902,13 +1901,15 @@
                        [BoxPtr(sgcref), ConstInt(123), BoxPtr(sgcref)],
                        'void', descr=WriteBarrierDescr())
             if cond:
-                assert record == [(s, 123, s)]
+                assert record == [s]
             else:
                 assert record == []
 
     def test_cond_call_gc_wb_array_card_marking_fast_path(self):
-        def func_void(a, b, c):
-            record.append((a, b, c))
+        def func_void(a):
+            record.append(a)
+            if cond == 1:      # the write barrier sets the flag
+                s.data.tid |= 32768
         record = []
         #
         S = lltype.Struct('S', ('tid', lltype.Signed))
@@ -1922,34 +1923,40 @@
                                      ('card6', lltype.Char),
                                      ('card7', lltype.Char),
                                      ('data',  S))
-        FUNC = self.FuncType([lltype.Ptr(S), lltype.Signed, lltype.Ptr(S)],
-                             lltype.Void)
+        FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
         func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
         funcbox = self.get_funcbox(self.cpu, func_ptr)
         class WriteBarrierDescr(AbstractDescr):
             jit_wb_if_flag = 4096
             jit_wb_if_flag_byteofs = struct.pack("i", 4096).index('\x10')
             jit_wb_if_flag_singlebyte = 0x10
-            jit_wb_cards_set = 8192
-            jit_wb_cards_set_byteofs = struct.pack("i", 8192).index('\x20')
-            jit_wb_cards_set_singlebyte = 0x20
+            jit_wb_cards_set = 32768
+            jit_wb_cards_set_byteofs = struct.pack("i", 32768).index('\x80')
+            jit_wb_cards_set_singlebyte = -0x80
             jit_wb_card_page_shift = 7
             def get_write_barrier_from_array_fn(self, cpu):
                 return funcbox.getint()
         #
-        for BoxIndexCls in [BoxInt, ConstInt]:
-            for cond in [False, True]:
+        for BoxIndexCls in [BoxInt, ConstInt]*3:
+            for cond in [-1, 0, 1, 2]:
+                # cond=-1:GCFLAG_TRACK_YOUNG_PTRS, GCFLAG_CARDS_SET are not set
+                # cond=0: GCFLAG_CARDS_SET is never set
+                # cond=1: GCFLAG_CARDS_SET is not set, but the wb sets it
+                # cond=2: GCFLAG_CARDS_SET is already set
                 print
                 print '_'*79
                 print 'BoxIndexCls =', BoxIndexCls
-                print 'JIT_WB_CARDS_SET =', cond
+                print 'testing cond =', cond
                 print
                 value = random.randrange(-sys.maxint, sys.maxint)
-                value |= 4096
-                if cond:
-                    value |= 8192
+                if cond >= 0:
+                    value |= 4096
                 else:
-                    value &= ~8192
+                    value &= ~4096
+                if cond == 2:
+                    value |= 32768
+                else:
+                    value &= ~32768
                 s = lltype.malloc(S_WITH_CARDS, immortal=True, zero=True)
                 s.data.tid = value
                 sgcref = rffi.cast(llmemory.GCREF, s.data)
@@ -1958,11 +1965,13 @@
                 self.execute_operation(rop.COND_CALL_GC_WB_ARRAY,
                            [BoxPtr(sgcref), box_index, BoxPtr(sgcref)],
                            'void', descr=WriteBarrierDescr())
-                if cond:
+                if cond in [0, 1]:
+                    assert record == [s.data]
+                else:
                     assert record == []
+                if cond in [1, 2]:
                     assert s.card6 == '\x02'
                 else:
-                    assert record == [(s.data, (9<<7) + 17, s.data)]
                     assert s.card6 == '\x00'
                 assert s.card0 == '\x00'
                 assert s.card1 == '\x00'
@@ -1971,6 +1980,9 @@
                 assert s.card4 == '\x00'
                 assert s.card5 == '\x00'
                 assert s.card7 == '\x00'
+                if cond == 1:
+                    value |= 32768
+                assert s.data.tid == value
 
     def test_force_operations_returning_void(self):
         values = []
diff --git a/pypy/jit/backend/x86/assembler.py b/pypy/jit/backend/x86/assembler.py
--- a/pypy/jit/backend/x86/assembler.py
+++ b/pypy/jit/backend/x86/assembler.py
@@ -10,7 +10,7 @@
 from pypy.rlib.jit import AsmInfo
 from pypy.jit.backend.model import CompiledLoopToken
 from pypy.jit.backend.x86.regalloc import (RegAlloc, get_ebp_ofs, _get_scale,
-    gpr_reg_mgr_cls, _valid_addressing_size)
+    gpr_reg_mgr_cls, xmm_reg_mgr_cls, _valid_addressing_size)
 
 from pypy.jit.backend.x86.arch import (FRAME_FIXED_SIZE, FORCE_INDEX_OFS, WORD,
                                        IS_X86_32, IS_X86_64)
@@ -83,6 +83,7 @@
         self.float_const_abs_addr = 0
         self.malloc_slowpath1 = 0
         self.malloc_slowpath2 = 0
+        self.wb_slowpath = [0, 0, 0, 0]
         self.memcpy_addr = 0
         self.setup_failure_recovery()
         self._debug = False
@@ -109,9 +110,13 @@
         self.memcpy_addr = self.cpu.cast_ptr_to_int(support.memcpy_fn)
         self._build_failure_recovery(False)
         self._build_failure_recovery(True)
+        self._build_wb_slowpath(False)
+        self._build_wb_slowpath(True)
         if self.cpu.supports_floats:
             self._build_failure_recovery(False, withfloats=True)
             self._build_failure_recovery(True, withfloats=True)
+            self._build_wb_slowpath(False, withfloats=True)
+            self._build_wb_slowpath(True, withfloats=True)
             support.ensure_sse2_floats()
             self._build_float_constants()
         self._build_propagate_exception_path()
@@ -344,6 +349,82 @@
         rawstart = mc.materialize(self.cpu.asmmemmgr, [])
         self.stack_check_slowpath = rawstart
 
+    def _build_wb_slowpath(self, withcards, withfloats=False):
+        descr = self.cpu.gc_ll_descr.write_barrier_descr
+        if descr is None:
+            return
+        if not withcards:
+            func = descr.get_write_barrier_fn(self.cpu)
+        else:
+            if descr.jit_wb_cards_set == 0:
+                return
+            func = descr.get_write_barrier_from_array_fn(self.cpu)
+            if func == 0:
+                return
+        #
+        # This builds a helper function called from the slow path of
+        # write barriers.  It must save all registers, and optionally
+        # all XMM registers.  It takes a single argument just pushed
+        # on the stack even on X86_64.  It must restore stack alignment
+        # accordingly.
+        mc = codebuf.MachineCodeBlockWrapper()
+        #
+        frame_size = (1 +     # my argument, considered part of my frame
+                      1 +     # my return address
+                      len(gpr_reg_mgr_cls.save_around_call_regs))
+        if withfloats:
+            frame_size += 16     # X86_32: 16 words for 8 registers;
+                                 # X86_64: just 16 registers
+        if IS_X86_32:
+            frame_size += 1      # argument to pass to the call
+        #
+        # align to a multiple of 16 bytes
+        frame_size = (frame_size + (CALL_ALIGN-1)) & ~(CALL_ALIGN-1)
+        #
+        correct_esp_by = (frame_size - 2) * WORD
+        mc.SUB_ri(esp.value, correct_esp_by)
+        #
+        ofs = correct_esp_by
+        if withfloats:
+            for reg in xmm_reg_mgr_cls.save_around_call_regs:
+                ofs -= 8
+                mc.MOVSD_sx(ofs, reg.value)
+        for reg in gpr_reg_mgr_cls.save_around_call_regs:
+            ofs -= WORD
+            mc.MOV_sr(ofs, reg.value)
+        #
+        if IS_X86_32:
+            mc.MOV_rs(eax.value, (frame_size - 1) * WORD)
+            mc.MOV_sr(0, eax.value)
+        elif IS_X86_64:
+            mc.MOV_rs(edi.value, (frame_size - 1) * WORD)
+        mc.CALL(imm(func))
+        #
+        if withcards:
+            # A final TEST8 before the RET, for the caller.  Careful to
+            # not follow this instruction with another one that changes
+            # the status of the CPU flags!
+            mc.MOV_rs(eax.value, (frame_size - 1) * WORD)
+            mc.TEST8(addr_add_const(eax, descr.jit_wb_if_flag_byteofs),
+                     imm(-0x80))
+        #
+        ofs = correct_esp_by
+        if withfloats:
+            for reg in xmm_reg_mgr_cls.save_around_call_regs:
+                ofs -= 8
+                mc.MOVSD_xs(reg.value, ofs)
+        for reg in gpr_reg_mgr_cls.save_around_call_regs:
+            ofs -= WORD
+            mc.MOV_rs(reg.value, ofs)
+        #
+        # ADD esp, correct_esp_by --- but cannot use ADD, because
+        # of its effects on the CPU flags
+        mc.LEA_rs(esp.value, correct_esp_by)
+        mc.RET16_i(WORD)
+        #
+        rawstart = mc.materialize(self.cpu.asmmemmgr, [])
+        self.wb_slowpath[withcards + 2 * withfloats] = rawstart
+
     @staticmethod
     @rgc.no_collect
     def _release_gil_asmgcc(css):
@@ -2324,102 +2405,83 @@
 
     def genop_discard_cond_call_gc_wb(self, op, arglocs):
         # Write code equivalent to write_barrier() in the GC: it checks
-        # a flag in the object at arglocs[0], and if set, it calls the
-        # function remember_young_pointer() from the GC.  The arguments
-        # to the call are in arglocs[:N].  The rest, arglocs[N:], contains
-        # registers that need to be saved and restored across the call.
-        # N is either 2 (regular write barrier) or 3 (array write barrier).
+        # a flag in the object at arglocs[0], and if set, it calls a
+        # helper piece of assembler.  The latter saves registers as needed
+        # and call the function jit_remember_young_pointer() from the GC.
         descr = op.getdescr()
         if we_are_translated():
             cls = self.cpu.gc_ll_descr.has_write_barrier_class()
             assert cls is not None and isinstance(descr, cls)
         #
         opnum = op.getopnum()
-        if opnum == rop.COND_CALL_GC_WB:
-            N = 2
-            func = descr.get_write_barrier_fn(self.cpu)
-            card_marking = False
-        elif opnum == rop.COND_CALL_GC_WB_ARRAY:
-            N = 3
-            func = descr.get_write_barrier_from_array_fn(self.cpu)
-            assert func != 0
-            card_marking = descr.jit_wb_cards_set != 0
-        else:
-            raise AssertionError(opnum)
+        card_marking = False
+        mask = descr.jit_wb_if_flag_singlebyte
+        if opnum == rop.COND_CALL_GC_WB_ARRAY and descr.jit_wb_cards_set != 0:
+            # assumptions the rest of the function depends on:
+            assert (descr.jit_wb_cards_set_byteofs ==
+                    descr.jit_wb_if_flag_byteofs)
+            assert descr.jit_wb_cards_set_singlebyte == -0x80
+            card_marking = True
+            mask = descr.jit_wb_if_flag_singlebyte | -0x80
         #
         loc_base = arglocs[0]
         self.mc.TEST8(addr_add_const(loc_base, descr.jit_wb_if_flag_byteofs),
-                      imm(descr.jit_wb_if_flag_singlebyte))
+                      imm(mask))
         self.mc.J_il8(rx86.Conditions['Z'], 0) # patched later
         jz_location = self.mc.get_relative_pos()
 
         # for cond_call_gc_wb_array, also add another fast path:
         # if GCFLAG_CARDS_SET, then we can just set one bit and be done
         if card_marking:
-            self.mc.TEST8(addr_add_const(loc_base,
-                                         descr.jit_wb_cards_set_byteofs),
-                          imm(descr.jit_wb_cards_set_singlebyte))
-            self.mc.J_il8(rx86.Conditions['NZ'], 0) # patched later
-            jnz_location = self.mc.get_relative_pos()
+            # GCFLAG_CARDS_SET is in this byte at 0x80, so this fact can
+            # been checked by the status flags of the previous TEST8
+            self.mc.J_il8(rx86.Conditions['S'], 0) # patched later
+            js_location = self.mc.get_relative_pos()
         else:
-            jnz_location = 0
+            js_location = 0
 
-        # the following is supposed to be the slow path, so whenever possible
-        # we choose the most compact encoding over the most efficient one.
-        if IS_X86_32:
-            limit = -1      # push all arglocs on the stack
-        elif IS_X86_64:
-            limit = N - 1   # push only arglocs[N:] on the stack
-        for i in range(len(arglocs)-1, limit, -1):
-            loc = arglocs[i]
-            if isinstance(loc, RegLoc):
-                self.mc.PUSH_r(loc.value)
-            else:
-                assert not IS_X86_64 # there should only be regs in arglocs[N:]
-                self.mc.PUSH_i32(loc.getint())
-        if IS_X86_64:
-            # We clobber these registers to pass the arguments, but that's
-            # okay, because consider_cond_call_gc_wb makes sure that any
-            # caller-save registers with values in them are present in
-            # arglocs[N:] too, so they are saved on the stack above and
-            # restored below.
-            if N == 2:
-                callargs = [edi, esi]
-            else:
-                callargs = [edi, esi, edx]
-            remap_frame_layout(self, arglocs[:N], callargs,
-                               X86_64_SCRATCH_REG)
+        # Write only a CALL to the helper prepared in advance, passing it as
+        # argument the address of the structure we are writing into
+        # (the first argument to COND_CALL_GC_WB).
+        helper_num = card_marking
+        if self._regalloc.xrm.reg_bindings:
+            helper_num += 2
+        if self.wb_slowpath[helper_num] == 0:    # tests only
+            assert not we_are_translated()
+            self.cpu.gc_ll_descr.write_barrier_descr = descr
+            self._build_wb_slowpath(card_marking,
+                                    bool(self._regalloc.xrm.reg_bindings))
+            assert self.wb_slowpath[helper_num] != 0
         #
-        # misaligned stack in the call, but it's ok because the write barrier
-        # is not going to call anything more.  Also, this assumes that the
-        # write barrier does not touch the xmm registers.  (Slightly delicate
-        # assumption, given that the write barrier can end up calling the
-        # platform's malloc() from AddressStack.append().  XXX may need to
-        # be done properly)
-        self.mc.CALL(imm(func))
-        if IS_X86_32:
-            self.mc.ADD_ri(esp.value, N*WORD)
-        for i in range(N, len(arglocs)):
-            loc = arglocs[i]
-            assert isinstance(loc, RegLoc)
-            self.mc.POP_r(loc.value)
+        self.mc.PUSH(loc_base)
+        self.mc.CALL(imm(self.wb_slowpath[helper_num]))
 
-        # if GCFLAG_CARDS_SET, then we can do the whole thing that would
-        # be done in the CALL above with just four instructions, so here
-        # is an inline copy of them
         if card_marking:
-            self.mc.JMP_l8(0) # jump to the exit, patched later
-            jmp_location = self.mc.get_relative_pos()
-            # patch the JNZ above
-            offset = self.mc.get_relative_pos() - jnz_location
+            # The helper ends again with a check of the flag in the object.
+            # So here, we can simply write again a 'JNS', which will be
+            # taken if GCFLAG_CARDS_SET is still not set.
+            self.mc.J_il8(rx86.Conditions['NS'], 0) # patched later
+            jns_location = self.mc.get_relative_pos()
+            #
+            # patch the JS above
+            offset = self.mc.get_relative_pos() - js_location
             assert 0 < offset <= 127
-            self.mc.overwrite(jnz_location-1, chr(offset))
+            self.mc.overwrite(js_location-1, chr(offset))
             #
+            # case GCFLAG_CARDS_SET: emit a few instructions to do
+            # directly the card flag setting
             loc_index = arglocs[1]
             if isinstance(loc_index, RegLoc):
-                # choose a scratch register
-                tmp1 = loc_index
-                self.mc.PUSH_r(tmp1.value)
+                if IS_X86_64 and isinstance(loc_base, RegLoc):
+                    # copy loc_index into r11
+                    tmp1 = X86_64_SCRATCH_REG
+                    self.mc.MOV_rr(tmp1.value, loc_index.value)
+                    final_pop = False
+                else:
+                    # must save the register loc_index before it is mutated
+                    self.mc.PUSH_r(loc_index.value)
+                    tmp1 = loc_index
+                    final_pop = True
                 # SHR tmp, card_page_shift
                 self.mc.SHR_ri(tmp1.value, descr.jit_wb_card_page_shift)
                 # XOR tmp, -8
@@ -2427,7 +2489,9 @@
                 # BTS [loc_base], tmp
                 self.mc.BTS(addr_add_const(loc_base, 0), tmp1)
                 # done
-                self.mc.POP_r(tmp1.value)
+                if final_pop:
+                    self.mc.POP_r(loc_index.value)
+                #
             elif isinstance(loc_index, ImmedLoc):
                 byte_index = loc_index.value >> descr.jit_wb_card_page_shift
                 byte_ofs = ~(byte_index >> 3)
@@ -2435,11 +2499,12 @@
                 self.mc.OR8(addr_add_const(loc_base, byte_ofs), imm(byte_val))
             else:
                 raise AssertionError("index is neither RegLoc nor ImmedLoc")
-            # patch the JMP above
-            offset = self.mc.get_relative_pos() - jmp_location
+            #
+            # patch the JNS above
+            offset = self.mc.get_relative_pos() - jns_location
             assert 0 < offset <= 127
-            self.mc.overwrite(jmp_location-1, chr(offset))
-        #
+            self.mc.overwrite(jns_location-1, chr(offset))
+
         # patch the JZ above
         offset = self.mc.get_relative_pos() - jz_location
         assert 0 < offset <= 127
diff --git a/pypy/jit/backend/x86/regalloc.py b/pypy/jit/backend/x86/regalloc.py
--- a/pypy/jit/backend/x86/regalloc.py
+++ b/pypy/jit/backend/x86/regalloc.py
@@ -980,16 +980,6 @@
         # or setarrayitem_gc. It avoids loading it twice from the memory.
         arglocs = [self.rm.make_sure_var_in_reg(op.getarg(i), args)
                    for i in range(N)]
-        # add eax, ecx and edx as extra "arguments" to ensure they are
-        # saved and restored.  Fish in self.rm to know which of these
-        # registers really need to be saved (a bit of a hack).  Moreover,
-        # we don't save and restore any SSE register because the called
-        # function, a GC write barrier, is known not to touch them.
-        # See remember_young_pointer() in rpython/memory/gc/generation.py.
-        for v, reg in self.rm.reg_bindings.items():
-            if (reg in self.rm.save_around_call_regs
-                and self.rm.stays_alive(v)):
-                arglocs.append(reg)
         self.PerformDiscard(op, arglocs)
         self.rm.possibly_free_vars_for_op(op)
 
diff --git a/pypy/jit/backend/x86/rx86.py b/pypy/jit/backend/x86/rx86.py
--- a/pypy/jit/backend/x86/rx86.py
+++ b/pypy/jit/backend/x86/rx86.py
@@ -316,6 +316,13 @@
         assert rexbyte == 0
     return 0
 
+# REX prefixes: 'rex_w' generates a REX_W, forcing the instruction
+# to operate on 64-bit.  'rex_nw' doesn't, so the instruction operates
+# on 32-bit or less; the complete REX prefix is omitted if unnecessary.
+# 'rex_fw' is a special case which doesn't generate a REX_W but forces
+# the REX prefix in all cases.  It is only useful on instructions which
+# have an 8-bit register argument, to force access to the "sil" or "dil"
+# registers (as opposed to "ah-dh").
 rex_w  = encode_rex, 0, (0x40 | REX_W), None      # a REX.W prefix
 rex_nw = encode_rex, 0, 0, None                   # an optional REX prefix
 rex_fw = encode_rex, 0, 0x40, None                # a forced REX prefix
@@ -496,9 +503,9 @@
     AND8_rr = insn(rex_fw, '\x20', byte_register(1), byte_register(2,8), '\xC0')
 
     OR8_rr = insn(rex_fw, '\x08', byte_register(1), byte_register(2,8), '\xC0')
-    OR8_mi = insn(rex_fw, '\x80', orbyte(1<<3), mem_reg_plus_const(1),
+    OR8_mi = insn(rex_nw, '\x80', orbyte(1<<3), mem_reg_plus_const(1),
                   immediate(2, 'b'))
-    OR8_ji = insn(rex_fw, '\x80', orbyte(1<<3), abs_, immediate(1),
+    OR8_ji = insn(rex_nw, '\x80', orbyte(1<<3), abs_, immediate(1),
                   immediate(2, 'b'))
 
     NEG_r = insn(rex_w, '\xF7', register(1), '\xD8')
@@ -531,7 +538,13 @@
 
     PUSH_r = insn(rex_nw, register(1), '\x50')
     PUSH_b = insn(rex_nw, '\xFF', orbyte(6<<3), stack_bp(1))
+    PUSH_i8 = insn('\x6A', immediate(1, 'b'))
     PUSH_i32 = insn('\x68', immediate(1, 'i'))
+    def PUSH_i(mc, immed):
+        if single_byte(immed):
+            mc.PUSH_i8(immed)
+        else:
+            mc.PUSH_i32(immed)
 
     POP_r = insn(rex_nw, register(1), '\x58')
     POP_b = insn(rex_nw, '\x8F', orbyte(0<<3), stack_bp(1))
diff --git a/pypy/jit/backend/x86/test/test_rx86.py b/pypy/jit/backend/x86/test/test_rx86.py
--- a/pypy/jit/backend/x86/test/test_rx86.py
+++ b/pypy/jit/backend/x86/test/test_rx86.py
@@ -183,7 +183,8 @@
 
 def test_push32():
     cb = CodeBuilder32
-    assert_encodes_as(cb, 'PUSH_i32', (9,), '\x68\x09\x00\x00\x00')
+    assert_encodes_as(cb, 'PUSH_i', (0x10009,), '\x68\x09\x00\x01\x00')
+    assert_encodes_as(cb, 'PUSH_i', (9,), '\x6A\x09')
 
 def test_sub_ji8():
     cb = CodeBuilder32
diff --git a/pypy/jit/backend/x86/test/test_ztranslation.py b/pypy/jit/backend/x86/test/test_ztranslation.py
--- a/pypy/jit/backend/x86/test/test_ztranslation.py
+++ b/pypy/jit/backend/x86/test/test_ztranslation.py
@@ -69,7 +69,7 @@
         #
         from pypy.rpython.lltypesystem import lltype, rffi
         from pypy.rlib.libffi import types, CDLL, ArgChain
-        from pypy.rlib.test.test_libffi import get_libm_name
+        from pypy.rlib.test.test_clibffi import get_libm_name
         libm_name = get_libm_name(sys.platform)
         jitdriver2 = JitDriver(greens=[], reds = ['i', 'func', 'res', 'x'])
         def libffi_stuff(i, j):
diff --git a/pypy/module/__pypy__/__init__.py b/pypy/module/__pypy__/__init__.py
--- a/pypy/module/__pypy__/__init__.py
+++ b/pypy/module/__pypy__/__init__.py
@@ -44,6 +44,8 @@
         'list_strategy'             : 'interp_magic.list_strategy',
         'validate_fd'               : 'interp_magic.validate_fd',
     }
+    if sys.platform == 'win32':
+        interpleveldefs['get_console_cp'] = 'interp_magic.get_console_cp'
 
     submodules = {
         "builders": BuildersModule,
diff --git a/pypy/module/__pypy__/interp_magic.py b/pypy/module/__pypy__/interp_magic.py
--- a/pypy/module/__pypy__/interp_magic.py
+++ b/pypy/module/__pypy__/interp_magic.py
@@ -88,3 +88,10 @@
         rposix.validate_fd(fd)
     except OSError, e:
         raise wrap_oserror(space, e)
+
+def get_console_cp(space):
+    from pypy.rlib import rwin32    # Windows only
+    return space.newtuple([
+        space.wrap('cp%d' % rwin32.GetConsoleCP()),
+        space.wrap('cp%d' % rwin32.GetConsoleOutputCP()),
+        ])
diff --git a/pypy/module/_ffi/__init__.py b/pypy/module/_ffi/__init__.py
--- a/pypy/module/_ffi/__init__.py
+++ b/pypy/module/_ffi/__init__.py
@@ -1,4 +1,5 @@
 from pypy.interpreter.mixedmodule import MixedModule
+import os
 
 class Module(MixedModule):
 
@@ -10,7 +11,8 @@
         '_StructDescr': 'interp_struct.W__StructDescr',
         'Field':     'interp_struct.W_Field',
     }
-
+    if os.name == 'nt':
+        interpleveldefs['WinDLL'] = 'interp_funcptr.W_WinDLL'
     appleveldefs = {
         'Structure': 'app_struct.Structure',
         }
diff --git a/pypy/module/_ffi/interp_funcptr.py b/pypy/module/_ffi/interp_funcptr.py
--- a/pypy/module/_ffi/interp_funcptr.py
+++ b/pypy/module/_ffi/interp_funcptr.py
@@ -9,6 +9,7 @@
 #
 from pypy.rlib import jit
 from pypy.rlib import libffi
+from pypy.rlib.clibffi import get_libc_name, StackCheckError
 from pypy.rlib.rdynload import DLOpenError
 from pypy.rlib.rarithmetic import intmask, r_uint
 from pypy.rlib.objectmodel import we_are_translated
@@ -59,7 +60,10 @@
         self = jit.promote(self)
         argchain = self.build_argchain(space, args_w)
         func_caller = CallFunctionConverter(space, self.func, argchain)
-        return func_caller.do_and_wrap(self.w_restype)
+        try:
+            return func_caller.do_and_wrap(self.w_restype)
+        except StackCheckError, e:
+            raise OperationError(space.w_ValueError, space.wrap(e.message))
         #return self._do_call(space, argchain)
 
     def free_temp_buffers(self, space):
@@ -230,13 +234,14 @@
     restype = unwrap_ffitype(space, w_restype, allow_void=True)
     return argtypes_w, argtypes, w_restype, restype
 
- at unwrap_spec(addr=r_uint, name=str)
-def descr_fromaddr(space, w_cls, addr, name, w_argtypes, w_restype):
+ at unwrap_spec(addr=r_uint, name=str, flags=int)
+def descr_fromaddr(space, w_cls, addr, name, w_argtypes, 
+                    w_restype, flags=libffi.FUNCFLAG_CDECL):
     argtypes_w, argtypes, w_restype, restype = unpack_argtypes(space,
                                                                w_argtypes,
                                                                w_restype)
     addr = rffi.cast(rffi.VOIDP, addr)
-    func = libffi.Func(name, argtypes, restype, addr)
+    func = libffi.Func(name, argtypes, restype, addr, flags)
     return W_FuncPtr(func, argtypes_w, w_restype)
 
 
@@ -254,6 +259,7 @@
 
 class W_CDLL(Wrappable):
     def __init__(self, space, name, mode):
+        self.flags = libffi.FUNCFLAG_CDECL
         self.space = space
         if name is None:
             self.name = "<None>"
@@ -271,7 +277,8 @@
                                                                    w_argtypes,
                                                                    w_restype)
         try:
-            func = self.cdll.getpointer(name, argtypes, restype)
+            func = self.cdll.getpointer(name, argtypes, restype, 
+                                            flags = self.flags)
         except KeyError:
             raise operationerrfmt(space.w_AttributeError,
                                   "No symbol %s found in library %s", name, self.name)
@@ -300,10 +307,26 @@
     getaddressindll = interp2app(W_CDLL.getaddressindll),
     )
 
+class W_WinDLL(W_CDLL):
+    def __init__(self, space, name, mode):
+        W_CDLL.__init__(self, space, name, mode)
+        self.flags = libffi.FUNCFLAG_STDCALL
+
+ at unwrap_spec(name='str_or_None', mode=int)
+def descr_new_windll(space, w_type, name, mode=-1):
+    return space.wrap(W_WinDLL(space, name, mode))
+
+
+W_WinDLL.typedef = TypeDef(
+    '_ffi.WinDLL',
+    __new__     = interp2app(descr_new_windll),
+    getfunc     = interp2app(W_WinDLL.getfunc),
+    getaddressindll = interp2app(W_WinDLL.getaddressindll),
+    )
+
 # ========================================================================
 
 def get_libc(space):
-    from pypy.rlib.clibffi import get_libc_name
     try:
         return space.wrap(W_CDLL(space, get_libc_name(), -1))
     except OSError, e:
diff --git a/pypy/module/_ffi/test/test_funcptr.py b/pypy/module/_ffi/test/test_funcptr.py
--- a/pypy/module/_ffi/test/test_funcptr.py
+++ b/pypy/module/_ffi/test/test_funcptr.py
@@ -1,11 +1,11 @@
 from pypy.conftest import gettestobjspace
-from pypy.translator.platform import platform
-from pypy.translator.tool.cbuild import ExternalCompilationInfo
-from pypy.module._rawffi.interp_rawffi import TYPEMAP
-from pypy.module._rawffi.tracker import Tracker
-from pypy.translator.platform import platform
+from pypy.rpython.lltypesystem import rffi
+from pypy.rlib.clibffi import get_libc_name
+from pypy.rlib.libffi import types
+from pypy.rlib.libffi import CDLL
+from pypy.rlib.test.test_clibffi import get_libm_name
 
-import os, sys, py
+import sys, py
 
 class BaseAppTestFFI(object):
 
@@ -37,9 +37,6 @@
         return str(platform.compile([c_file], eci, 'x', standalone=False))
 
     def setup_class(cls):
-        from pypy.rpython.lltypesystem import rffi
-        from pypy.rlib.libffi import get_libc_name, CDLL, types
-        from pypy.rlib.test.test_libffi import get_libm_name
         space = gettestobjspace(usemodules=('_ffi', '_rawffi'))
         cls.space = space
         cls.w_iswin32 = space.wrap(sys.platform == 'win32')
@@ -96,7 +93,7 @@
 
     def test_getaddressindll(self):
         import sys
-        from _ffi import CDLL, types
+        from _ffi import CDLL
         libm = CDLL(self.libm_name)
         pow_addr = libm.getaddressindll('pow')
         fff = sys.maxint*2-1
@@ -105,7 +102,6 @@
         assert pow_addr == self.pow_addr & fff
 
     def test_func_fromaddr(self):
-        import sys
         from _ffi import CDLL, types, FuncPtr
         libm = CDLL(self.libm_name)
         pow_addr = libm.getaddressindll('pow')
@@ -569,3 +565,66 @@
             skip("unix specific")
         libnone = CDLL(None)
         raises(AttributeError, "libnone.getfunc('I_do_not_exist', [], types.void)")
+
+    def test_calling_convention1(self):
+        if not self.iswin32:
+            skip("windows specific")
+        from _ffi import WinDLL, types
+        libm = WinDLL(self.libm_name)
+        pow = libm.getfunc('pow', [types.double, types.double], types.double)
+        try:
+            pow(2, 3)
+        except ValueError, e:
+            assert e.message.startswith('Procedure called with')
+        else:
+            assert 0, 'test must assert, wrong calling convention'
+
+    def test_calling_convention2(self):
+        if not self.iswin32:
+            skip("windows specific")
+        from _ffi import WinDLL, types
+        kernel = WinDLL('Kernel32.dll')
+        sleep = kernel.getfunc('Sleep', [types.uint], types.void)
+        sleep(10)
+
+    def test_calling_convention3(self):
+        if not self.iswin32:
+            skip("windows specific")
+        from _ffi import CDLL, types
+        wrong_kernel = CDLL('Kernel32.dll')
+        wrong_sleep = wrong_kernel.getfunc('Sleep', [types.uint], types.void)
+        try:
+            wrong_sleep(10)
+        except ValueError, e:
+            assert e.message.startswith('Procedure called with')
+        else:
+            assert 0, 'test must assert, wrong calling convention'
+
+    def test_func_fromaddr2(self):
+        if not self.iswin32:
+            skip("windows specific")
+        from _ffi import CDLL, types, FuncPtr
+        from _rawffi import FUNCFLAG_STDCALL
+        libm = CDLL(self.libm_name)
+        pow_addr = libm.getaddressindll('pow')
+        wrong_pow = FuncPtr.fromaddr(pow_addr, 'pow', 
+                [types.double, types.double], types.double, FUNCFLAG_STDCALL)
+        try:
+            wrong_pow(2, 3) == 8
+        except ValueError, e:
+            assert e.message.startswith('Procedure called with')
+        else:
+            assert 0, 'test must assert, wrong calling convention'
+
+    def test_func_fromaddr3(self):
+        if not self.iswin32:
+            skip("windows specific")
+        from _ffi import WinDLL, types, FuncPtr
+        from _rawffi import FUNCFLAG_STDCALL
+        kernel = WinDLL('Kernel32.dll')
+        sleep_addr = kernel.getaddressindll('Sleep')
+        sleep = FuncPtr.fromaddr(sleep_addr, 'sleep', [types.uint], 
+                            types.void, FUNCFLAG_STDCALL)
+        sleep(10)
+
+ 
diff --git a/pypy/module/_ffi/test/test_type_converter.py b/pypy/module/_ffi/test/test_type_converter.py
--- a/pypy/module/_ffi/test/test_type_converter.py
+++ b/pypy/module/_ffi/test/test_type_converter.py
@@ -144,6 +144,7 @@
     get_unichar_p = get_all
     get_float = get_all
     get_singlefloat = get_all
+    get_unsigned_which_fits_into_a_signed = get_all
     
     def convert(self, w_ffitype, val):
         self.val = val
diff --git a/pypy/module/_minimal_curses/fficurses.py b/pypy/module/_minimal_curses/fficurses.py
--- a/pypy/module/_minimal_curses/fficurses.py
+++ b/pypy/module/_minimal_curses/fficurses.py
@@ -8,11 +8,20 @@
 from pypy.rpython.extfunc import register_external
 from pypy.module._minimal_curses import interp_curses
 from pypy.translator.tool.cbuild import ExternalCompilationInfo
+from sys import platform
 
-eci = ExternalCompilationInfo(
-    includes = ['curses.h', 'term.h'],
-    libraries = ['curses'],
-)
+_CYGWIN = platform == 'cygwin'
+
+if _CYGWIN:
+    eci = ExternalCompilationInfo(
+        includes = ['ncurses/curses.h', 'ncurses/term.h'],
+        libraries = ['curses'],
+    )
+else:
+    eci = ExternalCompilationInfo(
+        includes = ['curses.h', 'term.h'],
+        libraries = ['curses'],
+    )
 
 rffi_platform.verify_eci(eci)
 
diff --git a/pypy/module/_socket/test/test_sock_app.py b/pypy/module/_socket/test/test_sock_app.py
--- a/pypy/module/_socket/test/test_sock_app.py
+++ b/pypy/module/_socket/test/test_sock_app.py
@@ -618,9 +618,12 @@
         except timeout:
             pass
         t.recv(count)    
-        # test sendall() timeout, be sure to send data larger than the
-        # socket buffer
-        raises(timeout, cli.sendall, 'foobar' * 7000)
+        # test sendall() timeout
+        try:
+            while 1:
+                cli.sendall('foobar' * 70)
+        except timeout:
+            pass
         # done
         cli.close()
         t.close()
diff --git a/pypy/module/cpyext/test/test_cpyext.py b/pypy/module/cpyext/test/test_cpyext.py
--- a/pypy/module/cpyext/test/test_cpyext.py
+++ b/pypy/module/cpyext/test/test_cpyext.py
@@ -36,7 +36,7 @@
 class AppTestApi:
     def setup_class(cls):
         cls.space = gettestobjspace(usemodules=['cpyext', 'thread', '_rawffi', 'array'])
-        from pypy.rlib.libffi import get_libc_name
+        from pypy.rlib.clibffi import get_libc_name
         cls.w_libc = cls.space.wrap(get_libc_name())
 
     def test_load_error(self):
diff --git a/pypy/module/micronumpy/interp_boxes.py b/pypy/module/micronumpy/interp_boxes.py
--- a/pypy/module/micronumpy/interp_boxes.py
+++ b/pypy/module/micronumpy/interp_boxes.py
@@ -12,15 +12,18 @@
 MIXIN_32 = (int_typedef,) if LONG_BIT == 32 else ()
 MIXIN_64 = (int_typedef,) if LONG_BIT == 64 else ()
 
+
 def new_dtype_getter(name):
     def _get_dtype(space):
         from pypy.module.micronumpy.interp_dtype import get_dtype_cache
         return getattr(get_dtype_cache(space), "w_%sdtype" % name)
+
     def new(space, w_subtype, w_value):
         dtype = _get_dtype(space)
         return dtype.itemtype.coerce_subtype(space, w_subtype, w_value)
     return func_with_new_name(new, name + "_box_new"), staticmethod(_get_dtype)
 
+
 class PrimitiveBox(object):
     _mixin_ = True
 
@@ -30,6 +33,7 @@
     def convert_to(self, dtype):
         return dtype.box(self.value)
 
+
 class W_GenericBox(Wrappable):
     _attrs_ = ()
 
@@ -71,7 +75,7 @@
     def _binop_right_impl(ufunc_name):
         def impl(self, space, w_other, w_out=None):
             from pypy.module.micronumpy import interp_ufuncs
-            return getattr(interp_ufuncs.get(space), ufunc_name).call(space, 
+            return getattr(interp_ufuncs.get(space), ufunc_name).call(space,
                                                             [w_other, self, w_out])
         return func_with_new_name(impl, "binop_right_%s_impl" % ufunc_name)
 
@@ -132,6 +136,9 @@
         w_remainder = self.descr_rmod(space, w_other)
         return space.newtuple([w_quotient, w_remainder])
 
+    def descr_hash(self, space):
+        return space.hash(self.item(space))
+
     def item(self, space):
         return self.get_dtype(space).itemtype.to_builtin_type(space, self)
 
@@ -315,6 +322,8 @@
     __abs__ = interp2app(W_GenericBox.descr_abs),
     __invert__ = interp2app(W_GenericBox.descr_invert),
 
+    __hash__ = interp2app(W_GenericBox.descr_hash),
+
     tolist = interp2app(W_GenericBox.item),
 )
 
@@ -440,4 +449,4 @@
     __module__ = "numpypy",
     __new__ = interp2app(W_UnicodeBox.descr__new__unicode_box.im_func),
 )
-                                          
+
diff --git a/pypy/module/micronumpy/interp_numarray.py b/pypy/module/micronumpy/interp_numarray.py
--- a/pypy/module/micronumpy/interp_numarray.py
+++ b/pypy/module/micronumpy/interp_numarray.py
@@ -690,11 +690,17 @@
         return self.getitem(offset).convert_to(longdtype).item(
             space)
 
+    @jit.unroll_safe
     def descr_item(self, space, w_arg=None):
         if space.is_w(w_arg, space.w_None):
-            if not isinstance(self, Scalar):
-                raise OperationError(space.w_ValueError, space.wrap("index out of bounds"))
-            return self.value.item(space)
+            if isinstance(self, Scalar):
+                return self.value.item(space)
+            if support.product(self.shape) == 1:
+                return self.descr_getitem(space,
+                                          space.newtuple([space.wrap(0) for i
+                                                   in range(len(self.shape))]))
+            raise OperationError(space.w_ValueError,
+                                 space.wrap("index out of bounds"))
         if space.isinstance_w(w_arg, space.w_int):
             if isinstance(self, Scalar):
                 raise OperationError(space.w_ValueError, space.wrap("index out of bounds"))
diff --git a/pypy/module/micronumpy/test/test_dtypes.py b/pypy/module/micronumpy/test/test_dtypes.py
--- a/pypy/module/micronumpy/test/test_dtypes.py
+++ b/pypy/module/micronumpy/test/test_dtypes.py
@@ -211,33 +211,23 @@
 
         a = array(range(10), dtype=int64)
         b = array([0] * 10, dtype=int64)
-        for idx in b: a[idx] += 1
+        for idx in b:
+            a[idx] += 1
 
-    def test_hash_int8(self):
-        from _numpypy import int8
+    def test_hash(self):
+        import _numpypy as numpy
+        for tp, value in [
+            (numpy.int8, 4),
+            (numpy.int16, 5),
+            (numpy.uint32, 7),
+            (numpy.int64, 3),
+            (numpy.float32, 2.0),
+            (numpy.float64, 4.32),
+        ]:
+            assert hash(tp(value)) == hash(value)
 
-        hash(int8(0))
-        d = {int8(5):99}
 
-    def test_hash_int16(self):
-        from _numpypy import int16
-
-        hash(int16(0))
-        d = {int16(99):42}
-
-    def test_hash_int32(self):
-        from _numpypy import int32
-
-        hash(int32(0))
-        d = {int32(5):99}
-
-    def test_hash_int64(self):
-        from _numpypy import int64
-
-        hash(int64(0))
-        d = {int64(99):42}
-
-class AppTestTypes(BaseNumpyAppTest):    
+class AppTestTypes(BaseNumpyAppTest):
     def test_abstract_types(self):
         import _numpypy as numpy
         raises(TypeError, numpy.generic, 0)
@@ -461,7 +451,7 @@
     def test_various_types(self):
         import _numpypy as numpy
         import sys
-        
+
         assert numpy.int16 is numpy.short
         assert numpy.int8 is numpy.byte
         assert numpy.bool_ is numpy.bool8
@@ -472,7 +462,7 @@
 
     def test_mro(self):
         import _numpypy as numpy
-        
+
         assert numpy.int16.__mro__ == (numpy.int16, numpy.signedinteger,
                                        numpy.integer, numpy.number,
                                        numpy.generic, object)
@@ -528,7 +518,7 @@
 class AppTestStrUnicodeDtypes(BaseNumpyAppTest):
     def test_str_unicode(self):
         from _numpypy import str_, unicode_, character, flexible, generic
-        
+
         assert str_.mro() == [str_, str, basestring, character, flexible, generic, object]
         assert unicode_.mro() == [unicode_, unicode, basestring, character, flexible, generic, object]
 
@@ -588,7 +578,7 @@
         from _numpypy import dtype
         d = dtype({'names': ['a', 'b', 'c'],
                    })
-        
+
 class AppTestNotDirect(BaseNumpyAppTest):
     def setup_class(cls):
         BaseNumpyAppTest.setup_class.im_func(cls)
diff --git a/pypy/module/micronumpy/test/test_numarray.py b/pypy/module/micronumpy/test/test_numarray.py
--- a/pypy/module/micronumpy/test/test_numarray.py
+++ b/pypy/module/micronumpy/test/test_numarray.py
@@ -1248,6 +1248,7 @@
         a = arange(3*2*6).reshape((3,2,6))
         b = arange(3*2*6)[::-1].reshape((2,6,3))
         assert dot(a, b)[2,0,1,2] == 1140
+        assert (dot([[1,2],[3,4]],[5,6]) == [17, 39]).all()
 
     def test_dot_constant(self):
         from _numpypy import array, dot
@@ -1999,6 +2000,7 @@
         assert a[::2].item(1) == 3
         assert (a + a).item(1) == 4
         raises(ValueError, "array(5).item(1)")
+        assert array([1]).item() == 1
 
 class AppTestSupport(BaseNumpyAppTest):
     def setup_class(cls):
diff --git a/pypy/module/micronumpy/types.py b/pypy/module/micronumpy/types.py
--- a/pypy/module/micronumpy/types.py
+++ b/pypy/module/micronumpy/types.py
@@ -13,11 +13,13 @@
 from pypy.tool.sourcetools import func_with_new_name
 from pypy.rlib import jit
 
+
 VOID_STORAGE = lltype.Array(lltype.Char, hints={'nolength': True,
                                                 'render_as_void': True})
 degToRad = math.pi / 180.0
 log2 = math.log(2)
-log2e = 1./log2
+log2e = 1. / log2
+
 
 def simple_unary_op(func):
     specialize.argtype(1)(func)
@@ -66,7 +68,7 @@
 
 class BaseType(object):
     _attrs_ = ()
-    
+
     def _unimplemented_ufunc(self, *args):
         raise NotImplementedError
 
@@ -133,7 +135,7 @@
                                  width, storage, i, offset, value)
         else:
             libffi.array_setitem_T(self.T, width, storage, i, offset, value)
-        
+
 
     def store(self, arr, width, i, offset, box):
         self._write(arr.storage, width, i, offset, self.unbox(box))
@@ -242,7 +244,7 @@
 
 class NonNativePrimitive(Primitive):
     _mixin_ = True
-    
+
     def _read(self, storage, width, i, offset):
         if we_are_translated():
             res = libffi.array_getitem(clibffi.cast_type_to_ffitype(self.T),
@@ -528,7 +530,7 @@
 
     T = rffi.LONGLONG
     BoxType = interp_boxes.W_Int64Box
-    format_code = "q"    
+    format_code = "q"
 
     _coerce = func_with_new_name(_int64_coerce, '_coerce')
 
@@ -900,7 +902,7 @@
 
     T = rffi.FLOAT
     BoxType = interp_boxes.W_Float32Box
-    format_code = "f"    
+    format_code = "f"
 
 class Float64(BaseType, Float):
     _attrs_ = ()
@@ -918,7 +920,7 @@
 
 class BaseStringType(object):
     _mixin_ = True
-    
+
     def __init__(self, size=0):
         self.size = size
 
@@ -949,14 +951,14 @@
 
     def get_element_size(self):
         return self.size
-    
+
     def read(self, arr, width, i, offset, dtype=None):
         if dtype is None:
             dtype = arr.dtype
         return interp_boxes.W_VoidBox(arr, i + offset, dtype)
 
     @jit.unroll_safe
-    def coerce(self, space, dtype, w_item): 
+    def coerce(self, space, dtype, w_item):
         from pypy.module.micronumpy.interp_numarray import W_NDimArray
 
         if isinstance(w_item, interp_boxes.W_VoidBox):
diff --git a/pypy/module/posix/test/test_posix2.py b/pypy/module/posix/test/test_posix2.py
--- a/pypy/module/posix/test/test_posix2.py
+++ b/pypy/module/posix/test/test_posix2.py
@@ -945,6 +945,20 @@
         import os
         assert hasattr(os, 'kill')
 
+    def test_pipe_flush(self):
+        os = self.posix
+        ffd, gfd = os.pipe()
+        f = os.fdopen(ffd, 'r')
+        g = os.fdopen(gfd, 'w')
+        g.write('he')
+        g.flush()
+        x = f.read(1)
+        assert x == 'h'
+        f.flush()
+        x = f.read(1)
+        assert x == 'e'
+
+
 class AppTestEnvironment(object):
     def setup_class(cls):
         cls.space = space
diff --git a/pypy/module/pypyjit/test_pypy_c/test__ffi.py b/pypy/module/pypyjit/test_pypy_c/test__ffi.py
--- a/pypy/module/pypyjit/test_pypy_c/test__ffi.py
+++ b/pypy/module/pypyjit/test_pypy_c/test__ffi.py
@@ -1,11 +1,10 @@
-import py
 import sys
 from pypy.module.pypyjit.test_pypy_c.test_00_model import BaseTestPyPyC
 
 class Test__ffi(BaseTestPyPyC):
 
     def test__ffi_call(self):
-        from pypy.rlib.test.test_libffi import get_libm_name
+        from pypy.rlib.test.test_clibffi import get_libm_name
         def main(libm_name):
             try:
                 from _ffi import CDLL, types
@@ -42,7 +41,7 @@
 
 
     def test__ffi_call_frame_does_not_escape(self):
-        from pypy.rlib.test.test_libffi import get_libm_name
+        from pypy.rlib.test.test_clibffi import get_libm_name
         def main(libm_name):
             try:
                 from _ffi import CDLL, types
@@ -75,15 +74,22 @@
         assert opnames.count('new_with_vtable') == 1
 
     def test__ffi_call_releases_gil(self):
-        from pypy.rlib.test.test_libffi import get_libc_name
+        from pypy.rlib.clibffi import get_libc_name
         def main(libc_name, n):
             import time
+            import os
             from threading import Thread
-            from _ffi import CDLL, types
             #
-            libc = CDLL(libc_name)
-            sleep = libc.getfunc('sleep', [types.uint], types.uint)
-            delays = [0]*n + [1]
+            if os.name == 'nt':
+                from _ffi import WinDLL, types
+                libc = WinDLL(libc_name)
+                sleep = libc.getfunc('Sleep', [types.uint], types.uint)
+                delays = [0]*n + [1000]
+            else:
+                from _ffi import CDLL, types
+                libc = CDLL(libc_name)
+                sleep = libc.getfunc('sleep', [types.uint], types.uint)
+                delays = [0]*n + [1]
             #
             def loop_of_sleeps(i, delays):
                 for delay in delays:
@@ -97,7 +103,6 @@
                 thread.join()
             end = time.time()
             return end - start
-        #
         log = self.run(main, [get_libc_name(), 200], threshold=150,
                        import_site=True)
         assert 1 <= log.result <= 1.5 # at most 0.5 seconds of overhead
@@ -106,7 +111,7 @@
 
 
     def test_ctypes_call(self):
-        from pypy.rlib.test.test_libffi import get_libm_name
+        from pypy.rlib.test.test_clibffi import get_libm_name
         def main(libm_name):
             import ctypes
             libm = ctypes.CDLL(libm_name)
diff --git a/pypy/module/rctime/interp_time.py b/pypy/module/rctime/interp_time.py
--- a/pypy/module/rctime/interp_time.py
+++ b/pypy/module/rctime/interp_time.py
@@ -12,6 +12,15 @@
 
 _POSIX = os.name == "posix"
 _WIN = os.name == "nt"
+_CYGWIN = sys.platform == "cygwin"
+
+_time_zones = []
+if _CYGWIN:
+    _time_zones = ["GMT-12", "GMT-11", "GMT-10", "GMT-9", "GMT-8", "GMT-7",
+                   "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1",
+                   "GMT",  "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5",
+                   "GMT+6",  "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+11",
+                   "GMT+12",  "GMT+13", "GMT+14"]
 
 if _WIN:
     # Interruptible sleeps on Windows:
@@ -107,11 +116,17 @@
     CConfig.timeval = platform.Struct("struct timeval",
                                       [("tv_sec", rffi.INT),
                                        ("tv_usec", rffi.INT)])
-    CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
-        ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
-        ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
-        ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT), ("tm_gmtoff", rffi.LONG),
-        ("tm_zone", rffi.CCHARP)])
+    if _CYGWIN:
+        CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
+            ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
+            ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
+            ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT)])
+    else:
+        CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
+            ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
+            ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
+            ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT), ("tm_gmtoff", rffi.LONG),
+            ("tm_zone", rffi.CCHARP)])
 elif _WIN:
     calling_conv = 'win'
     CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
@@ -202,35 +217,81 @@
          tzname = rffi.charp2str(tzname_ptr[0]), rffi.charp2str(tzname_ptr[1])
 
     if _POSIX:
-        YEAR = (365 * 24 + 6) * 3600
+        if _CYGWIN:
+            YEAR = (365 * 24 + 6) * 3600
 
-        t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR)
-        # we cannot have reference to stack variable, put it on the heap
-        t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
-        t_ref[0] = rffi.cast(rffi.TIME_T, t)
-        p = c_localtime(t_ref)
-        janzone = -p.c_tm_gmtoff
-        tm_zone = rffi.charp2str(p.c_tm_zone)
-        janname = ["   ", tm_zone][bool(tm_zone)]
-        tt = t + YEAR / 2
-        t_ref[0] = rffi.cast(rffi.TIME_T, tt)
-        p = c_localtime(t_ref)
-        lltype.free(t_ref, flavor='raw')
-        tm_zone = rffi.charp2str(p.c_tm_zone)
-        julyzone = -p.c_tm_gmtoff
-        julyname = ["   ", tm_zone][bool(tm_zone)]
+            # about January 11th
+            t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR + 10 * 24 * 3600)
+            # we cannot have reference to stack variable, put it on the heap
+            t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
+            t_ref[0] = rffi.cast(rffi.TIME_T, t)
+            p = c_localtime(t_ref)
+            q = c_gmtime(t_ref)
+            janzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
+            if janzone < -12:
+                janname = "   "
+            elif janzone > 14:
+                janname = "   "
+            else:
+                janname = _time_zones[janzone - 12]
+            janzone = janzone * 3600
+            # about July 11th
+            tt = t + YEAR / 2
+            t_ref[0] = rffi.cast(rffi.TIME_T, tt)
+            p = c_localtime(t_ref)
+            q = c_gmtime(t_ref)
+            julyzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
+            if julyzone < -12:
+                julyname = "   "
+            elif julyzone > 14:
+                julyname = "   "
+            else:
+                julyname = _time_zones[julyzone - 12]
+            julyzone = julyzone * 3600
+            lltype.free(t_ref, flavor='raw')
 
-        if janzone < julyzone:
-            # DST is reversed in the southern hemisphere
-            timezone = julyzone
-            altzone = janzone
-            daylight = int(janzone != julyzone)
-            tzname = [julyname, janname]
+            if janzone < julyzone:
+                # DST is reversed in the southern hemisphere
+                timezone = julyzone
+                altzone = janzone
+                daylight = int(janzone != julyzone)
+                tzname = [julyname, janname]
+            else:
+                timezone = janzone
+                altzone = julyzone
+                daylight = int(janzone != julyzone)
+                tzname = [janname, julyname]
+
         else:
-            timezone = janzone
-            altzone = julyzone
-            daylight = int(janzone != julyzone)
-            tzname = [janname, julyname]
+            YEAR = (365 * 24 + 6) * 3600
+
+            t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR)
+            # we cannot have reference to stack variable, put it on the heap
+            t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
+            t_ref[0] = rffi.cast(rffi.TIME_T, t)
+            p = c_localtime(t_ref)
+            janzone = -p.c_tm_gmtoff
+            tm_zone = rffi.charp2str(p.c_tm_zone)
+            janname = ["   ", tm_zone][bool(tm_zone)]
+            tt = t + YEAR / 2
+            t_ref[0] = rffi.cast(rffi.TIME_T, tt)
+            p = c_localtime(t_ref)
+            lltype.free(t_ref, flavor='raw')
+            tm_zone = rffi.charp2str(p.c_tm_zone)
+            julyzone = -p.c_tm_gmtoff
+            julyname = ["   ", tm_zone][bool(tm_zone)]
+
+            if janzone < julyzone:
+                # DST is reversed in the southern hemisphere
+                timezone = julyzone
+                altzone = janzone
+                daylight = int(janzone != julyzone)
+                tzname = [julyname, janname]
+            else:
+                timezone = janzone
+                altzone = julyzone
+                daylight = int(janzone != julyzone)
+                tzname = [janname, julyname]
 
     _set_module_object(space, "timezone", space.wrap(timezone))
     _set_module_object(space, 'daylight', space.wrap(daylight))
@@ -361,9 +422,12 @@
     rffi.setintfield(glob_buf, 'c_tm_yday', tm_yday)
     rffi.setintfield(glob_buf, 'c_tm_isdst', space.int_w(tup_w[8]))
     if _POSIX:
-        # actually never happens, but makes annotator happy
-        glob_buf.c_tm_zone = lltype.nullptr(rffi.CCHARP.TO)
-        rffi.setintfield(glob_buf, 'c_tm_gmtoff', 0)
+        if _CYGWIN:
+            pass
+        else:
+            # actually never happens, but makes annotator happy
+            glob_buf.c_tm_zone = lltype.nullptr(rffi.CCHARP.TO)
+            rffi.setintfield(glob_buf, 'c_tm_gmtoff', 0)
 
     w_accept2dyear = _get_module_object(space, "accept2dyear")
     accept2dyear = space.int_w(w_accept2dyear)
diff --git a/pypy/module/test_lib_pypy/ctypes_tests/test_functions.py b/pypy/module/test_lib_pypy/ctypes_tests/test_functions.py
--- a/pypy/module/test_lib_pypy/ctypes_tests/test_functions.py
+++ b/pypy/module/test_lib_pypy/ctypes_tests/test_functions.py
@@ -484,6 +484,20 @@
         assert tf_b(-126) == -42
         assert tf_b._ptr is ptr
 
+    def test_custom_from_param(self):
+        class A(c_byte):
+            @classmethod
+            def from_param(cls, obj):
+                seen.append(obj)
+                return -126
+        tf_b = dll.tf_b
+        tf_b.restype = c_byte
+        tf_b.argtypes = (c_byte,)
+        tf_b.argtypes = [A]
+        seen = []
+        assert tf_b("yadda") == -42
+        assert seen == ["yadda"]
+
     def test_warnings(self):
         import warnings
         warnings.simplefilter("always")
diff --git a/pypy/objspace/std/listobject.py b/pypy/objspace/std/listobject.py
--- a/pypy/objspace/std/listobject.py
+++ b/pypy/objspace/std/listobject.py
@@ -1221,41 +1221,29 @@
         i += 1
     return space.w_True
 
-def lessthan_unwrappeditems(space, w_list1, w_list2):
-    # needs to be safe against eq_w() mutating the w_lists behind our back
-    # Search for the first index where items are different
-    i = 0
-    # XXX in theory, this can be implemented more efficiently as well. let's
-    # not care for now
-    while i < w_list1.length() and i < w_list2.length():
-        w_item1 = w_list1.getitem(i)
-        w_item2 = w_list2.getitem(i)
-        if not space.eq_w(w_item1, w_item2):
-            return space.lt(w_item1, w_item2)
-        i += 1
-    # No more items to compare -- compare sizes
-    return space.newbool(w_list1.length() < w_list2.length())
+def _make_list_comparison(name):
+    import operator
+    op = getattr(operator, name)
+    def compare_unwrappeditems(space, w_list1, w_list2):
+        # needs to be safe against eq_w() mutating the w_lists behind our back
+        # Search for the first index where items are different
+        i = 0
+        # XXX in theory, this can be implemented more efficiently as well.
+        # let's not care for now
+        while i < w_list1.length() and i < w_list2.length():
+            w_item1 = w_list1.getitem(i)
+            w_item2 = w_list2.getitem(i)
+            if not space.eq_w(w_item1, w_item2):
+                return getattr(space, name)(w_item1, w_item2)
+            i += 1
+        # No more items to compare -- compare sizes
+        return space.newbool(op(w_list1.length(), w_list2.length()))
+    return func_with_new_name(compare_unwrappeditems, name + '__List_List')
 
-def greaterthan_unwrappeditems(space, w_list1, w_list2):
-    # needs to be safe against eq_w() mutating the w_lists behind our back
-    # Search for the first index where items are different
-    i = 0
-    # XXX in theory, this can be implemented more efficiently as well. let's
-    # not care for now
-    while i < w_list1.length() and i < w_list2.length():
-        w_item1 = w_list1.getitem(i)
-        w_item2 = w_list2.getitem(i)
-        if not space.eq_w(w_item1, w_item2):
-            return space.gt(w_item1, w_item2)
-        i += 1
-    # No more items to compare -- compare sizes
-    return space.newbool(w_list1.length() > w_list2.length())
-
-def lt__List_List(space, w_list1, w_list2):
-    return lessthan_unwrappeditems(space, w_list1, w_list2)
-
-def gt__List_List(space, w_list1, w_list2):
-    return greaterthan_unwrappeditems(space, w_list1, w_list2)
+lt__List_List = _make_list_comparison('lt')
+le__List_List = _make_list_comparison('le')
+gt__List_List = _make_list_comparison('gt')
+ge__List_List = _make_list_comparison('ge')
 
 def delitem__List_ANY(space, w_list, w_idx):
     idx = get_list_index(space, w_idx)
diff --git a/pypy/objspace/std/test/test_listobject.py b/pypy/objspace/std/test/test_listobject.py
--- a/pypy/objspace/std/test/test_listobject.py
+++ b/pypy/objspace/std/test/test_listobject.py
@@ -1204,6 +1204,57 @@
             s.update(Sub2(arg))
             assert s == set(base(arg))
 
+    def test_comparison(self):
+        assert ([] <  []) is False
+        assert ([] <= []) is True
+        assert ([] == []) is True
+        assert ([] != []) is False
+        assert ([] >  []) is False
+        assert ([] >= []) is True
+        assert ([5] <  []) is False
+        assert ([5] <= []) is False
+        assert ([5] == []) is False
+        assert ([5] != []) is True
+        assert ([5] >  []) is True
+        assert ([5] >= []) is True
+        assert ([] <  [5]) is True
+        assert ([] <= [5]) is True
+        assert ([] == [5]) is False
+        assert ([] != [5]) is True
+        assert ([] >  [5]) is False
+        assert ([] >= [5]) is False
+        assert ([4] <  [5]) is True
+        assert ([4] <= [5]) is True
+        assert ([4] == [5]) is False
+        assert ([4] != [5]) is True
+        assert ([4] >  [5]) is False
+        assert ([4] >= [5]) is False
+        assert ([5] <  [5]) is False
+        assert ([5] <= [5]) is True
+        assert ([5] == [5]) is True
+        assert ([5] != [5]) is False
+        assert ([5] >  [5]) is False
+        assert ([5] >= [5]) is True
+        assert ([6] <  [5]) is False
+        assert ([6] <= [5]) is False
+        assert ([6] == [5]) is False
+        assert ([6] != [5]) is True
+        assert ([6] >  [5]) is True
+        assert ([6] >= [5]) is True
+        N = float('nan')
+        assert ([N] <  [5]) is False
+        assert ([N] <= [5]) is False
+        assert ([N] == [5]) is False
+        assert ([N] != [5]) is True
+        assert ([N] >  [5]) is False
+        assert ([N] >= [5]) is False
+        assert ([5] <  [N]) is False
+        assert ([5] <= [N]) is False
+        assert ([5] == [N]) is False
+        assert ([5] != [N]) is True
+        assert ([5] >  [N]) is False
+        assert ([5] >= [N]) is False
+
 class AppTestForRangeLists(AppTestW_ListObject):
 
     def setup_class(cls):
diff --git a/pypy/objspace/std/test/test_stringobject.py b/pypy/objspace/std/test/test_stringobject.py
--- a/pypy/objspace/std/test/test_stringobject.py
+++ b/pypy/objspace/std/test/test_stringobject.py
@@ -413,6 +413,9 @@
         assert 'abcdefghiabc'.find('def', 4) == -1
         assert 'abcdef'.find('', 13) == -1
         assert 'abcdefg'.find('def', 5, None) == -1
+        assert 'abcdef'.find('d', 6, 0) == -1
+        assert 'abcdef'.find('d', 3, 3) == -1
+        raises(TypeError, 'abcdef'.find, 'd', 1.0)
 
     def test_index(self):
         from sys import maxint
diff --git a/pypy/objspace/std/test/test_tupleobject.py b/pypy/objspace/std/test/test_tupleobject.py
--- a/pypy/objspace/std/test/test_tupleobject.py
+++ b/pypy/objspace/std/test/test_tupleobject.py
@@ -348,3 +348,54 @@
         assert (4, 2, 3, 4).index(4, 1) == 3
         assert (4, 4, 4).index(4, 1, 2) == 1
         raises(ValueError, (1, 2, 3, 4).index, 4, 0, 2)
+
+    def test_comparison(self):
+        assert (() <  ()) is False
+        assert (() <= ()) is True
+        assert (() == ()) is True
+        assert (() != ()) is False
+        assert (() >  ()) is False
+        assert (() >= ()) is True
+        assert ((5,) <  ()) is False
+        assert ((5,) <= ()) is False
+        assert ((5,) == ()) is False
+        assert ((5,) != ()) is True
+        assert ((5,) >  ()) is True
+        assert ((5,) >= ()) is True
+        assert (() <  (5,)) is True
+        assert (() <= (5,)) is True
+        assert (() == (5,)) is False
+        assert (() != (5,)) is True
+        assert (() >  (5,)) is False
+        assert (() >= (5,)) is False
+        assert ((4,) <  (5,)) is True
+        assert ((4,) <= (5,)) is True
+        assert ((4,) == (5,)) is False
+        assert ((4,) != (5,)) is True
+        assert ((4,) >  (5,)) is False
+        assert ((4,) >= (5,)) is False
+        assert ((5,) <  (5,)) is False
+        assert ((5,) <= (5,)) is True
+        assert ((5,) == (5,)) is True
+        assert ((5,) != (5,)) is False
+        assert ((5,) >  (5,)) is False
+        assert ((5,) >= (5,)) is True
+        assert ((6,) <  (5,)) is False
+        assert ((6,) <= (5,)) is False
+        assert ((6,) == (5,)) is False
+        assert ((6,) != (5,)) is True
+        assert ((6,) >  (5,)) is True
+        assert ((6,) >= (5,)) is True
+        N = float('nan')
+        assert ((N,) <  (5,)) is False
+        assert ((N,) <= (5,)) is False
+        assert ((N,) == (5,)) is False
+        assert ((N,) != (5,)) is True
+        assert ((N,) >  (5,)) is False
+        assert ((N,) >= (5,)) is False
+        assert ((5,) <  (N,)) is False
+        assert ((5,) <= (N,)) is False
+        assert ((5,) == (N,)) is False
+        assert ((5,) != (N,)) is True
+        assert ((5,) >  (N,)) is False
+        assert ((5,) >= (N,)) is False
diff --git a/pypy/objspace/std/tupleobject.py b/pypy/objspace/std/tupleobject.py
--- a/pypy/objspace/std/tupleobject.py
+++ b/pypy/objspace/std/tupleobject.py
@@ -8,6 +8,7 @@
 from pypy.objspace.std import slicetype
 from pypy.rlib.debug import make_sure_not_resized
 from pypy.rlib import jit
+from pypy.tool.sourcetools import func_with_new_name
 
 # Tuples of known length up to UNROLL_TUPLE_LIMIT have unrolled certain methods
 UNROLL_TUPLE_LIMIT = 10
@@ -138,29 +139,27 @@
             return space.w_False
     return space.w_True
 
- at jit.look_inside_iff(tuple_unroll_condition)
-def lt__Tuple_Tuple(space, w_tuple1, w_tuple2):
-    items1 = w_tuple1.wrappeditems
-    items2 = w_tuple2.wrappeditems
-    ncmp = min(len(items1), len(items2))
-    # Search for the first index where items are different
-    for p in range(ncmp):
-        if not space.eq_w(items1[p], items2[p]):
-            return space.lt(items1[p], items2[p])
-    # No more items to compare -- compare sizes
-    return space.newbool(len(items1) < len(items2))
+def _make_tuple_comparison(name):
+    import operator
+    op = getattr(operator, name)
+    #
+    @jit.look_inside_iff(tuple_unroll_condition)
+    def compare_tuples(space, w_tuple1, w_tuple2):
+        items1 = w_tuple1.wrappeditems
+        items2 = w_tuple2.wrappeditems
+        ncmp = min(len(items1), len(items2))
+        # Search for the first index where items are different
+        for p in range(ncmp):
+            if not space.eq_w(items1[p], items2[p]):
+                return getattr(space, name)(items1[p], items2[p])
+        # No more items to compare -- compare sizes
+        return space.newbool(op(len(items1), len(items2)))
+    return func_with_new_name(compare_tuples, name + '__Tuple_Tuple')
 
- at jit.look_inside_iff(tuple_unroll_condition)
-def gt__Tuple_Tuple(space, w_tuple1, w_tuple2):
-    items1 = w_tuple1.wrappeditems
-    items2 = w_tuple2.wrappeditems
-    ncmp = min(len(items1), len(items2))
-    # Search for the first index where items are different
-    for p in range(ncmp):
-        if not space.eq_w(items1[p], items2[p]):
-            return space.gt(items1[p], items2[p])
-    # No more items to compare -- compare sizes
-    return space.newbool(len(items1) > len(items2))
+lt__Tuple_Tuple = _make_tuple_comparison('lt')
+le__Tuple_Tuple = _make_tuple_comparison('le')
+gt__Tuple_Tuple = _make_tuple_comparison('gt')
+ge__Tuple_Tuple = _make_tuple_comparison('ge')
 
 def repr__Tuple(space, w_tuple):
     items = w_tuple.wrappeditems
diff --git a/pypy/rlib/libffi.py b/pypy/rlib/libffi.py
--- a/pypy/rlib/libffi.py
+++ b/pypy/rlib/libffi.py
@@ -1,15 +1,17 @@
 from __future__ import with_statement
 
 from pypy.rpython.lltypesystem import rffi, lltype
-from pypy.rlib.objectmodel import specialize, enforceargs, we_are_translated
+from pypy.rlib.objectmodel import specialize, enforceargs
 from pypy.rlib.rarithmetic import intmask, r_uint, r_singlefloat, r_longlong
 from pypy.rlib import jit
 from pypy.rlib import clibffi
-from pypy.rlib.clibffi import get_libc_name, FUNCFLAG_CDECL, AbstractFuncPtr, \
-    push_arg_as_ffiptr, c_ffi_call, FFI_TYPE_STRUCT
+from pypy.rlib.clibffi import FUNCFLAG_CDECL, FUNCFLAG_STDCALL, \
+        AbstractFuncPtr, push_arg_as_ffiptr, c_ffi_call, FFI_TYPE_STRUCT
 from pypy.rlib.rdynload import dlopen, dlclose, dlsym, dlsym_byordinal
 from pypy.rlib.rdynload import DLLHANDLE
 
+import os
+
 class types(object):
     """
     This namespace contains the primitive types you can use to declare the
@@ -374,7 +376,7 @@
         else:
             res = None
         self._free_buffers(ll_result, ll_args)
-        #check_fficall_result(ffires, self.flags)
+        clibffi.check_fficall_result(ffires, self.flags)
         return res
 
     def _free_buffers(self, ll_result, ll_args):
@@ -416,6 +418,11 @@
     def getaddressindll(self, name):
         return dlsym(self.lib, name)
 
+if os.name == 'nt':
+    class WinDLL(CDLL):
+        def getpointer(self, name, argtypes, restype, flags=FUNCFLAG_STDCALL):
+            return Func(name, argtypes, restype, dlsym(self.lib, name),
+                        flags=flags, keepalive=self)
 # ======================================================================
 
 @jit.oopspec('libffi_struct_getfield(ffitype, addr, offset)')
diff --git a/pypy/rlib/rope.py b/pypy/rlib/rope.py
--- a/pypy/rlib/rope.py
+++ b/pypy/rlib/rope.py
@@ -769,11 +769,11 @@
     len2 = subnode.length()
     if stop > len1 or stop == -1:
         stop = len1
+    if stop - start < 0:
+        return -1
     if len2 == 1:
         return find_int(node, subnode.getint(0), start, stop)
     if len2 == 0:
-        if (stop - start) < 0:
-            return -1
         return start
     if len2 > stop - start:
         return -1
diff --git a/pypy/rlib/rsdl/RIMG.py b/pypy/rlib/rsdl/RIMG.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/RIMG.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import sys
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rpython.tool import rffi_platform as platform
-from pypy.translator.tool.cbuild import ExternalCompilationInfo
-from pypy.rlib.rsdl import RSDL
-
-
-if sys.platform == 'darwin':
-    eci = ExternalCompilationInfo(
-        includes = ['SDL_image.h'],
-        frameworks = ['SDL_image'],
-        include_dirs = ['/Library/Frameworks/SDL_image.framework/Headers']
-    )
-else:
-    eci = ExternalCompilationInfo(
-        includes=['SDL_image.h'],
-        libraries=['SDL_image'],
-    )
-
-eci = eci.merge(RSDL.eci)
-
-def external(name, args, result):
-    return rffi.llexternal(name, args, result, compilation_info=eci)
-
-Load = external('IMG_Load', [rffi.CCHARP], RSDL.SurfacePtr)
diff --git a/pypy/rlib/rsdl/RMix.py b/pypy/rlib/rsdl/RMix.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/RMix.py
+++ /dev/null
@@ -1,68 +0,0 @@
-import sys
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rpython.tool import rffi_platform as platform
-from pypy.translator.tool.cbuild import ExternalCompilationInfo
-from pypy.rlib.rsdl import RSDL
-
-
-if sys.platform == 'darwin':
-    eci = ExternalCompilationInfo(
-        includes = ['SDL_mixer.h'],
-        frameworks = ['SDL_mixer'],
-        include_dirs = ['/Library/Frameworks/SDL_Mixer.framework/Headers']
-    )
-else:
-    eci = ExternalCompilationInfo(
-        includes=['SDL_mixer.h'],
-        libraries=['SDL_mixer'],
-    )
-
-eci = eci.merge(RSDL.eci)
-eci = eci.merge(eci)
-eci = eci.merge(eci)
-
-ChunkPtr             = lltype.Ptr(lltype.ForwardReference())
-
-class CConfig:
-    _compilation_info_ = eci
-
-    Chunk              = platform.Struct('Mix_Chunk', [('allocated', rffi.INT),
-                                                       ('abuf', RSDL.Uint8P),
-                                                       ('alen', RSDL.Uint32),
-                                                       ('volume', RSDL.Uint8)])
-
-globals().update(platform.configure(CConfig))
-
-ChunkPtr.TO.become(Chunk)
-
-
-Buffer = rffi.CArray(RSDL.Uint8)
-
-def external(name, args, result):
-    return rffi.llexternal(name, args, result, compilation_info=eci)
-
-OpenAudio           = external('Mix_OpenAudio',
-                               [rffi.INT, RSDL.Uint16, rffi.INT, rffi.INT],
-                               rffi.INT)
-
-CloseAudio          = external('Mix_CloseAudio', [], lltype.Void)
-
-LoadWAV_RW          = external('Mix_LoadWAV_RW',
-                               [RSDL.RWopsPtr, rffi.INT],
-                               ChunkPtr)
-
-def LoadWAV(filename_ccharp):
-    with rffi.scoped_str2charp('rb') as mode:
-        return LoadWAV_RW(RSDL.RWFromFile(filename_ccharp, mode), 1)
-
-
-PlayChannelTimed    = external('Mix_PlayChannelTimed',
-                               [rffi.INT, ChunkPtr, rffi.INT, rffi.INT],
-                               rffi.INT)
-
-def PlayChannel(channel,chunk,loops):
-    return PlayChannelTimed(channel, chunk, loops, -1)
-
-"""Returns zero if the channel is not playing. 
-Otherwise if you passed in -1, the number of channels playing is returned"""
-ChannelPlaying  = external('Mix_Playing', [rffi.INT], rffi.INT)
diff --git a/pypy/rlib/rsdl/RMix_helper.py b/pypy/rlib/rsdl/RMix_helper.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/RMix_helper.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rlib.rsdl import RMix, RSDL
-from pypy.rpython.tool import rffi_platform as platform
-
-
-def malloc_buffer_chunk(has_own_allocated_buffer, length_bytes, volume):
-    buffer_pointer = lltype.malloc(RMix.Buffer, length_bytes, flavor='raw')
-    return malloc_chunk(has_own_allocated_buffer, length_bytes, volume)
-
-def malloc_chunk(has_own_allocated_buffer, buffer_pointer, length_bytes, volume):
-    """
-    Creates a new Mix_Chunk.
-    has_own_allocated_buffer:  if 1 struct has its own allocated buffer, 
-                                if 0 abuf should not be freed
-    buffer_pointer:             pointer to audio data
-    length_bytes:               length of audio data in bytes
-    volume:                     Per-sample volume, 0-128 (normally 
-                                MIX_MAX_VOLUME after loading)"""
-    p = lltype.malloc(RMix.Chunk, flavor='raw')
-    rffi.setintfield(p, 'c_allocated', has_own_allocated_buffer)
-    rffi.setintfield(p, 'c_abuf', buffer_pointer)
-    rffi.setintfield(p, 'c_alen', length_bytes)
-    rffi.setintfield(p, 'c_volume', volume)
-    return p
\ No newline at end of file
diff --git a/pypy/rlib/rsdl/RSDL.py b/pypy/rlib/rsdl/RSDL.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/RSDL.py
+++ /dev/null
@@ -1,249 +0,0 @@
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rpython.tool import rffi_platform as platform
-from pypy.rlib.rsdl.constants import _constants
-from pypy.rlib.rsdl.eci import get_rsdl_compilation_info
-from pypy.rlib.objectmodel import we_are_translated
-import py
-import sys
-
-# ------------------------------------------------------------------------------
-
-eci = get_rsdl_compilation_info()
-
-def external(name, args, result):
-    return rffi.llexternal(name, args, result, compilation_info=eci)
-
-# ------------------------------------------------------------------------------
-
-RectPtr             = lltype.Ptr(lltype.ForwardReference())
-SurfacePtr          = lltype.Ptr(lltype.ForwardReference())
-PixelFormatPtr      = lltype.Ptr(lltype.ForwardReference())
-EventPtr            = lltype.Ptr(lltype.ForwardReference())
-KeyboardEventPtr    = lltype.Ptr(lltype.ForwardReference())
-MouseButtonEventPtr = lltype.Ptr(lltype.ForwardReference())
-MouseMotionEventPtr = lltype.Ptr(lltype.ForwardReference())
-KeyPtr              = lltype.Ptr(lltype.ForwardReference())
-RWopsPtr            = lltype.Ptr(lltype.ForwardReference())
-
-# ------------------------------------------------------------------------------
-
-class CConfig:
-    _compilation_info_ = eci
-
-    Uint8  = platform.SimpleType('Uint8',  rffi.INT)
-    Uint16 = platform.SimpleType('Uint16', rffi.INT)
-    Sint16 = platform.SimpleType('Sint16', rffi.INT)
-    Uint32 = platform.SimpleType('Uint32', rffi.INT)
-
-    Rect             = platform.Struct('SDL_Rect', 
-                                    [('x', rffi.INT),
-                                     ('y', rffi.INT),
-                                     ('w', rffi.INT),
-                                     ('h', rffi.INT)])
-    
-    Surface          = platform.Struct('SDL_Surface', 
-                                    [('w', rffi.INT),
-                                     ('h', rffi.INT),
-                                     ('format', PixelFormatPtr),
-                                     ('pitch', rffi.INT),
-                                     ('pixels', rffi.UCHARP)])
-    
-    PixelFormat      = platform.Struct('SDL_PixelFormat',
-                                    [('BitsPerPixel', rffi.INT),
-                                     ('BytesPerPixel', rffi.INT),
-                                     ('Rmask', rffi.INT),
-                                     ('Gmask', rffi.INT),
-                                     ('Bmask', rffi.INT),
-                                     ('Amask', rffi.INT)])
-
-    Event            = platform.Struct('SDL_Event',
-                                    [('type', rffi.INT)])
-    
-    keysym           = platform.Struct('SDL_keysym', 
-                                    [('scancode', rffi.INT),
-                                     ('sym', rffi.INT),
-                                     ('mod', rffi.INT),
-                                     ('unicode', rffi.INT)])
-    
-    KeyboardEvent    = platform.Struct('SDL_KeyboardEvent',
-                                    [('type', rffi.INT),
-                                     ('state', rffi.INT),
-                                     ('keysym', keysym)])
-    
-    MouseButtonEvent = platform.Struct('SDL_MouseButtonEvent',
-                                    [('type', rffi.INT),
-                                     ('button', rffi.INT),
-                                     ('state', rffi.INT),
-                                     ('x', rffi.INT),
-                                     ('y', rffi.INT)])
-    
-    MouseMotionEvent = platform.Struct('SDL_MouseMotionEvent',
-                                    [('type', rffi.INT),
-                                     ('state', rffi.INT),
-                                     ('x', rffi.INT),
-                                     ('y', rffi.INT),
-                                     ('xrel', rffi.INT),
-                                     ('yrel', rffi.INT)])
-    
-    QuitEvent        = platform.Struct('SDL_QuitEvent',
-                                    [('type', rffi.INT)])
-    
-    RWops = platform.Struct('SDL_RWops', [])
-
-# ------------------------------------------------------------------------------
-
-for _prefix, _list in _constants.items():
-    for _name in _list:
-        setattr(CConfig, _name, platform.ConstantInteger(_prefix+_name))
-
-# ------------------------------------------------------------------------------
-
-globals().update(platform.configure(CConfig))
-
-# ------------------------------------------------------------------------------
-
-RectPtr.TO.become(Rect)
-SurfacePtr.TO.become(Surface)
-PixelFormatPtr.TO.become(PixelFormat)
-EventPtr.TO.become(Event)
-KeyboardEventPtr.TO.become(KeyboardEvent)
-MouseButtonEventPtr.TO.become(MouseButtonEvent)
-MouseMotionEventPtr.TO.become(MouseMotionEvent)
-RWopsPtr.TO.become(RWops)
-
-# ------------------------------------------------------------------------------
-
-Uint8P  = lltype.Ptr(lltype.Array(Uint8, hints={'nolength': True}))
-Uint16P = lltype.Ptr(lltype.Array(Uint16, hints={'nolength': True}))
-# need to add signed hint here
-Sint16P = lltype.Ptr(lltype.Array(Sint16, hints={'nolength': True}))
-Uint32P = lltype.Ptr(lltype.Array(Uint32, hints={'nolength': True}))
-
-
-# ------------------------------------------------------------------------------
-
-_Init            = external('SDL_Init', 
-                             [Uint32], 
-                             rffi.INT)
-                                  
-Mac_Init        = external('SDL_Init', 
-                             [Uint32], 
-                             rffi.INT)
-
-Quit             = external('SDL_Quit', [], 
-                            lltype.Void)
-
-SetVideoMode     = external('SDL_SetVideoMode', 
-                             [rffi.INT, rffi.INT, rffi.INT, Uint32],
-                             SurfacePtr)
-
-WM_SetCaption    = external('SDL_WM_SetCaption', 
-                             [rffi.CCHARP, rffi.CCHARP],
-                             lltype.Void)
-
-EnableUNICODE    = external('SDL_EnableUNICODE', 
-                             [rffi.INT], 
-                             rffi.INT)
-
-WaitEvent        = external('SDL_WaitEvent', 
-                             [EventPtr], 
-                             rffi.INT)
-
-PollEvent        = external('SDL_PollEvent',
-                             [EventPtr], 
-                             rffi.INT)
-
-Flip             = external('SDL_Flip', 
-                             [SurfacePtr], 
-                             rffi.INT)
-
-CreateRGBSurface = external('SDL_CreateRGBSurface', 
-                             [Uint32, rffi.INT, rffi.INT, rffi.INT,
-                              Uint32, Uint32, Uint32, Uint32],
-                             SurfacePtr)
-
-LockSurface      = external('SDL_LockSurface', 
-                             [SurfacePtr], 
-                             rffi.INT)
-
-UnlockSurface    = external('SDL_UnlockSurface', 
-                             [SurfacePtr],
-                             lltype.Void)
-
-FreeSurface      = external('SDL_FreeSurface', 
-                             [SurfacePtr],
-                             lltype.Void)
-
-MapRGB           = external('SDL_MapRGB', 
-                             [PixelFormatPtr, Uint8, Uint8,  Uint8], 
-                             Uint32)
-
-GetRGB           = external('SDL_GetRGB',
-                             [Uint32, PixelFormatPtr, Uint8P, Uint8P, Uint8P], 
-                             lltype.Void)
-
-GetRGBA          = external('SDL_GetRGBA', 
-                             [Uint32, PixelFormatPtr, Uint8P, Uint8P, 
-                             Uint8P, Uint8P], 
-                             lltype.Void)
-
-FillRect         = external('SDL_FillRect', 
-                             [SurfacePtr, RectPtr, Uint32], 
-                             rffi.INT)
-
-BlitSurface      = external('SDL_UpperBlit', 
-                             [SurfacePtr, RectPtr, SurfacePtr,  RectPtr], 
-                             rffi.INT)
-
-SetAlpha         = external('SDL_SetAlpha', 
-                             [SurfacePtr, Uint32, Uint8], 
-                             rffi.INT)
-
-SetColorKey      = external('SDL_SetColorKey',
-                            [SurfacePtr, Uint32, Uint32],
-                            rffi.INT)
-
-ShowCursor       = external('SDL_ShowCursor',
-                            [rffi.INT],
-                            rffi.INT)
-
-GetTicks         = external('SDL_GetTicks',
-                            [],
-                            Uint32)
-
-Delay            = external('SDL_Delay',
-                            [Uint32],
-                            lltype.Void)
-
-UpdateRect       = external('SDL_UpdateRect',
-                            [SurfacePtr, rffi.INT, rffi.INT, rffi.INT],
-                            lltype.Void)
-
-GetKeyName       = external('SDL_GetKeyName',
-                            [rffi.INT], 
-                            rffi.CCHARP)
-
-GetError         = external('SDL_GetError',
-                            [],
-                            rffi.CCHARP)
-
-RWFromFile       = external('SDL_RWFromFile',
-                            [rffi.CCHARP, rffi.CCHARP],
-                            RWopsPtr)
-
-# ------------------------------------------------------------------------------
-
-
-if sys.platform == 'darwin':
-    def Init(flags):
-        if not we_are_translated():
-            from AppKit import NSApplication
-            NSApplication.sharedApplication()
-        #CustomApplicationMain(0, " ")
-        return _Init(flags)
-        #Mac_Init()
-else:
-    Init = _Init
-    
-    
-    
diff --git a/pypy/rlib/rsdl/RSDL_helper.py b/pypy/rlib/rsdl/RSDL_helper.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/RSDL_helper.py
+++ /dev/null
@@ -1,108 +0,0 @@
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy.rlib.rsdl import RSDL
-
-def get_rgb(color, format):
-    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
-    try:
-        RSDL.GetRGB(color,
-                    format,
-                    rffi.ptradd(rgb, 0),
-                    rffi.ptradd(rgb, 1),
-                    rffi.ptradd(rgb, 2))
-        r = rffi.cast(lltype.Signed, rgb[0])
-        g = rffi.cast(lltype.Signed, rgb[1])
-        b = rffi.cast(lltype.Signed, rgb[2])
-        result = r, g, b
-    finally:
-        lltype.free(rgb, flavor='raw')
-
-    return result
-
-def get_rgba(color, format):
-    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 4, flavor='raw')
-    try:
-        RSDL.GetRGBA(color,
-                    format,
-                    rffi.ptradd(rgb, 0),
-                    rffi.ptradd(rgb, 1),
-                    rffi.ptradd(rgb, 2),
-                    rffi.ptradd(rgb, 3))
-        r = rffi.cast(lltype.Signed, rgb[0])
-        g = rffi.cast(lltype.Signed, rgb[1])
-        b = rffi.cast(lltype.Signed, rgb[2])
-        a = rffi.cast(lltype.Signed, rgb[3])
-        result = r, g, b, a
-    finally:
-        lltype.free(rgb, flavor='raw')
-
-    return result
-
-def get_pixel(image, x, y):
-    """Return the pixel value at (x, y)
-    NOTE: The surface must be locked before calling this!
-    """
-    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
-    pitch = rffi.getintfield(image, 'c_pitch')
-    # Here p is the address to the pixel we want to retrieve
-    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
-    if bpp == 1:
-        return rffi.cast(RSDL.Uint32, p[0])
-    elif bpp == 2:
-        p = rffi.cast(RSDL.Uint16P, p)
-        return rffi.cast(RSDL.Uint32, p[0])
-    elif bpp == 3:
-        p0 = rffi.cast(lltype.Signed, p[0])
-        p1 = rffi.cast(lltype.Signed, p[1])
-        p2 = rffi.cast(lltype.Signed, p[2])
-        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
-            result = p0 << 16 | p1 << 8 | p2
-        else:
-            result = p0 | p1 << 8 | p2 << 16
-        return rffi.cast(RSDL.Uint32, result)
-    elif bpp == 4:
-        p = rffi.cast(RSDL.Uint32P, p)
-        return p[0]
-    else:
-        raise ValueError("bad BytesPerPixel")
-
-def set_pixel(image, x, y, pixel):
-    """Return the pixel value at (x, y)
-    NOTE: The surface must be locked before calling this!
-    """
-    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
-    pitch = rffi.getintfield(image, 'c_pitch')
-    # Here p is the address to the pixel we want to retrieve
-    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
-    if bpp == 1:
-        p[0] = rffi.cast(rffi.UCHAR,pixel)
-    elif bpp == 2:
-        p = rffi.cast(RSDL.Uint16P, p)
-        p[0] = rffi.cast(RSDL.Uint16,pixel) 
-    elif bpp == 3:
-        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
-            p[0] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
-            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
-            p[2] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
-        else:
-            p[0] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
-            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
-            p[2] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
-    elif bpp == 4:
-        p = rffi.cast(RSDL.Uint32P, p)
-        p[0] = rffi.cast(RSDL.Uint32, pixel)
-    else:
-        raise ValueError("bad BytesPerPixel")
-
-def mallocrect(x, y, w, h):
-    p = lltype.malloc(RSDL.Rect, flavor='raw')
-    rffi.setintfield(p, 'c_x', x)
-    rffi.setintfield(p, 'c_y', y)
-    rffi.setintfield(p, 'c_w', w)
-    rffi.setintfield(p, 'c_h', h)
-    return p
-
-def blit_complete_surface(src, dst, x, y):
-    dstrect = mallocrect(x, y, rffi.getintfield(src, 'c_w'), rffi.getintfield(src, 'c_w'))
-    RSDL.BlitSurface(src, lltype.nullptr(RSDL.Rect), dst, dstrect)
-    lltype.free(dstrect, flavor='raw')
-
diff --git a/pypy/rlib/rsdl/__init__.py b/pypy/rlib/rsdl/__init__.py
deleted file mode 100644
diff --git a/pypy/rlib/rsdl/constants.py b/pypy/rlib/rsdl/constants.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/constants.py
+++ /dev/null
@@ -1,261 +0,0 @@
-
-_constants = {
-    'SDL_': [      # constants with the 'SDL_' prefix in C
-        "YV12_OVERLAY",
-        "IYUV_OVERLAY",
-        "YUY2_OVERLAY",
-        "UYVY_OVERLAY",
-        "YVYU_OVERLAY",
-
-        "SWSURFACE",
-        "HWSURFACE",
-        "RESIZABLE",
-        "ASYNCBLIT",
-        "OPENGL",
-        "OPENGLBLIT",
-        "ANYFORMAT",
-        "HWPALETTE",
-        "DOUBLEBUF",
-        "FULLSCREEN",
-        "HWACCEL",
-        "SRCCOLORKEY",
-        "RLEACCELOK",
-        "RLEACCEL",
-        "SRCALPHA",
-        "PREALLOC",
-        "NOFRAME",
-
-        "GL_RED_SIZE",
-        "GL_GREEN_SIZE",
-        "GL_BLUE_SIZE",
-        "GL_ALPHA_SIZE",
-        "GL_BUFFER_SIZE",
-        "GL_DOUBLEBUFFER",
-        "GL_DEPTH_SIZE",
-        "GL_STENCIL_SIZE",
-        "GL_ACCUM_RED_SIZE",
-        "GL_ACCUM_GREEN_SIZE",
-        "GL_ACCUM_BLUE_SIZE",
-        "GL_ACCUM_ALPHA_SIZE",
-        "GL_STEREO",              #if SDL_VERSION_ATLEAST(1, 2, 5)
-        "GL_MULTISAMPLEBUFFERS",  #if SDL_VERSION_ATLEAST(1, 2, 6)
-        "GL_MULTISAMPLESAMPLES",  #if SDL_VERSION_ATLEAST(1, 2, 6)
-
-        "NOEVENT",
-        "ACTIVEEVENT",
-        "KEYDOWN",
-        "KEYUP",
-        "MOUSEMOTION",
-        "MOUSEBUTTONDOWN",
-        "MOUSEBUTTONUP",
-        "BUTTON_LEFT",
-        "BUTTON_MIDDLE", 
-        "BUTTON_RIGHT",
-        "BUTTON_WHEELUP", 
-        "BUTTON_WHEELDOWN", 
-        "JOYAXISMOTION",
-        "JOYBALLMOTION",
-        "JOYHATMOTION",
-        "JOYBUTTONDOWN",
-        "JOYBUTTONUP",
-        "VIDEORESIZE",
-        "VIDEOEXPOSE",
-        "QUIT",
-        "SYSWMEVENT",
-        "USEREVENT",
-        "NUMEVENTS",
-
-        "HAT_CENTERED",
-        "HAT_UP",
-        "HAT_RIGHTUP",
-        "HAT_RIGHT",
-        "HAT_RIGHTDOWN",
-        "HAT_DOWN",
-        "HAT_LEFTDOWN",
-        "HAT_LEFT",
-        "HAT_LEFTUP",
-        
-        "DISABLE",
-        "ENABLE",
-
-        # the following ones are not exposed in Pygame
-        "INIT_VIDEO",
-        "BYTEORDER",
-        "BIG_ENDIAN",
-        "LIL_ENDIAN",
-        ],
-
-    '': [      # constants with no prefix in C
-        "TIMER_RESOLUTION",
-        "AUDIO_U8",
-        "AUDIO_S8",
-        "AUDIO_U16LSB",
-        "AUDIO_S16LSB",
-        "AUDIO_U16MSB",
-        "AUDIO_S16MSB",
-        "AUDIO_U16",
-        "AUDIO_S16",
-        "AUDIO_U16SYS",
-        "AUDIO_S16SYS",
-
-        "KMOD_NONE",
-        "KMOD_LSHIFT",
-        "KMOD_RSHIFT",
-        "KMOD_LCTRL",
-        "KMOD_RCTRL",
-        "KMOD_LALT",
-        "KMOD_RALT",
-        "KMOD_LMETA",
-        "KMOD_RMETA",
-        "KMOD_NUM",
-        "KMOD_CAPS",
-        "KMOD_MODE",
-
-        "KMOD_CTRL",
-        "KMOD_SHIFT",
-        "KMOD_ALT",
-        "KMOD_META",
-        ],
-
-    'SDL': [      # constants with the 'SDL' prefix in C
-        "K_UNKNOWN",
-        "K_FIRST",
-        "K_BACKSPACE",
-        "K_TAB",
-        "K_CLEAR",
-        "K_RETURN",
-        "K_PAUSE",
-        "K_ESCAPE",
-        "K_SPACE",
-        "K_EXCLAIM",
-        "K_QUOTEDBL",
-        "K_HASH",
-        "K_DOLLAR",
-        "K_AMPERSAND",
-        "K_QUOTE",
-        "K_LEFTPAREN",
-        "K_RIGHTPAREN",
-        "K_ASTERISK",
-        "K_PLUS",
-        "K_COMMA",
-        "K_MINUS",
-        "K_PERIOD",
-        "K_SLASH",
-        "K_0",
-        "K_1",
-        "K_2",
-        "K_3",
-        "K_4",
-        "K_5",
-        "K_6",
-        "K_7",
-        "K_8",
-        "K_9",
-        "K_COLON",
-        "K_SEMICOLON",
-        "K_LESS",
-        "K_EQUALS",
-        "K_GREATER",
-        "K_QUESTION",
-        "K_AT",
-        "K_LEFTBRACKET",
-        "K_BACKSLASH",
-        "K_RIGHTBRACKET",
-        "K_CARET",
-        "K_UNDERSCORE",
-        "K_BACKQUOTE",
-        "K_a",
-        "K_b",
-        "K_c",
-        "K_d",
-        "K_e",
-        "K_f",
-        "K_g",
-        "K_h",
-        "K_i",
-        "K_j",
-        "K_k",
-        "K_l",
-        "K_m",
-        "K_n",
-        "K_o",
-        "K_p",
-        "K_q",
-        "K_r",
-        "K_s",
-        "K_t",
-        "K_u",
-        "K_v",
-        "K_w",
-        "K_x",
-        "K_y",
-        "K_z",
-        "K_DELETE",
-
-        "K_KP0",
-        "K_KP1",
-        "K_KP2",
-        "K_KP3",
-        "K_KP4",
-        "K_KP5",
-        "K_KP6",
-        "K_KP7",
-        "K_KP8",
-        "K_KP9",
-        "K_KP_PERIOD",
-        "K_KP_DIVIDE",
-        "K_KP_MULTIPLY",
-        "K_KP_MINUS",
-        "K_KP_PLUS",
-        "K_KP_ENTER",
-        "K_KP_EQUALS",
-        "K_UP",
-        "K_DOWN",
-        "K_RIGHT",
-        "K_LEFT",
-        "K_INSERT",
-        "K_HOME",
-        "K_END",
-        "K_PAGEUP",
-        "K_PAGEDOWN",
-        "K_F1",
-        "K_F2",
-        "K_F3",
-        "K_F4",
-        "K_F5",
-        "K_F6",
-        "K_F7",
-        "K_F8",
-        "K_F9",
-        "K_F10",
-        "K_F11",
-        "K_F12",
-        "K_F13",
-        "K_F14",
-        "K_F15",
-
-        "K_NUMLOCK",
-        "K_CAPSLOCK",
-        "K_SCROLLOCK",
-        "K_RSHIFT",
-        "K_LSHIFT",
-        "K_RCTRL",
-        "K_LCTRL",
-        "K_RALT",
-        "K_LALT",
-        "K_RMETA",
-        "K_LMETA",
-        "K_LSUPER",
-        "K_RSUPER",
-        "K_MODE",
-
-        "K_HELP",
-        "K_PRINT",
-        "K_SYSREQ",
-        "K_BREAK",
-        "K_MENU",
-        "K_POWER",
-        "K_EURO",
-        "K_LAST",
-        ],
-    }
diff --git a/pypy/rlib/rsdl/eci.py b/pypy/rlib/rsdl/eci.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/eci.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from pypy.translator.tool.cbuild import ExternalCompilationInfo
-from pypy.translator.platform import CompilationError
-import py
-import sys
-
-def get_rsdl_compilation_info():
-    if sys.platform == 'darwin':
-        eci = ExternalCompilationInfo(
-            includes = ['SDL.h'],
-            include_dirs = ['/Library/Frameworks/SDL.framework/Headers'],
-            link_files = [
-                str(py.path.local(__file__).dirpath().join('macosx-sdl-main/SDLMain.m')),
-            ],
-            frameworks = ['SDL', 'Cocoa']
-        )
-    else:
-        eci = ExternalCompilationInfo(
-            includes=['SDL.h'],
-            )
-        eci = eci.merge(ExternalCompilationInfo.from_config_tool('sdl-config'))
-    return eci
-
-def check_sdl_installation():
-    from pypy.rpython.tool import rffi_platform as platform
-    platform.verify_eci(get_rsdl_compilation_info())
-
-SDLNotInstalled = (ImportError, CompilationError)
diff --git a/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.h b/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.h
deleted file mode 100644
--- a/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.h
+++ /dev/null
@@ -1,11 +0,0 @@
-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1 at purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max at quendi.de>
-
-    Feel free to customize this file to suit your needs
-*/
-
-#import <Cocoa/Cocoa.h>
-
- at interface SDLMain : NSObject
- at end
diff --git a/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.m b/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.m
deleted file mode 100644
--- a/pypy/rlib/rsdl/macosx-sdl-main/SDLMain.m
+++ /dev/null
@@ -1,384 +0,0 @@
-/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
-       Initial Version: Darrell Walisser <dwaliss1 at purdue.edu>
-       Non-NIB-Code & other changes: Max Horn <max at quendi.de>
-
-    Feel free to customize this file to suit your needs
-*/
-
-#import "SDL.h"
-#import "SDLMain.h"
-#import <sys/param.h> /* for MAXPATHLEN */
-#import <unistd.h>
-
-/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
- but the method still is there and works. To avoid warnings, we declare
- it ourselves here. */
- at interface NSApplication(SDL_Missing_Methods)
-- (void)setAppleMenu:(NSMenu *)menu;
- at end
-
-/* Use this flag to determine whether we use SDLMain.nib or not */
-#define		SDL_USE_NIB_FILE	0
-
-/* Use this flag to determine whether we use CPS (docking) or not */
-#define		SDL_USE_CPS		1
-#ifdef SDL_USE_CPS
-/* Portions of CPS.h */
-typedef struct CPSProcessSerNum
-{
-	UInt32		lo;
-	UInt32		hi;
-} CPSProcessSerNum;
-
-extern OSErr	CPSGetCurrentProcess( CPSProcessSerNum *psn);
-extern OSErr 	CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
-extern OSErr	CPSSetFrontProcess( CPSProcessSerNum *psn);
-
-#endif /* SDL_USE_CPS */
-
-static int    gArgc;
-static char  **gArgv;
-static BOOL   gFinderLaunch;
-static BOOL   gCalledAppMainline = FALSE;
-
-static NSString *getApplicationName(void)
-{
-    NSDictionary *dict;
-    NSString *appName = 0;
-
-    /* Determine the application name */
-    dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
-    if (dict)
-        appName = [dict objectForKey: @"CFBundleName"];
-    
-    if (![appName length])
-        appName = [[NSProcessInfo processInfo] processName];
-
-    return appName;
-}
-
-#if SDL_USE_NIB_FILE
-/* A helper category for NSString */
- at interface NSString (ReplaceSubString)
-- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
- at end
-#endif
-
- at interface SDLApplication : NSApplication
- at end
-
- at implementation SDLApplication
-/* Invoked from the Quit menu item */
-- (void)terminate:(id)sender
-{
-    /* Post a SDL_QUIT event */
-    SDL_Event event;
-    event.type = SDL_QUIT;
-    SDL_PushEvent(&event);
-}
- at end
-
-/* The main class of the application, the application's delegate */
- at implementation SDLMain
-
-/* Set the working directory to the .app's parent directory */
-- (void) setupWorkingDirectory:(BOOL)shouldChdir
-{
-    if (shouldChdir)
-    {
-        char parentdir[MAXPATHLEN];
-		CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
-		CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
-		if (CFURLGetFileSystemRepresentation(url2, true, (UInt8 *)parentdir, MAXPATHLEN)) {
-	        assert ( chdir (parentdir) == 0 );   /* chdir to the binary app's parent */
-		}
-		CFRelease(url);
-		CFRelease(url2);
-	}
-
-}
-
-#if SDL_USE_NIB_FILE
-
-/* Fix menu to contain the real app name instead of "SDL App" */
-- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
-{
-    NSRange aRange;
-    NSEnumerator *enumerator;
-    NSMenuItem *menuItem;
-
-    aRange = [[aMenu title] rangeOfString:@"SDL App"];
-    if (aRange.length != 0)
-        [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
-
-    enumerator = [[aMenu itemArray] objectEnumerator];
-    while ((menuItem = [enumerator nextObject]))
-    {
-        aRange = [[menuItem title] rangeOfString:@"SDL App"];
-        if (aRange.length != 0)
-            [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
-        if ([menuItem hasSubmenu])
-            [self fixMenu:[menuItem submenu] withAppName:appName];
-    }
-    [ aMenu sizeToFit ];
-}
-
-#else
-
-static void setApplicationMenu(void)
-{
-    /* warning: this code is very odd */
-    NSMenu *appleMenu;
-    NSMenuItem *menuItem;
-    NSString *title;
-    NSString *appName;
-    
-    appName = getApplicationName();
-    appleMenu = [[NSMenu alloc] initWithTitle:@""];
-    
-    /* Add menu items */
-    title = [@"About " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
-
-    [appleMenu addItem:[NSMenuItem separatorItem]];
-
-    title = [@"Hide " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
-
-    menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
-    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
-
-    [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
-
-    [appleMenu addItem:[NSMenuItem separatorItem]];
-
-    title = [@"Quit " stringByAppendingString:appName];
-    [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
-
-    
-    /* Put menu into the menubar */
-    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
-    [menuItem setSubmenu:appleMenu];
-    [[NSApp mainMenu] addItem:menuItem];
-
-    /* Tell the application object that this is now the application menu */
-    [NSApp setAppleMenu:appleMenu];
-
-    /* Finally give up our references to the objects */
-    [appleMenu release];
-    [menuItem release];
-}
-
-/* Create a window menu */
-static void setupWindowMenu(void)
-{
-    NSMenu      *windowMenu;
-    NSMenuItem  *windowMenuItem;
-    NSMenuItem  *menuItem;
-
-    windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
-    
-    /* "Minimize" item */
-    menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
-    [windowMenu addItem:menuItem];
-    [menuItem release];
-    
-    /* Put menu into the menubar */
-    windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
-    [windowMenuItem setSubmenu:windowMenu];
-    [[NSApp mainMenu] addItem:windowMenuItem];
-    
-    /* Tell the application object that this is now the window menu */
-    [NSApp setWindowsMenu:windowMenu];
-
-    /* Finally give up our references to the objects */
-    [windowMenu release];
-    [windowMenuItem release];
-}
-
-/* Replacement for NSApplicationMain */
-static void CustomApplicationMain (int argc, char **argv)
-{
-    NSAutoreleasePool	*pool = [[NSAutoreleasePool alloc] init];
-    SDLMain				*sdlMain;
-
-    /* Ensure the application object is initialised */
-    [SDLApplication sharedApplication];
-    
-#ifdef SDL_USE_CPS
-    {
-        CPSProcessSerNum PSN;
-        /* Tell the dock about us */
-        if (!CPSGetCurrentProcess(&PSN))
-            if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
-                if (!CPSSetFrontProcess(&PSN))
-                    [SDLApplication sharedApplication];
-    }
-#endif /* SDL_USE_CPS */
-
-    /* Set up the menubar */
-    [NSApp setMainMenu:[[NSMenu alloc] init]];
-    setApplicationMenu();
-    setupWindowMenu();
-
-    /* Create SDLMain and make it the app delegate */
-    sdlMain = [[SDLMain alloc] init];
-    [NSApp setDelegate:sdlMain];
-    
-    /* Start the main event loop */
-    [NSApp run];
-    
-    [sdlMain release];
-    [pool release];
-}
-
-#endif
-
-
-/*
- * Catch document open requests...this lets us notice files when the app
- *  was launched by double-clicking a document, or when a document was
- *  dragged/dropped on the app's icon. You need to have a
- *  CFBundleDocumentsType section in your Info.plist to get this message,
- *  apparently.
- *
- * Files are added to gArgv, so to the app, they'll look like command line
- *  arguments. Previously, apps launched from the finder had nothing but
- *  an argv[0].
- *
- * This message may be received multiple times to open several docs on launch.
- *
- * This message is ignored once the app's mainline has been called.
- */
-- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
-{
-    const char *temparg;
-    size_t arglen;
-    char *arg;
-    char **newargv;
-
-    if (!gFinderLaunch)  /* MacOS is passing command line args. */
-        return FALSE;
-
-    if (gCalledAppMainline)  /* app has started, ignore this document. */
-        return FALSE;
-
-    temparg = [filename UTF8String];
-    arglen = SDL_strlen(temparg) + 1;
-    arg = (char *) SDL_malloc(arglen);
-    if (arg == NULL)
-        return FALSE;
-
-    newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
-    if (newargv == NULL)
-    {
-        SDL_free(arg);
-        return FALSE;
-    }
-    gArgv = newargv;
-
-    SDL_strlcpy(arg, temparg, arglen);
-    gArgv[gArgc++] = arg;
-    gArgv[gArgc] = NULL;
-    return TRUE;
-}
-
-
-/* Called when the internal event loop has just started running */
-- (void) applicationDidFinishLaunching: (NSNotification *) note
-{
-    int status;
-
-    /* Set the working directory to the .app's parent directory */
-    [self setupWorkingDirectory:gFinderLaunch];
-
-#if SDL_USE_NIB_FILE
-    /* Set the main menu to contain the real app name instead of "SDL App" */
-    [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
-#endif
-
-    /* Hand off to main application code */
-    gCalledAppMainline = TRUE;
-    status = SDL_main (gArgc, gArgv);
-
-    /* We're done, thank you for playing */
-    exit(status);
-}
- at end
-
-
- at implementation NSString (ReplaceSubString)
-
-- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
-{
-    unsigned int bufferSize;
-    unsigned int selfLen = [self length];
-    unsigned int aStringLen = [aString length];
-    unichar *buffer;
-    NSRange localRange;
-    NSString *result;
-
-    bufferSize = selfLen + aStringLen - aRange.length;
-    buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar));
-    
-    /* Get first part into buffer */
-    localRange.location = 0;
-    localRange.length = aRange.location;
-    [self getCharacters:buffer range:localRange];
-    
-    /* Get middle part into buffer */
-    localRange.location = 0;
-    localRange.length = aStringLen;
-    [aString getCharacters:(buffer+aRange.location) range:localRange];
-     
-    /* Get last part into buffer */
-    localRange.location = aRange.location + aRange.length;
-    localRange.length = selfLen - localRange.location;
-    [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
-    
-    /* Build output string */
-    result = [NSString stringWithCharacters:buffer length:bufferSize];
-    
-    NSDeallocateMemoryPages(buffer, bufferSize);
-    
-    return result;
-}
-
- at end
-
-
-
-#ifdef main
-#  undef main
-#endif
-
-
-/* Main entry point to executable - should *not* be SDL_main! */
-int main (int argc, char **argv)
-{
-    /* Copy the arguments into a global variable */
-    /* This is passed if we are launched by double-clicking */
-    if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
-        gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
-        gArgv[0] = argv[0];
-        gArgv[1] = NULL;
-        gArgc = 1;
-        gFinderLaunch = YES;
-    } else {
-        int i;
-        gArgc = argc;
-        gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
-        for (i = 0; i <= argc; i++)
-            gArgv[i] = argv[i];
-        gFinderLaunch = NO;
-    }
-
-#if SDL_USE_NIB_FILE
-    [SDLApplication poseAsClass:[NSApplication class]];
-    NSApplicationMain (argc, argv);
-#else
-    CustomApplicationMain (argc, argv);
-#endif
-    return 0;
-}
-
diff --git a/pypy/rlib/rsdl/test/__init__.py b/pypy/rlib/rsdl/test/__init__.py
deleted file mode 100644
diff --git a/pypy/rlib/rsdl/test/applause.wav b/pypy/rlib/rsdl/test/applause.wav
deleted file mode 100644
Binary file pypy/rlib/rsdl/test/applause.wav has changed
diff --git a/pypy/rlib/rsdl/test/autopath.py b/pypy/rlib/rsdl/test/autopath.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/autopath.py
+++ /dev/null
@@ -1,131 +0,0 @@
-"""
-self cloning, automatic path configuration 
-
-copy this into any subdirectory of pypy from which scripts need 
-to be run, typically all of the test subdirs. 
-The idea is that any such script simply issues
-
-    import autopath
-
-and this will make sure that the parent directory containing "pypy"
-is in sys.path. 
-
-If you modify the master "autopath.py" version (in pypy/tool/autopath.py) 
-you can directly run it which will copy itself on all autopath.py files
-it finds under the pypy root directory. 
-
-This module always provides these attributes:
-
-    pypydir    pypy root directory path 
-    this_dir   directory where this autopath.py resides 
-
-"""
-
-def __dirinfo(part):
-    """ return (partdir, this_dir) and insert parent of partdir
-    into sys.path.  If the parent directories don't have the part
-    an EnvironmentError is raised."""
-
-    import sys, os
-    try:
-        head = this_dir = os.path.realpath(os.path.dirname(__file__))
-    except NameError:
-        head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
-
-    error = None
-    while head:
-        partdir = head
-        head, tail = os.path.split(head)
-        if tail == part:
-            checkfile = os.path.join(partdir, os.pardir, 'pypy', '__init__.py')
-            if not os.path.exists(checkfile):
-                error = "Cannot find %r" % (os.path.normpath(checkfile),)
-            break
-    else:
-        error = "Cannot find the parent directory %r of the path %r" % (
-            partdir, this_dir)
-    if not error:
-        # check for bogus end-of-line style (e.g. files checked out on
-        # Windows and moved to Unix)
-        f = open(__file__.replace('.pyc', '.py'), 'r')
-        data = f.read()
-        f.close()
-        if data.endswith('\r\n') or data.endswith('\r'):
-            error = ("Bad end-of-line style in the .py files. Typically "
-                     "caused by a zip file or a checkout done on Windows and "
-                     "moved to Unix or vice-versa.")
-    if error:
-        raise EnvironmentError("Invalid source tree - bogus checkout! " +
-                               error)
-    
-    pypy_root = os.path.join(head, '')
-    try:
-        sys.path.remove(head)
-    except ValueError:
-        pass
-    sys.path.insert(0, head)
-
-    munged = {}
-    for name, mod in sys.modules.items():
-        if '.' in name:
-            continue
-        fn = getattr(mod, '__file__', None)
-        if not isinstance(fn, str):
-            continue
-        newname = os.path.splitext(os.path.basename(fn))[0]
-        if not newname.startswith(part + '.'):
-            continue
-        path = os.path.join(os.path.dirname(os.path.realpath(fn)), '')
-        if path.startswith(pypy_root) and newname != part:
-            modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep)
-            if newname != '__init__':
-                modpaths.append(newname)
-            modpath = '.'.join(modpaths)
-            if modpath not in sys.modules:
-                munged[modpath] = mod
-
-    for name, mod in munged.iteritems():
-        if name not in sys.modules:
-            sys.modules[name] = mod
-        if '.' in name:
-            prename = name[:name.rfind('.')]
-            postname = name[len(prename)+1:]
-            if prename not in sys.modules:
-                __import__(prename)
-                if not hasattr(sys.modules[prename], postname):
-                    setattr(sys.modules[prename], postname, mod)
-
-    return partdir, this_dir
-
-def __clone():
-    """ clone master version of autopath.py into all subdirs """
-    from os.path import join, walk
-    if not this_dir.endswith(join('pypy','tool')):
-        raise EnvironmentError("can only clone master version "
-                               "'%s'" % join(pypydir, 'tool',_myname))
-
-
-    def sync_walker(arg, dirname, fnames):
-        if _myname in fnames:
-            fn = join(dirname, _myname)
-            f = open(fn, 'rwb+')
-            try:
-                if f.read() == arg:
-                    print "checkok", fn
-                else:
-                    print "syncing", fn
-                    f = open(fn, 'w')
-                    f.write(arg)
-            finally:
-                f.close()
-    s = open(join(pypydir, 'tool', _myname), 'rb').read()
-    walk(pypydir, sync_walker, s)
-
-_myname = 'autopath.py'
-
-# set guaranteed attributes
-
-pypydir, this_dir = __dirinfo('pypy')
-
-if __name__ == '__main__':
-    __clone()
diff --git a/pypy/rlib/rsdl/test/conftest.py b/pypy/rlib/rsdl/test/conftest.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/conftest.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from pypy.rlib.rsdl.eci import check_sdl_installation, SDLNotInstalled
-import py
-
-def pytest_ignore_collect(path):
-    try:
-        check_sdl_installation()
-    except SDLNotInstalled, e:
-        return True
-    else:
-        return False
diff --git a/pypy/rlib/rsdl/test/demo.jpg b/pypy/rlib/rsdl/test/demo.jpg
deleted file mode 100644
Binary file pypy/rlib/rsdl/test/demo.jpg has changed
diff --git a/pypy/rlib/rsdl/test/demo.png b/pypy/rlib/rsdl/test/demo.png
deleted file mode 100644
Binary file pypy/rlib/rsdl/test/demo.png has changed
diff --git a/pypy/rlib/rsdl/test/test_basic.py b/pypy/rlib/rsdl/test/test_basic.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/test_basic.py
+++ /dev/null
@@ -1,37 +0,0 @@
-import py
-from pypy.rlib.rsdl import RSDL
-from pypy.rlib.rarithmetic import r_uint
-from pypy.rpython.lltypesystem import rffi
-
-
-def test_sdl_init():
-    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
-    RSDL.Quit()
-
-def test_surface_basic():
-    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
-    surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
-                                    r_uint(0x000000FF),
-                                    r_uint(0x0000FF00),
-                                    r_uint(0x00FF0000),
-                                    r_uint(0xFF000000))
-    assert surface
-    assert rffi.getintfield(surface, 'c_w') == 150
-    assert rffi.getintfield(surface, 'c_h') == 50
-    RSDL.FreeSurface(surface)
-    RSDL.Quit()
-    
-    
-def test_get_keyname():
-    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
-    assert RSDL.GetKeyName(RSDL.K_PLUS)[0] == '+'
-    assert RSDL.GetKeyName(RSDL.K_RIGHTPAREN)[0] == ')'
-    assert RSDL.GetKeyName(RSDL.K_z)[0] == 'z'
-    
-def test_delay_getticks():
-    assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
-    RSDL.Delay(10)
-    i = RSDL.GetTicks()
-    assert i >= 10
-    RSDL.Quit()
-    
\ No newline at end of file
diff --git a/pypy/rlib/rsdl/test/test_sdl_image.py b/pypy/rlib/rsdl/test/test_sdl_image.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/test_sdl_image.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import py, os
-import autopath
-from pypy.rlib.rsdl import RSDL, RIMG, RSDL_helper
-from pypy.rpython.lltypesystem import lltype, rffi
-
-
-def test_load_image():
-    for filename in ["demo.jpg", "demo.png"]:
-        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
-        assert image
-        assert rffi.getintfield(image, 'c_w') == 17
-        assert rffi.getintfield(image, 'c_h') == 23
-        RSDL.FreeSurface(image)
-
-def test_image_pixels():
-    for filename in ["demo.jpg", "demo.png"]:
-        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
-        assert image
-        assert rffi.getintfield(image.c_format, 'c_BytesPerPixel') in (3, 4)
-        RSDL.LockSurface(image)
-        result = {}
-        try:
-            rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
-            try:
-                for y in range(23):
-                    for x in range(y % 13, 17, 13):
-                        color = RSDL_helper.get_pixel(image, x, y)
-                        RSDL.GetRGB(color,
-                                    image.c_format,
-                                    rffi.ptradd(rgb, 0),
-                                    rffi.ptradd(rgb, 1),
-                                    rffi.ptradd(rgb, 2))
-                        r = rffi.cast(lltype.Signed, rgb[0])
-                        g = rffi.cast(lltype.Signed, rgb[1])
-                        b = rffi.cast(lltype.Signed, rgb[2])
-                        result[x, y] = r, g, b
-            finally:
-                lltype.free(rgb, flavor='raw')
-        finally:
-            RSDL.UnlockSurface(image)
-        RSDL.FreeSurface(image)
-        for x, y in result:
-            f = (x*17 + y*23) / float(17*17+23*23)
-            expected_r = int(255.0 * (1.0-f))
-            expected_g = 0
-            expected_b = int(255.0 * f)
-            r, g, b = result[x, y]
-            assert abs(r-expected_r) < 10
-            assert abs(g-expected_g) < 10
-            assert abs(b-expected_b) < 10
diff --git a/pypy/rlib/rsdl/test/test_sdl_mixer.py b/pypy/rlib/rsdl/test/test_sdl_mixer.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/test_sdl_mixer.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import py
-import os
-import time
-import autopath
-from pypy.rlib.rsdl import RSDL, RMix, RSDL_helper
-from pypy.rpython.lltypesystem import lltype, rffi
-
-def test_open_mixer():
-    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
-        error = rffi.charp2str(RSDL.GetError())
-        raise Exception(error)
-    RMix.CloseAudio()
-
-def test_load_wav():
-    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
-        error = rffi.charp2str(RSDL.GetError())
-        raise Exception(error)
-    filename = rffi.str2charp('applause.wav')
-    RMix.LoadWAV(filename)
-    rffi.free_charp(filename)
-    RMix.CloseAudio()
-
-def test_play_wav():
-    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
-        error = rffi.charp2str(RSDL.GetError())
-        raise Exception(error)
-    filename = rffi.str2charp('applause.wav')
-    applause = RMix.LoadWAV(filename)
-    rffi.free_charp(filename)
-    RMix.PlayChannel(-1, applause, -1)
-    time.sleep(1)
-    RMix.CloseAudio()
-
diff --git a/pypy/rlib/rsdl/test/test_surface.py b/pypy/rlib/rsdl/test/test_surface.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/test_surface.py
+++ /dev/null
@@ -1,75 +0,0 @@
-import py, sys
-from pypy.rlib.rsdl import RSDL, RSDL_helper
-from pypy.rlib.rarithmetic import r_uint
-from pypy.rpython.lltypesystem import lltype, rffi
-
-class TestSurface:
-
-    def setup_method(self, meth):
-        self.dst_surf = RSDL.CreateRGBSurface(0, 300, 300, 32,
-                                        r_uint(0x000000FF),
-                                        r_uint(0x0000FF00),
-                                        r_uint(0x00FF0000),
-                                        r_uint(0x00000000))
-        self.src_surf = RSDL.CreateRGBSurface(0, 50, 50, 32,
-                                        r_uint(0x000000FF),
-                                        r_uint(0x0000FF00),
-                                        r_uint(0x00FF0000),
-                                        r_uint(0x00000000))
-        fmt = self.src_surf.c_format
-        self.black = RSDL.MapRGB(fmt, 0, 0, 0)
-        self.red = RSDL.MapRGB(fmt, 255, 0, 0)
-        self.blue = RSDL.MapRGB(fmt, 0, 0, 255)
-        RSDL.FillRect(self.src_surf, lltype.nullptr(RSDL.Rect), self.red)
-
-    def test_simple(self):
-        pass   # only checks that creating the surfaces works
-
-    def test_set_alpha(self):
-        # prepare
-        assert RSDL.SetAlpha(self.src_surf, RSDL.SRCALPHA, 128) == 0
-
-        # draw
-        RSDL_helper.blit_complete_surface(
-            self.src_surf,
-            self.dst_surf,
-            10, 10)
-        RSDL_helper.blit_complete_surface(
-            self.src_surf,
-            self.dst_surf,
-            20, 20)
-
-        # check
-        for position, color in (
-                (( 0, 0), (  0,0,0)), # no rect
-                ((10,10), (127,0,0)), # one rect
-                ((20,20), (191,0,0))  # two overlapping rects
-            ):
-            fetched_color = RSDL_helper.get_pixel(self.dst_surf, position[0], position[1])
-            assert RSDL_helper.get_rgb(fetched_color, self.dst_surf.c_format) == color 
-
-    def test_set_color_key(self):
-        # prepare
-        fillrect = RSDL_helper.mallocrect(10, 10, 30, 30)
-        RSDL.FillRect(self.src_surf, fillrect, self.blue)
-        lltype.free(fillrect, flavor='raw')
-        assert RSDL.SetColorKey(self.src_surf, RSDL.SRCCOLORKEY, self.blue) == 0
-
-        # draw
-        RSDL_helper.blit_complete_surface(self.src_surf, self.dst_surf, 0, 0)
-
-        # check
-        for position, color in (
-                (( 0, 0), self.red),
-                ((10,10), self.black),
-                ((20,20), self.black),
-                ((40,40), self.red)
-            ):
-            fetched_color = RSDL_helper.get_pixel(self.dst_surf, position[0], position[1])
-            assert fetched_color == color
-
-    def teardown_method(self, meth):
-        RSDL.FreeSurface(self.src_surf)
-        RSDL.FreeSurface(self.dst_surf)
-        RSDL.Quit()
-
diff --git a/pypy/rlib/rsdl/test/test_video.py b/pypy/rlib/rsdl/test/test_video.py
deleted file mode 100644
--- a/pypy/rlib/rsdl/test/test_video.py
+++ /dev/null
@@ -1,241 +0,0 @@
-
-import py, sys
-from pypy.rlib.rsdl import RSDL, RSDL_helper
-from pypy.rlib.rarithmetic import r_uint
-from pypy.rpython.lltypesystem import lltype, rffi
-from pypy import conftest
-
-#
-#  This test file is skipped unless run with "py.test --view".
-#  If it is run as "py.test --view -s", then it interactively asks
-#  for confirmation that the window looks as expected.
-#
-
-
-class TestVideo:
-
-    def setup_method(self, meth):
-        if not conftest.option.view:
-            py.test.skip("'--view' not specified, "
-                         "skipping tests that open a window")
-        assert RSDL.Init(RSDL.INIT_VIDEO) >= 0
-        self.screen = RSDL.SetVideoMode(640, 480, 32, 0)
-        assert self.screen
-        self.is_interactive = sys.stdout.isatty()
-
-    def check(self, msg):
-        if self.is_interactive:
-            print
-            answer = raw_input('Interactive test: %s - ok? [Y] ' % msg)
-            if answer and not answer.upper().startswith('Y'):
-                py.test.fail(msg)
-        else:
-            print msg
-
-    def test_simple(self):
-        pass   # only checks that opening and closing the window works
-
-    def test_fillrect_full(self):
-        fmt = self.screen.c_format
-        for colorname, r, g, b in [('dark red', 128, 0, 0),
-                                   ('yellow', 255, 255, 0),
-                                   ('blue', 0, 0, 255)]:
-            color = RSDL.MapRGB(fmt, r, g, b)
-            RSDL.FillRect(self.screen, lltype.nullptr(RSDL.Rect), color)
-            RSDL.Flip(self.screen)
-            self.check("Screen filled with %s" % colorname)
-
-    def test_caption(self):
-        RSDL.WM_SetCaption("Hello World!", "Hello World!")
-        self.check('The window caption is "Hello World!"')
-
-    def test_keypresses(self):
-        if not self.is_interactive:
-            py.test.skip("interactive test only")
-        RSDL.EnableUNICODE(1)
-        print
-        print "Keys pressed in the Pygame window should be printed below."
-        print "    Use Escape to quit."
-        event = lltype.malloc(RSDL.Event, flavor='raw')
-        try:
-            while True:
-                    ok = RSDL.WaitEvent(event)
-                    assert rffi.cast(lltype.Signed, ok) == 1
-                    c_type = rffi.getintfield(event, 'c_type')
-                    if c_type == RSDL.KEYDOWN:
-                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
-                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
-                            print 'Escape key'
-                            break
-                        char = rffi.getintfield(p.c_keysym, 'c_unicode')
-                        if char != 0:
-                            print 'Key:', unichr(char).encode('utf-8')
-                        else:
-                            print 'Some special key'
-                    else:
-                        print '(event of type %d)' % c_type
-        finally:
-            lltype.free(event, flavor='raw')
-
-    def test_poll(self):
-        if not self.is_interactive:
-            py.test.skip("interactive test only")
-        import time, sys
-        RSDL.EnableUNICODE(1)
-        print
-        print "Keys pressed in the Pygame window give a dot."
-        print "    Wait 3 seconds to quit."
-        timeout = time.time() + 3
-        event = lltype.malloc(RSDL.Event, flavor='raw')
-        try:
-            while True:
-                # busy polling
-                ok = RSDL.PollEvent(event)
-                ok = rffi.cast(lltype.Signed, ok)
-                assert ok >= 0
-                if ok > 0:
-                    c_type = rffi.getintfield(event, 'c_type')
-                    if c_type == RSDL.KEYDOWN:
-                        sys.stderr.write('.')
-                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
-                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
-                            print 'Escape key'
-                            break
-                        timeout = time.time() + 3
-                else:
-                    if time.time() > timeout:
-                        break
-                time.sleep(0.05)
-        finally:
-            lltype.free(event, flavor='raw')
-
-    def test_mousemove(self):
-        if not self.is_interactive:
-            py.test.skip("interactive test only")
-        print
-        print "Move the Mouse up and down:"
-        print "    Use Escape to quit."
-        event = lltype.malloc(RSDL.Event, flavor="raw")
-        directions = [False]*4
-        try:
-            while True:
-                ok = RSDL.WaitEvent(event)
-                assert rffi.cast(lltype.Signed, ok) == 1
-                c_type = rffi.getintfield(event, "c_type")
-                if c_type == RSDL.MOUSEMOTION:
-                    m = rffi.cast(RSDL.MouseMotionEventPtr, event)
-                    assert rffi.getintfield(m, "c_x") >= 0
-                    assert rffi.getintfield(m, "c_y") >= 0
-                    print rffi.getintfield(m, "c_xrel")
-                    directions[0] |= rffi.getintfield(m, "c_xrel")>0
-                    directions[1] |= rffi.getintfield(m, "c_xrel")<0
-                    directions[2] |= rffi.getintfield(m, "c_yrel")>0
-                    directions[3] |= rffi.getintfield(m, "c_yrel")<0
-                    if False not in directions:
-                        break
-                elif c_type == RSDL.KEYUP:
-                    p = rffi.cast(RSDL.KeyboardEventPtr, event)
-                    if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
-                        print "    test manually aborted"
-                        py.test.fail(" mousemovement test aborted")
-                        break  
-        finally:
-            lltype.free(event, flavor='raw')
-                
-
-    def test_mousebutton_wheel(self):
-        if not self.is_interactive:
-            py.test.skip("interactive test only")
-        print
-        print "Press the given MouseButtons:"
-        print "        Use Escape to pass tests."
-        
-        event_tests = [("left button",   RSDL.BUTTON_LEFT),
-                       ("middle button", RSDL.BUTTON_MIDDLE),
-                       ("right button",  RSDL.BUTTON_RIGHT),
-                       ("scroll up",     RSDL.BUTTON_WHEELUP),
-                       ("scroll down",   RSDL.BUTTON_WHEELDOWN)]
-        test_success = []
-        event = lltype.malloc(RSDL.Event, flavor='raw')
-        try:
-            for button_test in event_tests:
-                print "    press %s:" % button_test[0]
-                while True:
-                    ok = RSDL.WaitEvent(event)
-                    assert rffi.cast(lltype.Signed, ok) == 1
-                    c_type = rffi.getintfield(event, 'c_type')
-                    if c_type == RSDL.MOUSEBUTTONDOWN:
-                        pass
-                    elif c_type == RSDL.MOUSEBUTTONUP:
-                        b = rffi.cast(RSDL.MouseButtonEventPtr, event)
-                        if rffi.getintfield(b, 'c_button') == button_test[1]:
-                            test_success.append(True)
-                            break
-                    elif c_type == RSDL.KEYUP:
-                        p = rffi.cast(RSDL.KeyboardEventPtr, event)
-                        if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
-                            test_success.append(False) 
-                            print "        manually aborted"
-                            break
-                        #break
-            if False in test_success:
-                py.test.fail("")
-        finally:
-            lltype.free(event, flavor='raw')
-            
-            
-    def test_show_hide_cursor(self):
-        RSDL.ShowCursor(RSDL.DISABLE)
-        self.check("Is the cursor hidden? ")
-        RSDL.ShowCursor(RSDL.ENABLE)
-        self.check("Is the cursor shown? ")
-        
-    def test_bit_pattern(self):
-        HEIGHT = WIDTH = 10
-        fmt = self.screen.c_format
-        white = RSDL.MapRGB(fmt, 255, 255, 255)
-        black = RSDL.MapRGB(fmt, 0, 0, 0)
-        RSDL.LockSurface(self.screen)
-        for i in xrange(WIDTH):
-            for j in xrange(HEIGHT):
-                k = j*WIDTH + i
-                if k % 2:
-                    c = white
-                else:
-                    c = black
-                RSDL_helper.set_pixel(self.screen, i, j, c)
-        RSDL.UnlockSurface(self.screen)
-        RSDL.Flip(self.screen)
-        self.check("Upper left corner 10x10 field with vertical black/white stripes")
-
-    def test_blit_rect(self):
-        surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
-                                        r_uint(0x000000FF),
-                                        r_uint(0x0000FF00),
-                                        r_uint(0x00FF0000),
-                                        r_uint(0xFF000000))
-        fmt = surface.c_format
-        color = RSDL.MapRGB(fmt, 255, 0, 0)
-        RSDL.FillRect(surface, lltype.nullptr(RSDL.Rect), color)
-        
-        paintrect = RSDL_helper.mallocrect(75, 0, 150, 50)
-        dstrect = lltype.malloc(RSDL.Rect, flavor='raw')
-        try:
-            color = RSDL.MapRGB(fmt, 255, 128, 0)
-            RSDL.FillRect(surface, paintrect, color)
-
-            rffi.setintfield(dstrect, 'c_x',  10)
-            rffi.setintfield(dstrect, 'c_y',  10)
-            rffi.setintfield(dstrect, 'c_w', 150)
-            rffi.setintfield(dstrect, 'c_h',  50)
-            RSDL.BlitSurface(surface, lltype.nullptr(RSDL.Rect), self.screen, dstrect)
-            RSDL.Flip(self.screen)
-        finally:
-            lltype.free(dstrect, flavor='raw')
-            lltype.free(paintrect, flavor='raw')
-        RSDL.FreeSurface(surface)
-        self.check("Half Red/Orange rectangle(150px * 50px) at the top left, 10 pixels from the border")
-
-    def teardown_method(self, meth):
-        RSDL.Quit()
-
diff --git a/pypy/rlib/rwin32.py b/pypy/rlib/rwin32.py
--- a/pypy/rlib/rwin32.py
+++ b/pypy/rlib/rwin32.py
@@ -367,6 +367,14 @@
         'GetCurrentProcessId', [], DWORD)
     def GetCurrentProcessId():
         return rffi.cast(lltype.Signed, _GetCurrentProcessId())
+
+    _GetConsoleCP = winexternal('GetConsoleCP', [], DWORD)
+    _GetConsoleOutputCP = winexternal('GetConsoleOutputCP', [], DWORD)
+    def GetConsoleCP():
+        return rffi.cast(lltype.Signed, _GetConsoleCP())
+    def GetConsoleOutputCP():
+        return rffi.cast(lltype.Signed, _GetConsoleOutputCP())
+
     def os_kill(pid, sig):
         if sig == CTRL_C_EVENT or sig == CTRL_BREAK_EVENT:
             if GenerateConsoleCtrlEvent(sig, pid) == 0:
diff --git a/pypy/rlib/streamio.py b/pypy/rlib/streamio.py
--- a/pypy/rlib/streamio.py
+++ b/pypy/rlib/streamio.py
@@ -500,7 +500,7 @@
         if self.buf:
             try:
                 self.do_seek(self.tell(), 0)
-            except MyNotImplementedError:
+            except (MyNotImplementedError, OSError):
                 pass
             else:
                 self.buf = ""
@@ -713,7 +713,7 @@
         if self.buf is not None:
             try:
                 self.do_seek(self.bufstart-len(self.buf), 1)
-            except MyNotImplementedError:
+            except (MyNotImplementedError, OSError):
                 pass
             else:
                 self.buf = None
@@ -968,7 +968,10 @@
 
     def flush_buffers(self):
         if self.lfbuffer:
-            self.base.seek(-len(self.lfbuffer), 1)
+            try:
+                self.base.seek(-len(self.lfbuffer), 1)
+            except (MyNotImplementedError, OSError):
+                return
             self.lfbuffer = ""
         self.do_flush()
 
@@ -1102,7 +1105,7 @@
         if self.buf:
             try:
                 self.base.seek(-len(self.buf), 1)
-            except MyNotImplementedError:
+            except (MyNotImplementedError, OSError):
                 pass
             else:
                 self.buf = ""
diff --git a/pypy/rlib/test/test_libffi.py b/pypy/rlib/test/test_libffi.py
--- a/pypy/rlib/test/test_libffi.py
+++ b/pypy/rlib/test/test_libffi.py
@@ -1,12 +1,13 @@
-import sys
+import os
 
 import py
 
 from pypy.rlib.rarithmetic import r_singlefloat, r_longlong, r_ulonglong
-from pypy.rlib.test.test_clibffi import BaseFfiTest, get_libm_name, make_struct_ffitype_e
+from pypy.rlib.test.test_clibffi import BaseFfiTest, make_struct_ffitype_e
 from pypy.rpython.lltypesystem import rffi, lltype
 from pypy.rpython.lltypesystem.ll2ctypes import ALLOCATED
-from pypy.rlib.libffi import (CDLL, Func, get_libc_name, ArgChain, types,
+from pypy.rpython.llinterp import LLException
+from pypy.rlib.libffi import (CDLL, ArgChain, types,
                               IS_32_BIT, array_getitem, array_setitem)
 from pypy.rlib.libffi import (struct_getfield_int, struct_setfield_int,
                               struct_getfield_longlong, struct_setfield_longlong,
@@ -175,6 +176,15 @@
         #
         lltype.free(p, flavor='raw')
 
+    def test_windll(self):
+        if os.name != 'nt':
+            skip('Run only on windows')
+        from pypy.rlib.libffi import WinDLL
+        dll = WinDLL('Kernel32.dll')
+        sleep = dll.getpointer('Sleep',[types.uint], types.void)
+        chain = ArgChain()
+        chain.arg(10)
+        sleep.call(chain, lltype.Void, is_struct=False)
 
 class TestLibffiCall(BaseFfiTest):
     """
@@ -219,9 +229,16 @@
         eci = ExternalCompilationInfo(export_symbols=exports)
         cls.libfoo_name = str(platform.compile([c_file], eci, 'x',
                                                standalone=False))
+        cls.dll = cls.CDLL(cls.libfoo_name)
+
+    def teardown_class(cls):
+        if cls.dll:
+            cls.dll.__del__()
+            # Why doesn't this call cls.dll.__del__() ?
+            #del cls.dll
 
     def get_libfoo(self):
-        return self.CDLL(self.libfoo_name)
+        return self.dll    
 
     def call(self, funcspec, args, RESULT, is_struct=False, jitif=[]):
         """
@@ -536,4 +553,27 @@
         assert p[1] == 34
         lltype.free(p, flavor='raw')
         lltype.free(ffi_point_struct, flavor='raw')
+
+    if os.name == 'nt':
+        def test_stdcall_simple(self):
+            """
+                int __stdcall std_diff_xy(int x, Signed y)
+                {
+                    return x - y;
+                }
+            """
+            libfoo = self.get_libfoo()
+            func = (libfoo, 'std_diff_xy', [types.sint, types.signed], types.sint)
+            try:
+                self.call(func, [50, 8], lltype.Signed)
+            except ValueError, e:
+                assert e.message == 'Procedure called with not enough ' + \
+                     'arguments (8 bytes missing) or wrong calling convention'
+            except LLException, e:
+                #jitted code raises this
+                assert str(e) == "<LLException 'StackCheckError'>"
+            else:
+                assert 0, 'wrong calling convention should have raised'
+
+
         
diff --git a/pypy/rlib/test/test_rjvm.py b/pypy/rlib/test/test_rjvm.py
--- a/pypy/rlib/test/test_rjvm.py
+++ b/pypy/rlib/test/test_rjvm.py
@@ -1,4 +1,6 @@
 import py
+py.test.skip('this is outdated. Check the jvm-improvements branch')
+
 try:
     import jpype
 except ImportError:
diff --git a/pypy/rpython/memory/gc/minimark.py b/pypy/rpython/memory/gc/minimark.py
--- a/pypy/rpython/memory/gc/minimark.py
+++ b/pypy/rpython/memory/gc/minimark.py
@@ -111,10 +111,13 @@
 # The following flag is set on externally raw_malloc'ed arrays of pointers.
 # They are allocated with some extra space in front of them for a bitfield,
 # one bit per 'card_page_indices' indices.
-GCFLAG_HAS_CARDS    = first_gcflag << 5
-GCFLAG_CARDS_SET    = first_gcflag << 6     # <- at least one card bit is set
+GCFLAG_HAS_CARDS    = first_gcflag << 6
+GCFLAG_CARDS_SET    = first_gcflag << 7     # <- at least one card bit is set
+# note that GCFLAG_CARDS_SET is the most significant bit of a byte:
+# this is required for the JIT (x86)
 
-TID_MASK            = (first_gcflag << 7) - 1
+#GCFLAG_UNUSED      = first_gcflag << 5     # this flag is free
+TID_MASK            = (first_gcflag << 8) - 1
 
 
 FORWARDSTUB = lltype.GcStruct('forwarding_stub',
@@ -994,12 +997,9 @@
     def _init_writebarrier_logic(self):
         DEBUG = self.DEBUG
         # The purpose of attaching remember_young_pointer to the instance
-        # instead of keeping it as a regular method is to help the JIT call it.
-        # Additionally, it makes the code in write_barrier() marginally smaller
+        # instead of keeping it as a regular method is to
+        # make the code in write_barrier() marginally smaller
         # (which is important because it is inlined *everywhere*).
-        # For x86, there is also an extra requirement: when the JIT calls
-        # remember_young_pointer(), it assumes that it will not touch the SSE
-        # registers, so it does not save and restore them (that's a *hack*!).
         def remember_young_pointer(addr_struct, newvalue):
             # 'addr_struct' is the address of the object in which we write.
             # 'newvalue' is the address that we are going to write in there.
@@ -1033,6 +1033,17 @@
         remember_young_pointer._dont_inline_ = True
         self.remember_young_pointer = remember_young_pointer
         #
+        def jit_remember_young_pointer(addr_struct):
+            # minimal version of the above, with just one argument,
+            # called by the JIT when GCFLAG_TRACK_YOUNG_PTRS is set
+            self.old_objects_pointing_to_young.append(addr_struct)
+            objhdr = self.header(addr_struct)
+            objhdr.tid &= ~GCFLAG_TRACK_YOUNG_PTRS
+            if objhdr.tid & GCFLAG_NO_HEAP_PTRS:
+                objhdr.tid &= ~GCFLAG_NO_HEAP_PTRS
+                self.prebuilt_root_objects.append(addr_struct)
+        self.jit_remember_young_pointer = jit_remember_young_pointer
+        #
         if self.card_page_indices > 0:
             self._init_writebarrier_with_card_marker()
 
@@ -1087,60 +1098,21 @@
         self.remember_young_pointer_from_array2 = (
             remember_young_pointer_from_array2)
 
-        # xxx trying it out for the JIT: a 3-arguments version of the above
-        def remember_young_pointer_from_array3(addr_array, index, newvalue):
+        def jit_remember_young_pointer_from_array(addr_array):
+            # minimal version of the above, with just one argument,
+            # called by the JIT when GCFLAG_TRACK_YOUNG_PTRS is set
+            # but GCFLAG_CARDS_SET is cleared.  This tries to set
+            # GCFLAG_CARDS_SET if possible; otherwise, it falls back
+            # to jit_remember_young_pointer().
             objhdr = self.header(addr_array)
-            #
-            # a single check for the common case of neither GCFLAG_HAS_CARDS
-            # nor GCFLAG_NO_HEAP_PTRS
-            if objhdr.tid & (GCFLAG_HAS_CARDS | GCFLAG_NO_HEAP_PTRS) == 0:
-                # common case: fast path, jump to the end of the function
-                pass
-            elif objhdr.tid & GCFLAG_HAS_CARDS == 0:
-                # no cards, but GCFLAG_NO_HEAP_PTRS is set.
-                objhdr.tid &= ~GCFLAG_NO_HEAP_PTRS
-                self.prebuilt_root_objects.append(addr_array)
-                # jump to the end of the function
+            if objhdr.tid & GCFLAG_HAS_CARDS:
+                self.old_objects_with_cards_set.append(addr_array)
+                objhdr.tid |= GCFLAG_CARDS_SET
             else:
-                # case with cards.
-                #
-                # If the newly written address does not actually point to a
-                # young object, leave now.
-                if not self.appears_to_be_young(newvalue):
-                    return
-                #
-                # 'addr_array' is a raw_malloc'ed array with card markers
-                # in front.  Compute the index of the bit to set:
-                bitindex = index >> self.card_page_shift
-                byteindex = bitindex >> 3
-                bitmask = 1 << (bitindex & 7)
-                #
-                # If the bit is already set, leave now.
-                addr_byte = self.get_card(addr_array, byteindex)
-                byte = ord(addr_byte.char[0])
-                if byte & bitmask:
-                    return
-                addr_byte.char[0] = chr(byte | bitmask)
-                #
-                if objhdr.tid & GCFLAG_CARDS_SET == 0:
-                    self.old_objects_with_cards_set.append(addr_array)
-                    objhdr.tid |= GCFLAG_CARDS_SET
-                return
-            #
-            # Logic for the no-cards case, put here to minimize the number
-            # of checks done at the start of the function
-            if DEBUG:   # note: PYPY_GC_DEBUG=1 does not enable this
-                ll_assert(self.debug_is_old_object(addr_array),
-                        "young array with no card but GCFLAG_TRACK_YOUNG_PTRS")
-            #
-            if self.appears_to_be_young(newvalue):
-                self.old_objects_pointing_to_young.append(addr_array)
-                objhdr.tid &= ~GCFLAG_TRACK_YOUNG_PTRS
+                self.jit_remember_young_pointer(addr_array)
 
-        remember_young_pointer_from_array3._dont_inline_ = True
-        assert self.card_page_indices > 0
-        self.remember_young_pointer_from_array3 = (
-            remember_young_pointer_from_array3)
+        self.jit_remember_young_pointer_from_array = (
+            jit_remember_young_pointer_from_array)
 
     def get_card(self, obj, byteindex):
         size_gc_header = self.gcheaderbuilder.size_gc_header
diff --git a/pypy/rpython/memory/gctransform/framework.py b/pypy/rpython/memory/gctransform/framework.py
--- a/pypy/rpython/memory/gctransform/framework.py
+++ b/pypy/rpython/memory/gctransform/framework.py
@@ -455,13 +455,12 @@
                                             annmodel.SomeAddress()],
                                            annmodel.s_None,
                                            inline=True)
-            func = getattr(gcdata.gc, 'remember_young_pointer', None)
+            func = getattr(gcdata.gc, 'jit_remember_young_pointer', None)
             if func is not None:
                 # func should not be a bound method, but a real function
                 assert isinstance(func, types.FunctionType)
                 self.write_barrier_failing_case_ptr = getfn(func,
-                                               [annmodel.SomeAddress(),
-                                                annmodel.SomeAddress()],
+                                               [annmodel.SomeAddress()],
                                                annmodel.s_None)
             func = getattr(GCClass, 'write_barrier_from_array', None)
             if func is not None:
@@ -472,16 +471,15 @@
                                             annmodel.SomeInteger()],
                                            annmodel.s_None,
                                            inline=True)
-                func = getattr(gcdata.gc, 'remember_young_pointer_from_array3',
+                func = getattr(gcdata.gc,
+                               'jit_remember_young_pointer_from_array',
                                None)
                 if func is not None:
                     # func should not be a bound method, but a real function
                     assert isinstance(func, types.FunctionType)
                     self.write_barrier_from_array_failing_case_ptr = \
                                              getfn(func,
-                                                   [annmodel.SomeAddress(),
-                                                    annmodel.SomeInteger(),
-                                                    annmodel.SomeAddress()],
+                                                   [annmodel.SomeAddress()],
                                                    annmodel.s_None)
         self.statistics_ptr = getfn(GCClass.statistics.im_func,
                                     [s_gc, annmodel.SomeInteger()],
diff --git a/pypy/rpython/module/ll_os.py b/pypy/rpython/module/ll_os.py
--- a/pypy/rpython/module/ll_os.py
+++ b/pypy/rpython/module/ll_os.py
@@ -148,6 +148,7 @@
 else:
     includes += ['sys/utime.h']
 
+_CYGWIN = sys.platform == 'cygwin'
 
 class CConfig:
     """
@@ -1329,9 +1330,14 @@
                 return result
         else:
             # Posix
-            os_waitpid = self.llexternal('waitpid',
-                                         [rffi.PID_T, rffi.INTP, rffi.INT],
-                                         rffi.PID_T)
+            if _CYGWIN:
+                os_waitpid = self.llexternal('cygwin_waitpid',
+                                             [rffi.PID_T, rffi.INTP, rffi.INT],
+                                             rffi.PID_T)
+            else:
+                os_waitpid = self.llexternal('waitpid',
+                                             [rffi.PID_T, rffi.INTP, rffi.INT],
+                                             rffi.PID_T)
 
         def os_waitpid_llimpl(pid, options):
             status_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
diff --git a/pypy/tool/release/package.py b/pypy/tool/release/package.py
--- a/pypy/tool/release/package.py
+++ b/pypy/tool/release/package.py
@@ -145,6 +145,8 @@
             archive = str(builddir.join(name + '.tar.bz2'))
             if sys.platform == 'darwin' or sys.platform.startswith('freebsd'):
                 e = os.system('tar --numeric-owner -cvjf ' + archive + " " + name)
+            elif sys.platform == 'cygwin':
+                e = os.system('tar --owner=Administrator --group=Administrators --numeric-owner -cvjf ' + archive + " " + name)
             else:
                 e = os.system('tar --owner=root --group=root --numeric-owner -cvjf ' + archive + " " + name)
             if e:
diff --git a/pypy/translator/c/genc.py b/pypy/translator/c/genc.py
--- a/pypy/translator/c/genc.py
+++ b/pypy/translator/c/genc.py
@@ -15,6 +15,8 @@
 from pypy.rlib import exports
 from pypy.tool.nullpath import NullPyPathLocal
 
+_CYGWIN = sys.platform == 'cygwin'
+
 def import_module_from_directory(dir, modname):
     file, pathname, description = imp.find_module(modname, [str(dir)])
     try:
@@ -954,6 +956,8 @@
         srcdir / 'profiling.c',
         srcdir / 'debug_print.c',
     ]
+    if _CYGWIN:
+        files.append(srcdir / 'cygwin_wait.c')
     return eci.merge(ExternalCompilationInfo(separate_module_files=files))
 
 
diff --git a/pypy/translator/c/src/cygwin_wait.c b/pypy/translator/c/src/cygwin_wait.c
new file mode 100644
--- /dev/null
+++ b/pypy/translator/c/src/cygwin_wait.c
@@ -0,0 +1,47 @@
+/*
+  Work around compile error:
+  [translation:ERROR]     implement_4.c: In function 'pypy_g_ccall_waitpid__Signed_arrayPtr_Signed':
+  [translation:ERROR]     implement_4.c:150095:2: error: incompatible type for argument 2 of 'waitpid'
+  [translation:ERROR]     /usr/include/sys/wait.h:43:7: note: expected '__wait_status_ptr_t' but argument is of type 'long int *'
+*/
+
+#ifdef __CYGWIN__
+
+#include "wait.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  /*
+typedef int *__wait_status_ptr_t;
+  */
+
+  /*
+pid_t wait (__wait_status_ptr_t __status);
+pid_t waitpid (pid_t __pid, __wait_status_ptr_t __status, int __options);
+pid_t wait3 (__wait_status_ptr_t __status, int __options, struct rusage *__rusage);
+pid_t wait4 (pid_t __pid, __wait_status_ptr_t __status, int __options, struct rusage *__rusage);
+  */
+
+  pid_t cygwin_wait (int * __status){
+    return wait ((__wait_status_ptr_t) __status);
+  }
+
+  pid_t cygwin_waitpid (pid_t __pid, int * __status, int __options){
+    return waitpid (__pid, (__wait_status_ptr_t) __status, __options);
+  }
+
+  pid_t cygwin_wait3 (int * __status, int __options, struct rusage *__rusage){
+    return wait3 ((__wait_status_ptr_t) __status, __options, __rusage);
+  }
+
+  pid_t cygwin_wait4 (pid_t __pid, int * __status, int __options, struct rusage *__rusage){
+    return wait4 (__pid, (__wait_status_ptr_t) __status, __options, __rusage);
+  }
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pypy/translator/c/src/cygwin_wait.h b/pypy/translator/c/src/cygwin_wait.h
new file mode 100644
--- /dev/null
+++ b/pypy/translator/c/src/cygwin_wait.h
@@ -0,0 +1,43 @@
+/*
+  Work around compile error:
+  [translation:ERROR]     implement_4.c: In function 'pypy_g_ccall_waitpid__Signed_arrayPtr_Signed':
+  [translation:ERROR]     implement_4.c:150095:2: error: incompatible type for argument 2 of 'waitpid'
+  [translation:ERROR]     /usr/include/sys/wait.h:43:7: note: expected '__wait_status_ptr_t' but argument is of type 'long int *'
+*/
+
+#ifdef __CYGWIN__
+
+#ifndef _PYPY_WAIT_H
+#define _PYPY_WAIT_H
+
+#ifndef _SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+  /*
+typedef int *__wait_status_ptr_t;
+  */
+
+  /*
+pid_t wait (__wait_status_ptr_t __status);
+pid_t waitpid (pid_t __pid, __wait_status_ptr_t __status, int __options);
+pid_t wait3 (__wait_status_ptr_t __status, int __options, struct rusage *__rusage);
+pid_t wait4 (pid_t __pid, __wait_status_ptr_t __status, int __options, struct rusage *__rusage);
+  */
+
+  pid_t cygwin_wait (int * __status);
+  pid_t cygwin_waitpid (pid_t __pid, int * __status, int __options);
+  pid_t cygwin_wait3 (int * __status, int __options, struct rusage *__rusage);
+  pid_t cygwin_wait4 (pid_t __pid, int * __status, int __options, struct rusage *__rusage);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#endif
diff --git a/pypy/translator/c/src/g_include.h b/pypy/translator/c/src/g_include.h
--- a/pypy/translator/c/src/g_include.h
+++ b/pypy/translator/c/src/g_include.h
@@ -61,3 +61,8 @@
 #    pragma warning(disable: 4033 4102 4101 4716)
 #  endif
 #endif
+
+/* work around waitpid expecting different pointer type */
+#ifdef __CYGWIN__
+#include "src/cygwin_wait.h"
+#endif
diff --git a/pypy/translator/goal/app_main.py b/pypy/translator/goal/app_main.py
--- a/pypy/translator/goal/app_main.py
+++ b/pypy/translator/goal/app_main.py
@@ -288,7 +288,7 @@
             sys.path.append(dir)
             _seen[dir] = True
 
-def set_io_encoding(io_encoding):
+def set_io_encoding(io_encoding, io_encoding_output, errors, overridden):
     try:
         import _file
     except ImportError:
@@ -299,12 +299,11 @@
         set_file_encoding.argtypes = [ctypes.py_object, ctypes.c_char_p, ctypes.c_char_p]
     else:
         set_file_encoding = _file.set_file_encoding
-    if ":" in io_encoding:
-        encoding, errors = io_encoding.split(":", 1)
-    else:
-        encoding, errors = io_encoding, None
-    for f in [sys.stdin, sys.stdout, sys.stderr]:
-        set_file_encoding(f, encoding, errors)
+    for f, encoding in [(sys.stdin, io_encoding),
+                        (sys.stdout, io_encoding_output),
+                        (sys.stderr, io_encoding_output)]:
+        if isinstance(f, file) and (overridden or f.isatty()):
+            set_file_encoding(f, encoding, errors)
 
 # Order is significant!
 sys_flags = (
@@ -513,10 +512,20 @@
             print >> sys.stderr, "'import site' failed"
 
     readenv = not ignore_environment
-    io_encoding = ((readenv and os.getenv("PYTHONIOENCODING"))
-                   or sys.getfilesystemencoding())
+    io_encoding = readenv and os.getenv("PYTHONIOENCODING")
     if io_encoding:
-        set_io_encoding(io_encoding)
+        errors = None
+        if ":" in io_encoding:
+            io_encoding, errors = io_encoding.split(":", 1)
+        set_io_encoding(io_encoding, io_encoding, errors, True)
+    else:
+        if IS_WINDOWS:
+            import __pypy__
+            io_encoding, io_encoding_output = __pypy__.get_console_cp()
+        else:
+            io_encoding = io_encoding_output = sys.getfilesystemencoding()
+        if io_encoding:
+            set_io_encoding(io_encoding, io_encoding_output, None, False)
 
     pythonwarnings = readenv and os.getenv('PYTHONWARNINGS')
     if pythonwarnings:
diff --git a/pypy/translator/goal/targetsimplevideo.py b/pypy/translator/goal/targetsimplevideo.py
deleted file mode 100644
--- a/pypy/translator/goal/targetsimplevideo.py
+++ /dev/null
@@ -1,98 +0,0 @@
-from pypy.rlib.rsdl import RSDL, RSDL_helper
-from pypy.rpython.lltypesystem import rffi, lltype
-import py
-
-WIDTH = 1000
-HEIGHT = 1000
-
-def entry_point(argv=None):
-    RSDL.Init(RSDL.INIT_VIDEO) >= 0
-    screen = RSDL.SetVideoMode(WIDTH, HEIGHT, 32, 0)
-    event = lltype.malloc(RSDL.Event, flavor='raw')
-    paintpattern = 0
-    try:
-        while True:
-            ok = RSDL.WaitEvent(event)
-            assert rffi.cast(lltype.Signed, ok) == 1
-            c_type = rffi.getintfield(event, 'c_type')
-            if c_type == RSDL.KEYDOWN:
-                p = rffi.cast(RSDL.KeyboardEventPtr, event)
-                if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
-                    print 'Escape key'
-                    break
-            paintpattern += 1
-            update_screen(screen, paintpattern)
-    finally:
-        lltype.free(event, flavor='raw')
-
-    return 0
-        
-# -----------------------------------------------------------------------------
-
-def chess(screen, cola, colb):
-    for i in xrange(WIDTH):
-        for j in xrange(HEIGHT):
-            if (i+j) % 2:
-                c = cola
-            else:
-                c = colb
-            RSDL_helper.set_pixel(screen, i, j, c)
-                
-def white(screen, cola, colb):
-    for i in xrange(WIDTH):
-        for j in xrange(HEIGHT):
-            RSDL_helper.set_pixel(screen, i, j, colb)
-                
-def black(screen, cola, colb):
-    for i in xrange(WIDTH):
-        for j in xrange(HEIGHT):
-            RSDL_helper.set_pixel(screen, i, j, cola)
-                
-def stripes_v(screen, cola, colb):
-    for i in xrange(WIDTH):
-        for j in xrange(HEIGHT):
-            k = j*WIDTH + i
-            if k % 2:
-                c = cola
-            else:
-                c = colb
-            RSDL_helper.set_pixel(screen, i, j, c)
-                
-def stripes_m(screen, cola, colb):
-    for j in xrange(WIDTH):
-        for i in xrange(HEIGHT):
-            k = j*WIDTH + i
-            if k % 2:
-                c = cola
-            else:
-                c = colb
-            RSDL_helper.set_pixel(screen, i, j, c)
-            
-
-# -----------------------------------------------------------------------------
-
-pattern = [chess, white, black, stripes_v, stripes_m]
-pl = len(pattern)
-def update_screen(screen, paintpattern):
-    fmt = screen.c_format
-    white = RSDL.MapRGB(fmt, 255, 255, 255)
-    black = RSDL.MapRGB(fmt, 0, 0, 0)
-    RSDL.LockSurface(screen)
-    pattern[paintpattern % pl](screen, black, white)
-    RSDL.UnlockSurface(screen)
-    RSDL.Flip(screen)
-    RSDL.Delay(10  )
-    
-    
-# -----------------------------------------------------------------------------
-
-def target(*args):
-    return entry_point, None
-
-def test_target():
-    entry_point()
-
-if __name__ == '__main__':
-    entry_point()
-
-
diff --git a/pypy/translator/platform/__init__.py b/pypy/translator/platform/__init__.py
--- a/pypy/translator/platform/__init__.py
+++ b/pypy/translator/platform/__init__.py
@@ -278,6 +278,13 @@
         host_factory = Windows
     else:
         host_factory = Windows_x64
+elif sys.platform == 'cygwin':
+    from pypy.translator.platform.cygwin import Cygwin, Cygwin64
+    import platform
+    if platform.architecture()[0] == '32bit':
+        host_factory = Cygwin
+    else:
+        host_factory = Cygwin64
 else:
     # pray
     from pypy.translator.platform.distutils_platform import DistutilsPlatform
diff --git a/pypy/translator/platform/cygwin.py b/pypy/translator/platform/cygwin.py
new file mode 100644
--- /dev/null
+++ b/pypy/translator/platform/cygwin.py
@@ -0,0 +1,56 @@
+"""Support for Cygwin."""
+
+import os
+import sys
+from pypy.translator.platform.posix import BasePosix
+
+class BaseCygwin(BasePosix):
+    name = "cygwin"
+    
+#    link_flags = tuple(
+#                 ['-pthread',]
+#                 + os.environ.get('LDFLAGS', '').split())
+    link_flags = tuple(
+                 []
+                 + os.environ.get('LDFLAGS', '').split())
+    extra_libs = ('-lrt',)
+#    cflags = tuple(
+#             ['-O3', '-pthread', '-fomit-frame-pointer',
+#              '-Wall', '-Wno-unused']
+#             + os.environ.get('CFLAGS', '').split())
+    cflags = tuple(
+             ['-O3', '-fomit-frame-pointer',
+              '-Wall', '-Wno-unused']
+             + os.environ.get('CFLAGS', '').split())
+    standalone_only = ()
+    shared_only = ('-fPIC',)
+    so_ext = 'dll'
+    exe_ext = 'exe'
+    so_prefixes = ('lib', '')
+    
+    def _args_for_shared(self, args):
+        return ['-shared'] + args
+
+    def _include_dirs_for_libffi(self):
+        return self._pkg_config("libffi", "--cflags-only-I",
+                                ['/usr/include/libffi'])
+
+    def _library_dirs_for_libffi(self):
+        return self._pkg_config("libffi", "--libs-only-L",
+                                ['/usr/lib/libffi'])
+
+    def library_dirs_for_libffi_a(self):
+        # places where we need to look for libffi.a
+        # XXX obscuuure!  only look for libffi.a if run with translate.py
+        if 'translate' in sys.modules:
+            return self.library_dirs_for_libffi() + ['/usr/lib']
+        else:
+            return []
+
+
+class Cygwin(BaseCygwin):
+    shared_only = ()    # it seems that on 32-bit linux, compiling with -fPIC
+                        # gives assembler that asmgcc is not happy about.
+
+class Cygwin64(BaseCygwin):
+    pass
diff --git a/pypy/translator/platform/posix.py b/pypy/translator/platform/posix.py
--- a/pypy/translator/platform/posix.py
+++ b/pypy/translator/platform/posix.py
@@ -1,6 +1,6 @@
 """Base support for POSIX-like platforms."""
 
-import py, os
+import py, os, sys
 
 from pypy.tool import autopath
 from pypy.translator.platform import Platform, log, _run_subprocess
@@ -55,7 +55,8 @@
 
         if relto:
             response_file = relto.bestrelpath(response_file)
-        if self.cc == 'mingw32' or (self.cc== 'gcc' and os.name=='nt'):    
+        if (self.cc == 'mingw32' or (self.cc== 'gcc' and os.name=='nt')
+                or sys.platform == 'cygwin'):
             return ["-Wl,--export-all-symbols,--version-script=%s" % \
                     (response_file,)]
         return ["-Wl,--export-dynamic,--version-script=%s" % (response_file,)]


More information about the pypy-commit mailing list