File: svn-updates.dpatch

package info (click to toggle)
python2.5 2.5.2-15%2Blenny1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 55,940 kB
  • ctags: 97,448
  • sloc: ansic: 354,616; python: 320,341; sh: 16,213; asm: 6,567; makefile: 4,281; lisp: 3,696; perl: 3,674; xml: 894; objc: 756; sed: 2
file content (3546 lines) | stat: -rw-r--r-- 125,551 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
#! /bin/sh -e

# DP: SVN updates of the release25-maint branch (until 2008-07-31).

dir=
if [ $# -eq 3 -a "$2" = '-d' ]; then
    pdir="-d $3"
    dir="$3/"
elif [ $# -ne 1 ]; then
    echo >&2 "usage: `basename $0`: -patch|-unpatch [-d <srcdir>]"
    exit 1
fi
case "$1" in
    -patch)
        patch $pdir -f --no-backup-if-mismatch -p0 < $0
        autoconf
        ;;
    -unpatch)
        patch $pdir -f --no-backup-if-mismatch -R -p0 < $0
        rm -f configure
        ;;
    *)
	echo >&2 "usage: `basename $0`: -patch|-unpatch [-d <srcdir>]"
        exit 1
esac
exit 0

# svn diff http://svn.python.org/projects/python/tags/r252 http://svn.python.org/projects/python/branches/release25-maint
# diff -urN --exclude=.svn Python-2.5 svn

Index: Python/ceval.c
===================================================================
--- Python/ceval.c	(.../tags/r252)	(Revision 65324)
+++ Python/ceval.c	(.../branches/release25-maint)	(Revision 65324)
@@ -1603,9 +1603,11 @@
 							"lost sys.stdout");
 			}
 			if (w != NULL) {
+				Py_INCREF(w);
 				err = PyFile_WriteString("\n", w);
 				if (err == 0)
 					PyFile_SoftSpace(w, 0);
+				Py_DECREF(w);
 			}
 			Py_XDECREF(stream);
 			stream = NULL;
Index: Python/ast.c
===================================================================
--- Python/ast.c	(.../tags/r252)	(Revision 65324)
+++ Python/ast.c	(.../branches/release25-maint)	(Revision 65324)
@@ -249,6 +249,8 @@
 		    goto error;
                 asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
                                             arena));
+                if (!asdl_seq_GET(stmts, 0))
+                    goto error;
                 return Interactive(stmts, arena);
             }
             else {
@@ -679,6 +681,8 @@
 		    if (NCH(ch) != 1) {
 			/* We have complex arguments, setup for unpacking. */
 			asdl_seq_SET(args, k++, compiler_complex_args(c, ch));
+			if (!asdl_seq_GET(args, k-1))
+			    goto error;
 		    } else {
 			/* def foo((x)): setup for checking NAME below. */
 			/* Loop because there can be many parens and tuple
@@ -1878,10 +1882,14 @@
 	}
 	else if (TYPE(ch) == STAR) {
 	    vararg = ast_for_expr(c, CHILD(n, i+1));
+	    if (!vararg)
+	        return NULL;
 	    i++;
 	}
 	else if (TYPE(ch) == DOUBLESTAR) {
 	    kwarg = ast_for_expr(c, CHILD(n, i+1));
+	    if (!kwarg)
+	        return NULL;
 	    i++;
 	}
     }
@@ -3059,16 +3067,7 @@
 #endif
 	if (*end == 'l' || *end == 'L')
 		return PyLong_FromString((char *)s, (char **)0, 0);
-	if (s[0] == '0') {
-		x = (long) PyOS_strtoul((char *)s, (char **)&end, 0);
- 		if (x < 0 && errno == 0) {
-	 			return PyLong_FromString((char *)s,
-							 (char **)0,
-							 0);
-		}
-	}
-	else
-		x = PyOS_strtol((char *)s, (char **)&end, 0);
+	x = PyOS_strtol((char *)s, (char **)&end, 0);
 	if (*end == '\0') {
 		if (errno != 0)
 			return PyLong_FromString((char *)s, (char **)0, 0);
Index: Python/mysnprintf.c
===================================================================
--- Python/mysnprintf.c	(.../tags/r252)	(Revision 65324)
+++ Python/mysnprintf.c	(.../branches/release25-maint)	(Revision 65324)
@@ -54,18 +54,28 @@
 PyOS_vsnprintf(char *str, size_t size, const char  *format, va_list va)
 {
 	int len;  /* # bytes written, excluding \0 */
-#ifndef HAVE_SNPRINTF
+#ifdef HAVE_SNPRINTF
+#define _PyOS_vsnprintf_EXTRA_SPACE 1
+#else
+#define _PyOS_vsnprintf_EXTRA_SPACE 512
 	char *buffer;
 #endif
 	assert(str != NULL);
 	assert(size > 0);
 	assert(format != NULL);
+	/* We take a size_t as input but return an int.  Sanity check
+	 * our input so that it won't cause an overflow in the
+         * vsnprintf return value or the buffer malloc size.  */
+	if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) {
+		len = -666;
+		goto Done;
+	}
 
 #ifdef HAVE_SNPRINTF
 	len = vsnprintf(str, size, format, va);
 #else
 	/* Emulate it. */
-	buffer = PyMem_MALLOC(size + 512);
+	buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE);
 	if (buffer == NULL) {
 		len = -666;
 		goto Done;
@@ -75,7 +85,7 @@
 	if (len < 0)
 		/* ignore the error */;
 
-	else if ((size_t)len >= size + 512)
+	else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE)
 		Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
 
 	else {
@@ -86,8 +96,10 @@
 		str[to_copy] = '\0';
 	}
 	PyMem_FREE(buffer);
+#endif
 Done:
-#endif
-	str[size-1] = '\0';
+	if (size > 0)
+		str[size-1] = '\0';
 	return len;
+#undef _PyOS_vsnprintf_EXTRA_SPACE
 }
Index: Python/marshal.c
===================================================================
--- Python/marshal.c	(.../tags/r252)	(Revision 65324)
+++ Python/marshal.c	(.../branches/release25-maint)	(Revision 65324)
@@ -65,7 +65,10 @@
 	if (p->str == NULL)
 		return; /* An error already occurred */
 	size = PyString_Size(p->str);
-	newsize = size + 1024;
+	newsize = size + size + 1024;
+	if (newsize > 32*1024*1024) {
+		newsize = size + (size >> 3);	/* 12.5% overallocation */
+	}
 	if (_PyString_Resize(&p->str, newsize) != 0) {
 		p->ptr = p->end = NULL;
 	}
Index: Python/compile.c
===================================================================
--- Python/compile.c	(.../tags/r252)	(Revision 65324)
+++ Python/compile.c	(.../branches/release25-maint)	(Revision 65324)
@@ -2061,6 +2061,7 @@
 	if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
 				  s->lineno))
 		return 0;
+	Py_XDECREF(c->u->u_private);
 	c->u->u_private = s->v.ClassDef.name;
 	Py_INCREF(c->u->u_private);
 	str = PyString_InternFromString("__name__");
Index: Include/pymem.h
===================================================================
--- Include/pymem.h	(.../tags/r252)	(Revision 65324)
+++ Include/pymem.h	(.../branches/release25-maint)	(Revision 65324)
@@ -67,8 +67,12 @@
    for malloc(0), which would be treated as an error. Some platforms
    would return a pointer with no memory behind it, which would break
    pymalloc. To solve these problems, allocate an extra byte. */
-#define PyMem_MALLOC(n)         malloc((n) ? (n) : 1)
-#define PyMem_REALLOC(p, n)     realloc((p), (n) ? (n) : 1)
+/* Returns NULL to indicate error if a negative size or size larger than
+   Py_ssize_t can represent is supplied.  Helps prevents security holes. */
+#define PyMem_MALLOC(n)		(((n) < 0 || (n) > PY_SSIZE_T_MAX) ? NULL \
+				: malloc((n) ? (n) : 1))
+#define PyMem_REALLOC(p, n)	(((n) < 0 || (n) > PY_SSIZE_T_MAX) ? NULL \
+				: realloc((p), (n) ? (n) : 1))
 #define PyMem_FREE		free
 
 #endif	/* PYMALLOC_DEBUG */
@@ -77,24 +81,31 @@
  * Type-oriented memory interface
  * ==============================
  *
- * These are carried along for historical reasons.  There's rarely a good
- * reason to use them anymore (you can just as easily do the multiply and
- * cast yourself).
+ * Allocate memory for n objects of the given type.  Returns a new pointer
+ * or NULL if the request was too large or memory allocation failed.  Use
+ * these macros rather than doing the multiplication yourself so that proper
+ * overflow checking is always done.
  */
 
 #define PyMem_New(type, n) \
-  ( assert((n) <= PY_SIZE_MAX / sizeof(type)) , \
+  ( ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
 	( (type *) PyMem_Malloc((n) * sizeof(type)) ) )
 #define PyMem_NEW(type, n) \
-  ( assert((n) <= PY_SIZE_MAX / sizeof(type)) , \
+  ( ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
 	( (type *) PyMem_MALLOC((n) * sizeof(type)) ) )
 
+/*
+ * The value of (p) is always clobbered by this macro regardless of success.
+ * The caller MUST check if (p) is NULL afterwards and deal with the memory
+ * error if so.  This means the original value of (p) MUST be saved for the
+ * caller's memory error handler to not lose track of it.
+ */
 #define PyMem_Resize(p, type, n) \
-  ( assert((n) <= PY_SIZE_MAX / sizeof(type)) , \
-	( (p) = (type *) PyMem_Realloc((p), (n) * sizeof(type)) ) )
+  ( (p) = ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+	(type *) PyMem_Realloc((p), (n) * sizeof(type)) )
 #define PyMem_RESIZE(p, type, n) \
-  ( assert((n) <= PY_SIZE_MAX / sizeof(type)) , \
-	( (p) = (type *) PyMem_REALLOC((p), (n) * sizeof(type)) ) )
+  ( (p) = ((n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \
+	(type *) PyMem_REALLOC((p), (n) * sizeof(type)) )
 
 /* PyMem{Del,DEL} are left over from ancient days, and shouldn't be used
  * anymore.  They're just confusing aliases for PyMem_{Free,FREE} now.
Index: Objects/object.c
===================================================================
--- Objects/object.c	(.../tags/r252)	(Revision 65324)
+++ Objects/object.c	(.../branches/release25-maint)	(Revision 65324)
@@ -403,7 +403,12 @@
 	if (v->ob_type->tp_str == NULL)
 		return PyObject_Repr(v);
 
+	/* It is possible for a type to have a tp_str representation that loops
+	   infinitely. */
+	if (Py_EnterRecursiveCall(" while getting the str of an object"))
+		return NULL;
 	res = (*v->ob_type->tp_str)(v);
+	Py_LeaveRecursiveCall();
 	if (res == NULL)
 		return NULL;
 	type_ok = PyString_Check(res);
@@ -2141,4 +2146,3 @@
 #ifdef __cplusplus
 }
 #endif
-
Index: Objects/weakrefobject.c
===================================================================
--- Objects/weakrefobject.c	(.../tags/r252)	(Revision 65324)
+++ Objects/weakrefobject.c	(.../branches/release25-maint)	(Revision 65324)
@@ -900,7 +900,8 @@
             current->wr_callback = NULL;
             clear_weakref(current);
             if (callback != NULL) {
-                handle_callback(current, callback);
+                if (current->ob_refcnt > 0)
+                    handle_callback(current, callback);
                 Py_DECREF(callback);
             }
         }
@@ -918,9 +919,15 @@
             for (i = 0; i < count; ++i) {
                 PyWeakReference *next = current->wr_next;
 
-                Py_INCREF(current);
-                PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
-                PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
+                if (current->ob_refcnt > 0)
+                {
+                    Py_INCREF(current);
+                    PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
+                    PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
+                }
+                else {
+                    Py_DECREF(current->wr_callback);
+                }
                 current->wr_callback = NULL;
                 clear_weakref(current);
                 current = next;
@@ -928,6 +935,7 @@
             for (i = 0; i < count; ++i) {
                 PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);
 
+                /* The tuple may have slots left to NULL */
                 if (callback != NULL) {
                     PyObject *item = PyTuple_GET_ITEM(tuple, i * 2);
                     handle_callback((PyWeakReference *)item, callback);
Index: Objects/unicodeobject.c
===================================================================
--- Objects/unicodeobject.c	(.../tags/r252)	(Revision 65324)
+++ Objects/unicodeobject.c	(.../branches/release25-maint)	(Revision 65324)
@@ -200,7 +200,8 @@
        it contains). */
 
     oldstr = unicode->str;
-    PyMem_RESIZE(unicode->str, Py_UNICODE, length + 1);
+    unicode->str = PyObject_REALLOC(unicode->str,
+				    sizeof(Py_UNICODE) * (length + 1));
     if (!unicode->str) {
 	unicode->str = (Py_UNICODE *)oldstr;
         PyErr_NoMemory();
@@ -249,20 +250,23 @@
 	       never downsize it. */
 	    if ((unicode->length < length) &&
                 unicode_resize(unicode, length) < 0) {
-		PyMem_DEL(unicode->str);
+		PyObject_DEL(unicode->str);
 		goto onError;
 	    }
 	}
         else {
-	    unicode->str = PyMem_NEW(Py_UNICODE, length + 1);
+	    size_t new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
+	    unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
         }
         PyObject_INIT(unicode, &PyUnicode_Type);
     }
     else {
+	size_t new_size;
         unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
         if (unicode == NULL)
             return NULL;
-	unicode->str = PyMem_NEW(Py_UNICODE, length + 1);
+	new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
+	unicode->str = (Py_UNICODE*) PyObject_MALLOC(new_size);
     }
 
     if (!unicode->str) {
@@ -296,7 +300,7 @@
 	unicode_freelist_size < MAX_UNICODE_FREELIST_SIZE) {
         /* Keep-Alive optimization */
 	if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
-	    PyMem_DEL(unicode->str);
+	    PyObject_DEL(unicode->str);
 	    unicode->str = NULL;
 	    unicode->length = 0;
 	}
@@ -310,7 +314,7 @@
         unicode_freelist_size++;
     }
     else {
-	PyMem_DEL(unicode->str);
+	PyObject_DEL(unicode->str);
 	Py_XDECREF(unicode->defenc);
 	unicode->ob_type->tp_free((PyObject *)unicode);
     }
@@ -970,7 +974,7 @@
     while (s < e) {
         Py_UNICODE ch;
         restart:
-        ch = *s;
+        ch = (unsigned char) *s;
 
         if (inShift) {
             if ((ch == '-') || !B64CHAR(ch)) {
@@ -2269,8 +2273,22 @@
 	    else
 		x += 10 + c - 'A';
 	}
-#ifndef Py_UNICODE_WIDE
-        if (x > 0x10000) {
+        if (x <= 0xffff)
+                /* UCS-2 character */
+                *p++ = (Py_UNICODE) x;
+        else if (x <= 0x10ffff) {
+                /* UCS-4 character. Either store directly, or as
+                   surrogate pair. */
+#ifdef Py_UNICODE_WIDE
+                *p++ = (Py_UNICODE) x;
+#else
+                x -= 0x10000L;
+                *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
+                *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
+#endif
+        } else {
+            endinpos = s-starts;
+            outpos = p-PyUnicode_AS_UNICODE(v);
             if (unicode_decode_call_errorhandler(
                     errors, &errorHandler,
                     "rawunicodeescape", "\\Uxxxxxxxx out of range",
@@ -2278,8 +2296,6 @@
 		    (PyObject **)&v, &outpos, &p))
 		    goto onError;
         }
-#endif
-	*p++ = x;
 	nextByte:
 	;
     }
@@ -2333,6 +2349,32 @@
             *p++ = hexdigit[ch & 15];
         }
         else
+#else
+	/* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+	if (ch >= 0xD800 && ch < 0xDC00) {
+	    Py_UNICODE ch2;
+	    Py_UCS4 ucs;
+
+	    ch2 = *s++;
+	    size--;
+	    if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+		ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+		*p++ = '\\';
+		*p++ = 'U';
+		*p++ = hexdigit[(ucs >> 28) & 0xf];
+		*p++ = hexdigit[(ucs >> 24) & 0xf];
+		*p++ = hexdigit[(ucs >> 20) & 0xf];
+		*p++ = hexdigit[(ucs >> 16) & 0xf];
+		*p++ = hexdigit[(ucs >> 12) & 0xf];
+		*p++ = hexdigit[(ucs >> 8) & 0xf];
+		*p++ = hexdigit[(ucs >> 4) & 0xf];
+		*p++ = hexdigit[ucs & 0xf];
+		continue;
+	    }
+	    /* Fall through: isolated surrogates are copied as-is */
+	    s--;
+	    size++;
+	}
 #endif
 	/* Map 16-bit characters to '\uxxxx' */
 	if (ch >= 256) {
@@ -5689,7 +5731,8 @@
     Py_UNICODE *e;
     Py_UNICODE *p;
     Py_UNICODE *q;
-    Py_ssize_t i, j, old_j;
+    Py_UNICODE *qe;
+    Py_ssize_t i, j, incr;
     PyUnicodeObject *u;
     int tabsize = 8;
 
@@ -5697,63 +5740,70 @@
 	return NULL;
 
     /* First pass: determine size of output string */
-    i = j = old_j = 0;
-    e = self->str + self->length;
+    i = 0; /* chars up to and including most recent \n or \r */
+    j = 0; /* chars since most recent \n or \r (use in tab calculations) */
+    e = self->str + self->length; /* end of input */
     for (p = self->str; p < e; p++)
         if (*p == '\t') {
 	    if (tabsize > 0) {
-		j += tabsize - (j % tabsize);
-		if (old_j > j) {
-		    PyErr_SetString(PyExc_OverflowError,
-				    "new string is too long");
-		    return NULL;
-		}
-		old_j = j;
-	    }
+		incr = tabsize - (j % tabsize); /* cannot overflow */
+		if (j > PY_SSIZE_T_MAX - incr)
+		    goto overflow1;
+		j += incr;
+            }
 	}
         else {
+	    if (j > PY_SSIZE_T_MAX - 1)
+		goto overflow1;
             j++;
             if (*p == '\n' || *p == '\r') {
+		if (i > PY_SSIZE_T_MAX - j)
+		    goto overflow1;
                 i += j;
-                old_j = j = 0;
-                if (i < 0) {
-                    PyErr_SetString(PyExc_OverflowError,
-                                    "new string is too long");
-                    return NULL;
-                }
+                j = 0;
             }
         }
 
-    if ((i + j) < 0) {
-        PyErr_SetString(PyExc_OverflowError, "new string is too long");
-        return NULL;
-    }
+    if (i > PY_SSIZE_T_MAX - j)
+	goto overflow1;
 
     /* Second pass: create output string and fill it */
     u = _PyUnicode_New(i + j);
     if (!u)
         return NULL;
 
-    j = 0;
-    q = u->str;
+    j = 0; /* same as in first pass */
+    q = u->str; /* next output char */
+    qe = u->str + u->length; /* end of output */
 
     for (p = self->str; p < e; p++)
         if (*p == '\t') {
 	    if (tabsize > 0) {
 		i = tabsize - (j % tabsize);
 		j += i;
-		while (i--)
+		while (i--) {
+		    if (q >= qe)
+			goto overflow2;
 		    *q++ = ' ';
+                }
 	    }
 	}
 	else {
+	    if (q >= qe)
+		goto overflow2;
+	    *q++ = *p;
             j++;
-	    *q++ = *p;
             if (*p == '\n' || *p == '\r')
                 j = 0;
         }
 
     return (PyObject*) u;
+
+  overflow2:
+    Py_DECREF(u);
+  overflow1:
+    PyErr_SetString(PyExc_OverflowError, "new string is too long");
+    return NULL;
 }
 
 PyDoc_STRVAR(find__doc__,
@@ -7121,8 +7171,8 @@
             return PyUnicode_FromUnicode(NULL, 0);
         } else {
             source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
-            result_buf = (Py_UNICODE *)PyMem_MALLOC(slicelength*
-                                                    sizeof(Py_UNICODE));
+            result_buf = (Py_UNICODE *)PyObject_MALLOC(slicelength*
+                                                       sizeof(Py_UNICODE));
 	    
 	    if (result_buf == NULL)
 		    return PyErr_NoMemory();
@@ -7132,7 +7182,7 @@
             }
 
             result = PyUnicode_FromUnicode(result_buf, slicelength);
-            PyMem_FREE(result_buf);
+            PyObject_FREE(result_buf);
             return result;
         }
     } else {
@@ -7940,7 +7990,7 @@
 		Py_DECREF(tmp);
 		return NULL;
 	}
-	pnew->str = PyMem_NEW(Py_UNICODE, n+1);
+	pnew->str = (Py_UNICODE*) PyObject_MALLOC(sizeof(Py_UNICODE) * (n+1));
 	if (pnew->str == NULL) {
 		_Py_ForgetReference((PyObject *)pnew);
 		PyObject_Del(pnew);
@@ -8067,7 +8117,7 @@
 	PyUnicodeObject *v = u;
 	u = *(PyUnicodeObject **)u;
 	if (v->str)
-	    PyMem_DEL(v->str);
+	    PyObject_DEL(v->str);
 	Py_XDECREF(v->defenc);
 	PyObject_Del(v);
     }
Index: Objects/tupleobject.c
===================================================================
--- Objects/tupleobject.c	(.../tags/r252)	(Revision 65324)
+++ Objects/tupleobject.c	(.../branches/release25-maint)	(Revision 65324)
@@ -212,13 +212,25 @@
 	if (n == 0)
 		return PyString_FromString("()");
 
+	/* While not mutable, it is still possible to end up with a cycle in a
+	   tuple through an object that stores itself within a tuple (and thus
+	   infinitely asks for the repr of itself). This should only be
+	   possible within a type. */
+	i = Py_ReprEnter((PyObject *)v);
+	if (i != 0) {
+		return i > 0 ? PyString_FromString("(...)") : NULL;
+	}
+
 	pieces = PyTuple_New(n);
 	if (pieces == NULL)
 		return NULL;
 
 	/* Do repr() on each element. */
 	for (i = 0; i < n; ++i) {
+		if (Py_EnterRecursiveCall(" while getting the repr of a tuple"))
+			goto Done;
 		s = PyObject_Repr(v->ob_item[i]);
+		Py_LeaveRecursiveCall();
 		if (s == NULL)
 			goto Done;
 		PyTuple_SET_ITEM(pieces, i, s);
@@ -253,6 +265,7 @@
 
 Done:
 	Py_DECREF(pieces);
+	Py_ReprLeave((PyObject *)v);
 	return result;
 }
 
Index: Objects/fileobject.c
===================================================================
--- Objects/fileobject.c	(.../tags/r252)	(Revision 65324)
+++ Objects/fileobject.c	(.../branches/release25-maint)	(Revision 65324)
@@ -256,9 +256,12 @@
 		else if (errno == EINVAL) /* unknown, but not a mode string */
 			errno = ENOENT;
 #endif
+                /* EINVAL is returned when an invalid filename or
+                 * an invalid mode is supplied. */
 		if (errno == EINVAL)
-			PyErr_Format(PyExc_IOError, "invalid mode: %s",
-				     mode);
+			PyErr_Format(PyExc_IOError,
+                                     "invalid filename: %s or mode: %s",
+				     name, mode);
 		else
 			PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
 		f = NULL;
Index: Objects/obmalloc.c
===================================================================
--- Objects/obmalloc.c	(.../tags/r252)	(Revision 65324)
+++ Objects/obmalloc.c	(.../branches/release25-maint)	(Revision 65324)
@@ -727,6 +727,15 @@
 	uint size;
 
 	/*
+	 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
+	 * Most python internals blindly use a signed Py_ssize_t to track
+	 * things without checking for overflows or negatives.
+	 * As size_t is unsigned, checking for nbytes < 0 is not required.
+	 */
+	if (nbytes > PY_SSIZE_T_MAX)
+		return NULL;
+
+	/*
 	 * This implicitly redirects malloc(0).
 	 */
 	if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
@@ -1130,6 +1139,15 @@
 	if (p == NULL)
 		return PyObject_Malloc(nbytes);
 
+	/*
+	 * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
+	 * Most python internals blindly use a signed Py_ssize_t to track
+	 * things without checking for overflows or negatives.
+	 * As size_t is unsigned, checking for nbytes < 0 is not required.
+	 */
+	if (nbytes > PY_SSIZE_T_MAX)
+		return NULL;
+
 	pool = POOL_ADDR(p);
 	if (Py_ADDRESS_IN_RANGE(p, pool)) {
 		/* We're in charge of this block */
Index: Objects/stringobject.c
===================================================================
--- Objects/stringobject.c	(.../tags/r252)	(Revision 65324)
+++ Objects/stringobject.c	(.../branches/release25-maint)	(Revision 65324)
@@ -53,7 +53,11 @@
 PyString_FromStringAndSize(const char *str, Py_ssize_t size)
 {
 	register PyStringObject *op;
-	assert(size >= 0);
+	if (size < 0) {
+		PyErr_SetString(PyExc_SystemError,
+		    "Negative size passed to PyString_FromStringAndSize");
+		return NULL;
+	}
 	if (size == 0 && (op = nullstring) != NULL) {
 #ifdef COUNT_ALLOCS
 		null_strings++;
@@ -3299,9 +3303,9 @@
 static PyObject*
 string_expandtabs(PyStringObject *self, PyObject *args)
 {
-    const char *e, *p;
+    const char *e, *p, *qe;
     char *q;
-    Py_ssize_t i, j, old_j;
+    Py_ssize_t i, j, incr;
     PyObject *u;
     int tabsize = 8;
 
@@ -3309,63 +3313,70 @@
 	return NULL;
 
     /* First pass: determine size of output string */
-    i = j = old_j = 0;
-    e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
+    i = 0; /* chars up to and including most recent \n or \r */
+    j = 0; /* chars since most recent \n or \r (use in tab calculations) */
+    e = PyString_AS_STRING(self) + PyString_GET_SIZE(self); /* end of input */
     for (p = PyString_AS_STRING(self); p < e; p++)
         if (*p == '\t') {
 	    if (tabsize > 0) {
-		j += tabsize - (j % tabsize);
-		if (old_j > j) {
-		    PyErr_SetString(PyExc_OverflowError,
-				    "new string is too long");
-		    return NULL;
-		}
-		old_j = j;
+		incr = tabsize - (j % tabsize);
+		if (j > PY_SSIZE_T_MAX - incr)
+		    goto overflow1;
+		j += incr;
             }
 	}
         else {
+	    if (j > PY_SSIZE_T_MAX - 1)
+		goto overflow1;
             j++;
             if (*p == '\n' || *p == '\r') {
+		if (i > PY_SSIZE_T_MAX - j)
+		    goto overflow1;
                 i += j;
-                old_j = j = 0;
-                if (i < 0) {
-                    PyErr_SetString(PyExc_OverflowError,
-                                    "new string is too long");
-                    return NULL;
-                }
+                j = 0;
             }
         }
 
-    if ((i + j) < 0) {
-        PyErr_SetString(PyExc_OverflowError, "new string is too long");
-        return NULL;
-    }
+    if (i > PY_SSIZE_T_MAX - j)
+	goto overflow1;
 
     /* Second pass: create output string and fill it */
     u = PyString_FromStringAndSize(NULL, i + j);
     if (!u)
         return NULL;
 
-    j = 0;
-    q = PyString_AS_STRING(u);
+    j = 0; /* same as in first pass */
+    q = PyString_AS_STRING(u); /* next output char */
+    qe = PyString_AS_STRING(u) + PyString_GET_SIZE(u); /* end of output */
 
     for (p = PyString_AS_STRING(self); p < e; p++)
         if (*p == '\t') {
 	    if (tabsize > 0) {
 		i = tabsize - (j % tabsize);
 		j += i;
-		while (i--)
+		while (i--) {
+		    if (q >= qe)
+			goto overflow2;
 		    *q++ = ' ';
+		}
 	    }
 	}
 	else {
+	    if (q >= qe)
+		goto overflow2;
+	    *q++ = *p;
             j++;
-	    *q++ = *p;
             if (*p == '\n' || *p == '\r')
                 j = 0;
         }
 
     return u;
+
+  overflow2:
+    Py_DECREF(u);
+  overflow1:
+    PyErr_SetString(PyExc_OverflowError, "new string is too long");
+    return NULL;
 }
 
 Py_LOCAL_INLINE(PyObject *)
Index: Misc/ACKS
===================================================================
--- Misc/ACKS	(.../tags/r252)	(Revision 65324)
+++ Misc/ACKS	(.../branches/release25-maint)	(Revision 65324)
@@ -266,6 +266,7 @@
 Rycharde Hawkes
 Jochen Hayek
 Thomas Heller
+Malte Helmert
 Lance Finn Helsten
 Jonathan Hendry
 James Henstridge
Index: Misc/NEWS
===================================================================
--- Misc/NEWS	(.../tags/r252)	(Revision 65324)
+++ Misc/NEWS	(.../branches/release25-maint)	(Revision 65324)
@@ -4,9 +4,157 @@
 
 (editors: check NEWS.help for information about editing NEWS using ReST.)
 
-What's New in Python 2.5.2?
+What's New in Python 2.5.3?
 =============================
 
+*Release date: XX-XXX-20XX*
+
+Core and builtins
+-----------------
+
+- Issue #2620: Overflow checking when allocating or reallocating memory
+  was not always being done properly in some python types and extension
+  modules.  PyMem_MALLOC, PyMem_REALLOC, PyMem_NEW and PyMem_RESIZE have
+  all been updated to perform better checks and places in the code that
+  would previously leak memory on the error path when such an allocation
+  failed have been fixed.
+
+- Issue #2242: Fix a crash when decoding invalid utf-7 input on certain
+  Windows / Visual Studio versions.
+
+- Issue #3360: Fix incorrect parsing of '020000000000.0', which
+  produced a ValueError instead of giving the correct float.
+
+- Issue #3242: Fix a crash inside the print statement, if sys.stdout is
+  set to a custom object whose write() method happens to install
+  another file in sys.stdout.
+
+- Issue #3088: Corrected a race condition in classes derived from
+  threading.local: the first member set by a thread could be saved in
+  another thread's dictionary.
+
+- Issue #3100: Corrected a crash on deallocation of a subclassed weakref which
+  holds the last (strong) reference to its referent.
+
+- Issue #1686386: Tuple's tp_repr did not take into account the possibility of
+  having a self-referential tuple, which is possible from C code.  Nor did
+  object's tp_str consider that a type's tp_str could do something that could
+  lead to an inifinite recursion.  Py_ReprEnter() and Py_EnterRecursiveCall(),
+  respectively, fixed the issues.  (Backport of r58288 from trunk.)
+
+- Patch #1442: properly report exceptions when the PYTHONSTARTUP file
+  cannot be executed.
+
+- The compilation of a class nested in another class used to leak one
+  reference on the outer class name.
+
+- Issue #1477: With narrow Unicode builds, the unicode escape sequence
+  \Uxxxxxxxx did not accept values outside the Basic Multilingual Plane.  This
+  affected raw unicode literals and the 'raw-unicode-escape' codec.  Now
+  UTF-16 surrogates are generated in this case, like normal unicode literals
+  and the 'unicode-escape' codec.
+
+- Issue #2321: use pymalloc for unicode object string data to reduce
+  memory usage in some circumstances.
+
+- Issue #2238: Some syntax errors in *args and **kwargs expressions could give
+  bogus error messages.
+
+- Issue #2587: In the C API, PyString_FromStringAndSize() takes a signed size
+  parameter but was not verifying that it was greater than zero.  Values
+  less than zero will now raise a SystemError and return NULL to indicate a
+  bug in the calling C code.
+
+- Issue #2588, #2589: Fix potential integer underflow and overflow
+  conditions in the PyOS_vsnprintf C API function.
+
+
+Library
+-------
+
+- Issue #3339: dummy_thread.acquire() could return None which is not a valid
+  return value.
+
+- Issue #3116 and #1792:  Fix quadratic behavior in marshal.dumps().
+
+- Issue #2682: ctypes callback functions no longer contain a cyclic
+  reference to themselves.
+
+- Issue #2670:  Fix a failure in urllib2.build_opener(), when passed two
+  handlers that derive the same default base class.
+
+- Issue #2495: tokenize.untokenize now inserts a space between two consecutive
+  string literals; previously, ["" ""] was rendered as [""""], which is
+  incorrect python code.
+
+- Issue #2482: Make sure that the coefficient of a Decimal is always
+  stored as a str instance, not as a unicode instance.  This ensures
+  that str(Decimal) is always an instance of str.  This fixes a
+  regression from Python 2.5.1 to Python 2.5.2.
+
+- Issue #2478: fix failure of decimal.Decimal(0).sqrt()
+
+- Issue #2432: give DictReader the dialect and line_num attributes
+  advertised in the docs.
+
+- Issue #1747858: Fix chown to work with large uid's and gid's on 64-bit
+  platforms.
+
+- Bug #2220: handle rlcompleter attribute match failure more gracefully.
+
+- Bug #1725737: In distutil's sdist, exclude RCS, CVS etc. also in the
+  root directory, and also exclude .hg, .git, .bzr, and _darcs.
+
+- Bug #1389051: imaplib causes excessive memory fragmentation when reading
+  large messages.
+
+- Bug #1389051, 1092502: fix excessively large memory allocations when
+  calling .read() on a socket object wrapped with makefile().
+
+- Bug #1433694: minidom's .normalize() failed to set .nextSibling for
+  last child element.
+
+- Issue #2791: subprocess.Popen.communicate explicitly closes its
+  stdout and stderr fds rather than leaving them open until the
+  instance is destroyed.
+
+- Issue #2632: Prevent socket.read(bignumber) from over allocating memory
+  in the common case when the data is returned from the underlying socket
+  in increments much smaller than bignumber.
+
+Extension Modules
+-----------------
+
+- Patch #2111: Avoid mmap segfault when modifying a PROT_READ block.
+
+- zlib.decompressobj().flush(value) no longer crashes the interpreter when
+  passed a value less than or equal to zero.
+
+- issue2858: Fix potential memory corruption when bsddb.db.DBEnv.lock_get
+  and other bsddb.db object constructors raised an exception.
+
+Tests
+-----
+
+- Issue #3261: test_cookielib had an improper file encoding specified.
+
+- Patch #2232: os.tmpfile might fail on Windows if the user has no
+  permission to create files in the root directory.
+
+
+Documentation
+-------------
+
+Build
+-----
+
+Windows
+-------
+
+
+What's New in Python 2.5.2?
+===========================
+
 *Release date: 21-Feb-2008*
 
 Extension Modules
@@ -35,7 +183,7 @@
   collections.defaultdict, if its default_factory is set to a bound method.
 
 - Issue #1920: "while 0" statements were completely removed by the compiler,
-  even in the presence of an "else" clause, which is supposed to be run when 
+  even in the presence of an "else" clause, which is supposed to be run when
   the condition is false. Now the compiler correctly emits bytecode for the
   "else" suite.
 
@@ -69,7 +217,7 @@
   PY_SSIZE_T_CLEAN is set.  The str.decode method used to return incorrect
   results with huge strings.
 
-- Issue #1445: Fix a SystemError when accessing the ``cell_contents`` 
+- Issue #1445: Fix a SystemError when accessing the ``cell_contents``
   attribute of an empty cell object.
 
 - Issue #1265: Fix a problem with sys.settrace, if the tracing function uses a
@@ -102,6 +250,9 @@
 Library
 -------
 
+- curses.textpad: Fix off-by-one error that resulted in characters
+  being missed from the contents of a Textbox.
+
 - Patch #1966: Break infinite loop in httplib when the servers
   implements the chunked encoding incorrectly.
 
@@ -245,7 +396,7 @@
 - Issue1385: The hmac module now computes the correct hmac when using hashes
   with a block size other than 64 bytes (such as sha384 and sha512).
 
-- Issue829951: In the smtplib module, SMTP.starttls() now complies with 
+- Issue829951: In the smtplib module, SMTP.starttls() now complies with
   RFC 3207 and forgets any knowledge obtained from the server not obtained
   from the TLS negotiation itself.  Patch contributed by Bill Fenner.
 
@@ -265,7 +416,7 @@
 - Bug #1301: Bad assert in _tkinter fixed.
 
 - Patch #1114: fix curses module compilation on 64-bit AIX, & possibly
-  other 64-bit LP64 platforms where attr_t is not the same size as a long.  
+  other 64-bit LP64 platforms where attr_t is not the same size as a long.
   (Contributed by Luke Mewburn.)
 
 - Bug #1649098: Avoid declaration of zero-sized array declaration in
@@ -328,7 +479,7 @@
 
 - Define _BSD_SOURCE, to get access to POSIX extensions on OpenBSD 4.1+.
 
-- Patch #1673122: Use an explicit path to libtool when building a framework. 
+- Patch #1673122: Use an explicit path to libtool when building a framework.
   This avoids picking up GNU libtool from a users PATH.
 
 - Allow Emacs 22 for building the documentation in info format.
@@ -402,7 +553,7 @@
   a weakref on itself during a __del__ call for new-style classes (classic
   classes still have the bug).
 
-- Bug #1648179:  set.update() did not recognize an overridden __iter__ 
+- Bug #1648179:  set.update() did not recognize an overridden __iter__
   method in subclasses of dict.
 
 - Bug #1579370: Make PyTraceBack_Here use the current thread, not the
@@ -537,7 +688,7 @@
 - Bug #1563807: _ctypes built on AIX fails with ld ffi error.
 
 - Bug #1598620: A ctypes Structure cannot contain itself.
- 
+
 - Bug #1588217: don't parse "= " as a soft line break in binascii's
   a2b_qp() function, instead leave it in the string as quopri.decode()
   does.
@@ -649,7 +800,7 @@
   on "linux" and "gnu" systems.
 
 - Bug #1124861: Automatically create pipes if GetStdHandle fails in
-  subprocess. 
+  subprocess.
 
 - Patch #783050: the pty.fork() function now closes the slave fd
   correctly.
@@ -660,7 +811,7 @@
 
 - Bug #1643943: Fix %U handling for time.strptime.
 
-- Bug #1598181: Avoid O(N**2) bottleneck in subprocess communicate(). 
+- Bug #1598181: Avoid O(N**2) bottleneck in subprocess communicate().
 
 - Patch #1627441: close sockets properly in urllib2.
 
@@ -724,7 +875,7 @@
 - Bug #1446043: correctly raise a LookupError if an encoding name given
   to encodings.search_function() contains a dot.
 
-- Bug #1545341: The 'classifier' keyword argument to the Distutils setup() 
+- Bug #1545341: The 'classifier' keyword argument to the Distutils setup()
   function now accepts tuples as well as lists.
 
 - Bug #1560617: in pyclbr, return full module name not only for classes,
@@ -743,7 +894,7 @@
 - Bug #1575506: mailbox.py: Single-file mailboxes didn't re-lock
   properly in their flush() method.
 
-- Patch #1514543: mailbox.py: In the Maildir class, report errors if there's 
+- Patch #1514543: mailbox.py: In the Maildir class, report errors if there's
   a filename clash instead of possibly losing a message.  (Patch by David
   Watson.)
 
@@ -755,7 +906,7 @@
   wasn't consistent with existing implementations of message packing, and
   was buggy on some platforms.
 
-- Bug #1633678: change old mailbox.UnixMailbox class to parse 
+- Bug #1633678: change old mailbox.UnixMailbox class to parse
   'From' lines less strictly.
 
 - Bug #1576241: fix functools.wraps() to work on built-in functions.
Index: Mac/PythonLauncher/doscript.m
===================================================================
--- Mac/PythonLauncher/doscript.m	(.../tags/r252)	(Revision 65324)
+++ Mac/PythonLauncher/doscript.m	(.../branches/release25-maint)	(Revision 65324)
@@ -11,108 +11,49 @@
 #import <ApplicationServices/ApplicationServices.h>
 #import "doscript.h"
 
-/* I assume I could pick these up from somewhere, but where... */
-#define CREATOR 'trmx'
-
-#define ACTIVATE_CMD 'misc'
-#define ACTIVATE_SUITE 'actv'
-
-#define DOSCRIPT_CMD 'dosc'
-#define DOSCRIPT_SUITE 'core'
-#define WITHCOMMAND 'cmnd'
-
-/* ... and there's probably also a better way to do this... */
-#define START_TERMINAL "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal &"
-
 extern int 
 doscript(const char *command)
 {
-    OSErr err;
-    AppleEvent theAEvent, theReply;
-    AEAddressDesc terminalAddress;
-    AEDesc commandDesc;
-    OSType terminalCreator = CREATOR;
-    
-    /* set up locals  */
-    AECreateDesc(typeNull, NULL, 0, &theAEvent);
-    AECreateDesc(typeNull, NULL, 0, &terminalAddress);
-    AECreateDesc(typeNull, NULL, 0, &theReply);
-    AECreateDesc(typeNull, NULL, 0, &commandDesc);
-    
-    /* create the "activate" event for Terminal */
-    err = AECreateDesc(typeApplSignature, (Ptr) &terminalCreator,
-            sizeof(terminalCreator), &terminalAddress);
-    if (err != noErr) {
-        NSLog(@"doscript: AECreateDesc: error %d\n", err);
-        goto bail;
-    }
-    err = AECreateAppleEvent(ACTIVATE_SUITE, ACTIVATE_CMD,
-            &terminalAddress, kAutoGenerateReturnID,
-            kAnyTransactionID, &theAEvent);
-    
-    if (err != noErr) {
-        NSLog(@"doscript: AECreateAppleEvent(activate): error %d\n", err);
-        goto bail;
-    }
-    /* send the event  */
-    err = AESend(&theAEvent, &theReply, kAEWaitReply,
-            kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
-    if ( err == -600 ) {
-        int count=10;
-        /* If it failed with "no such process" try to start Terminal */
-        err = system(START_TERMINAL);
-        if ( err ) {
-            NSLog(@"doscript: system(): %s\n", strerror(errno));
-            goto bail;
-        }
-        do {
-            sleep(1);
-            /* send the event again */
-            err = AESend(&theAEvent, &theReply, kAEWaitReply,
-                    kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
-        } while (err == -600 && --count > 0);
-        if ( err == -600 )
-            NSLog(@"doscript: Could not activate Terminal\n");
-    }
-    if (err != noErr) {
-        NSLog(@"doscript: AESend(activate): error %d\n", err);
-        goto bail;
-    }
-            
-    /* create the "doscript with command" event for Terminal */
-    err = AECreateAppleEvent(DOSCRIPT_SUITE, DOSCRIPT_CMD,
-            &terminalAddress, kAutoGenerateReturnID,
-            kAnyTransactionID, &theAEvent);
-    if (err != noErr) {
-        NSLog(@"doscript: AECreateAppleEvent(doscript): error %d\n", err);
-        goto bail;
-    }
-    
-    /* add the command to the apple event */
-    err = AECreateDesc(typeChar, command, strlen(command), &commandDesc);
-    if (err != noErr) {
-        NSLog(@"doscript: AECreateDesc(command): error %d\n", err);
-        goto bail;
-    }
-    err = AEPutParamDesc(&theAEvent, WITHCOMMAND, &commandDesc);
-    if (err != noErr) {
-        NSLog(@"doscript: AEPutParamDesc: error %d\n", err);
-        goto bail;
-    }
+	char *bundleID = "com.apple.Terminal";
+	AppleEvent evt, res;
+	AEDesc desc;
+	OSStatus err;
 
-    /* send the command event to Terminal.app */
-    err = AESend(&theAEvent, &theReply, kAEWaitReply,
-            kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
-    
-    if (err != noErr) {
-        NSLog(@"doscript: AESend(docommand): error %d\n", err);
-        goto bail;
-    }
-    /* clean up and leave */
-bail:
-    AEDisposeDesc(&commandDesc);
-    AEDisposeDesc(&theAEvent);
-    AEDisposeDesc(&terminalAddress);
-    AEDisposeDesc(&theReply);
-    return err;
+	[[NSWorkspace sharedWorkspace] launchApplication:@"/Applications/Utilities/Terminal.app/"];
+
+	// Build event
+	err = AEBuildAppleEvent(kAECoreSuite, kAEDoScript,
+	                         typeApplicationBundleID,
+	                         bundleID, strlen(bundleID),
+	                         kAutoGenerateReturnID,
+	                         kAnyTransactionID,
+	                         &evt, NULL,
+	                         "'----':utf8(@)", strlen(command),
+	                         command);
+	if (err) {
+		NSLog(@"AEBuildAppleEvent failed: %d\n", err);
+		return err;
+	}
+
+	// Send event and check for any Apple Event Manager errors
+	err = AESendMessage(&evt, &res, kAEWaitReply, kAEDefaultTimeout);
+	AEDisposeDesc(&evt);
+	if (err) {
+		NSLog(@"AESendMessage failed: %d\n", err);
+		return err;
+	}
+	// Check for any application errors
+	err = AEGetParamDesc(&res, keyErrorNumber, typeSInt32, &desc);
+	AEDisposeDesc(&res);
+	if (!err) {
+		AEGetDescData(&desc, &err, sizeof(err));
+		NSLog(@"Terminal returned an error: %d", err);
+		AEDisposeDesc(&desc);
+	} else if (err == errAEDescNotFound) {
+		err = noErr;
+	} else {
+		NSLog(@"AEGetPArmDesc returned an error: %d", err);
+	}
+
+	return err;
 }
Index: Tools/msi/msi.py
===================================================================
--- Tools/msi/msi.py	(.../tags/r252)	(Revision 65324)
+++ Tools/msi/msi.py	(.../branches/release25-maint)	(Revision 65324)
@@ -853,6 +853,26 @@
     return installer.FileVersion("msvcr71.dll", 0), \
            installer.FileVersion("msvcr71.dll", 1)
 
+def generate_license():
+    import shutil, glob
+    out = open("LICENSE.txt", "w")
+    shutil.copyfileobj(open(os.path.join(srcdir, "LICENSE")), out)
+    for dir, file in (("bzip2","LICENSE"),
+                      ("db", "LICENSE"),
+                      ("openssl", "LICENSE"),
+                      ("tcl", "license.terms"),
+                      ("tk", "license.terms")):
+        out.write("\nThis copy of Python includes a copy of %s, which is licensed under the following terms:\n\n" % dir)
+        dirs = glob.glob(srcdir+"/../"+dir+"-*")
+        if not dirs:
+            raise ValueError, "Could not find "+srcdir+"/../"+dir+"-*"
+        if len(dirs) > 2:
+            raise ValueError, "Multiple copies of "+dir
+        dir = dirs[0]
+        shutil.copyfileobj(open(os.path.join(dir, file)), out)
+    out.close()
+
+
 class PyDirectory(Directory):
     """By default, all components in the Python installer
     can run from source."""
@@ -873,7 +893,8 @@
         root.add_file("PCBuild/w9xpopen.exe")
     root.add_file("README.txt", src="README")
     root.add_file("NEWS.txt", src="Misc/NEWS")
-    root.add_file("LICENSE.txt", src="LICENSE")
+    generate_license()
+    root.add_file("LICENSE.txt", src=os.path.abspath("LICENSE.txt"))
     root.start_component("python.exe", keyfile="python.exe")
     root.add_file("PCBuild/python.exe")
     root.start_component("pythonw.exe", keyfile="pythonw.exe")
Index: Lib/rlcompleter.py
===================================================================
--- Lib/rlcompleter.py	(.../tags/r252)	(Revision 65324)
+++ Lib/rlcompleter.py	(.../branches/release25-maint)	(Revision 65324)
@@ -125,7 +125,7 @@
         import re
         m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
         if not m:
-            return
+            return []
         expr, attr = m.group(1, 3)
         object = eval(expr, self.namespace)
         words = dir(object)
Index: Lib/idlelib/configHandler.py
===================================================================
--- Lib/idlelib/configHandler.py	(.../tags/r252)	(Revision 65324)
+++ Lib/idlelib/configHandler.py	(.../branches/release25-maint)	(Revision 65324)
@@ -207,7 +207,10 @@
             if not os.path.exists(userDir):
                 warn = ('\n Warning: os.path.expanduser("~") points to\n '+
                         userDir+',\n but the path does not exist.\n')
-                sys.stderr.write(warn)
+                try:
+                    sys.stderr.write(warn)
+                except IOError:
+                    pass
                 userDir = '~'
         if userDir == "~": # still no path to home!
             # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
@@ -248,7 +251,10 @@
                            ' from section %r.\n'
                            ' returning default value: %r\n' %
                            (option, section, default))
-                sys.stderr.write(warning)
+                try:
+                    sys.stderr.write(warning)
+                except IOError:
+                    pass
             return default
 
     def SetOption(self, configType, section, option, value):
@@ -357,7 +363,10 @@
                            '\n from theme %r.\n'
                            ' returning default value: %r\n' %
                            (element, themeName, theme[element]))
-                sys.stderr.write(warning)
+                try:
+                    sys.stderr.write(warning)
+                except IOError:
+                    pass
             colour=cfgParser.Get(themeName,element,default=theme[element])
             theme[element]=colour
         return theme
@@ -611,7 +620,10 @@
                                '\n from key set %r.\n'
                                ' returning default value: %r\n' %
                                (event, keySetName, keyBindings[event]))
-                    sys.stderr.write(warning)
+                    try:
+                        sys.stderr.write(warning)
+                    except IOError:
+                        pass
         return keyBindings
 
     def GetExtraHelpSourceList(self,configSet):
Index: Lib/idlelib/NEWS.txt
===================================================================
--- Lib/idlelib/NEWS.txt	(.../tags/r252)	(Revision 65324)
+++ Lib/idlelib/NEWS.txt	(.../branches/release25-maint)	(Revision 65324)
@@ -1,3 +1,12 @@
+What's New in IDLE 1.2.3c1?
+===========================
+
+*Release date: XX-XXX-2008*
+
+- Issue #2665: On Windows, an IDLE installation upgraded from an old version
+  would not start if a custom theme was defined.
+
+
 What's New in IDLE 1.2.2?
 =========================
 
Index: Lib/os.py
===================================================================
--- Lib/os.py	(.../tags/r252)	(Revision 65324)
+++ Lib/os.py	(.../branches/release25-maint)	(Revision 65324)
@@ -263,8 +263,9 @@
 
     Example:
 
+    import os
     from os.path import join, getsize
-    for root, dirs, files in walk('python/Lib/email'):
+    for root, dirs, files in os.walk('python/Lib/email'):
         print root, "consumes",
         print sum([getsize(join(root, name)) for name in files]),
         print "bytes in", len(files), "non-directory files"
Index: Lib/imaplib.py
===================================================================
--- Lib/imaplib.py	(.../tags/r252)	(Revision 65324)
+++ Lib/imaplib.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1147,7 +1147,7 @@
         chunks = []
         read = 0
         while read < size:
-            data = self.sslobj.read(size-read)
+            data = self.sslobj.read(min(size-read, 16384))
             read += len(data)
             chunks.append(data)
 
Index: Lib/tokenize.py
===================================================================
--- Lib/tokenize.py	(.../tags/r252)	(Revision 65324)
+++ Lib/tokenize.py	(.../branches/release25-maint)	(Revision 65324)
@@ -171,11 +171,12 @@
         t1 = [tok[:2] for tok in generate_tokens(f.readline)]
         newcode = untokenize(t1)
         readline = iter(newcode.splitlines(1)).next
-        t2 = [tok[:2] for tokin generate_tokens(readline)]
+        t2 = [tok[:2] for tok in generate_tokens(readline)]
         assert t1 == t2
     """
 
     startline = False
+    prevstring = False
     indents = []
     toks = []
     toks_append = toks.append
@@ -185,6 +186,14 @@
         if toknum in (NAME, NUMBER):
             tokval += ' '
 
+        # Insert a space between two consecutive strings
+        if toknum == STRING:
+            if prevstring:
+                tokval = ' ' + tokval
+            prevstring = True
+        else:
+            prevstring = False
+
         if toknum == INDENT:
             indents.append(tokval)
             continue
Index: Lib/distutils/command/sdist.py
===================================================================
--- Lib/distutils/command/sdist.py	(.../tags/r252)	(Revision 65324)
+++ Lib/distutils/command/sdist.py	(.../branches/release25-maint)	(Revision 65324)
@@ -347,14 +347,14 @@
           * the build tree (typically "build")
           * the release tree itself (only an issue if we ran "sdist"
             previously with --keep-temp, or it aborted)
-          * any RCS, CVS and .svn directories
+          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
         """
         build = self.get_finalized_command('build')
         base_dir = self.distribution.get_fullname()
 
         self.filelist.exclude_pattern(None, prefix=build.build_base)
         self.filelist.exclude_pattern(None, prefix=base_dir)
-        self.filelist.exclude_pattern(r'/(RCS|CVS|\.svn)/.*', is_regex=1)
+        self.filelist.exclude_pattern(r'(^|/)(RCS|CVS|\.svn|\.hg|\.git|\.bzr|_darcs)/.*', is_regex=1)
 
 
     def write_manifest (self):
Index: Lib/socket.py
===================================================================
--- Lib/socket.py	(.../tags/r252)	(Revision 65324)
+++ Lib/socket.py	(.../branches/release25-maint)	(Revision 65324)
@@ -56,6 +56,11 @@
 import os, sys
 
 try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
+
+try:
     from errno import EBADF
 except ImportError:
     EBADF = 9
@@ -211,6 +216,9 @@
             bufsize = self.default_bufsize
         self.bufsize = bufsize
         self.softspace = False
+        # _rbufsize is the suggested recv buffer size.  It is *strictly*
+        # obeyed within readline() for recv calls.  If it is larger than
+        # default_bufsize it will be used for recv calls within read().
         if bufsize == 0:
             self._rbufsize = 1
         elif bufsize == 1:
@@ -218,7 +226,11 @@
         else:
             self._rbufsize = bufsize
         self._wbufsize = bufsize
-        self._rbuf = "" # A string
+        # We use StringIO for the read buffer to avoid holding a list
+        # of variously sized string objects which have been known to
+        # fragment the heap due to how they are malloc()ed and often
+        # realloc()ed down much smaller than their original allocation.
+        self._rbuf = StringIO()
         self._wbuf = [] # A list of strings
         self._close = close
 
@@ -276,56 +288,85 @@
         return buf_len
 
     def read(self, size=-1):
-        data = self._rbuf
+        # Use max, disallow tiny reads in a loop as they are very inefficient.
+        # We never leave read() with any leftover data from a new recv() call
+        # in our internal buffer.
+        rbufsize = max(self._rbufsize, self.default_bufsize)
+        # Our use of StringIO rather than lists of string objects returned by
+        # recv() minimizes memory usage and fragmentation that occurs when
+        # rbufsize is large compared to the typical return value of recv().
+        buf = self._rbuf
+        buf.seek(0, 2)  # seek end
         if size < 0:
             # Read until EOF
-            buffers = []
-            if data:
-                buffers.append(data)
-            self._rbuf = ""
-            if self._rbufsize <= 1:
-                recv_size = self.default_bufsize
-            else:
-                recv_size = self._rbufsize
+            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
             while True:
-                data = self._sock.recv(recv_size)
+                data = self._sock.recv(rbufsize)
                 if not data:
                     break
-                buffers.append(data)
-            return "".join(buffers)
+                buf.write(data)
+            return buf.getvalue()
         else:
             # Read until size bytes or EOF seen, whichever comes first
-            buf_len = len(data)
+            buf_len = buf.tell()
             if buf_len >= size:
-                self._rbuf = data[size:]
-                return data[:size]
-            buffers = []
-            if data:
-                buffers.append(data)
-            self._rbuf = ""
+                # Already have size bytes in our buffer?  Extract and return.
+                buf.seek(0)
+                rv = buf.read(size)
+                self._rbuf = StringIO()
+                self._rbuf.write(buf.read())
+                return rv
+
+            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
             while True:
                 left = size - buf_len
-                recv_size = max(self._rbufsize, left)
-                data = self._sock.recv(recv_size)
+                # recv() will malloc the amount of memory given as its
+                # parameter even though it often returns much less data
+                # than that.  The returned data string is short lived
+                # as we copy it into a StringIO and free it.  This avoids
+                # fragmentation issues on many platforms.
+                data = self._sock.recv(left)
                 if not data:
                     break
-                buffers.append(data)
                 n = len(data)
-                if n >= left:
-                    self._rbuf = data[left:]
-                    buffers[-1] = data[:left]
+                if n == size and not buf_len:
+                    # Shortcut.  Avoid buffer data copies when:
+                    # - We have no data in our buffer.
+                    # AND
+                    # - Our call to recv returned exactly the
+                    #   number of bytes we were asked to read.
+                    return data
+                if n == left:
+                    buf.write(data)
+                    del data  # explicit free
                     break
+                assert n <= left, "recv(%d) returned %d bytes" % (left, n)
+                buf.write(data)
                 buf_len += n
-            return "".join(buffers)
+                del data  # explicit free
+                #assert buf_len == buf.tell()
+            return buf.getvalue()
 
     def readline(self, size=-1):
-        data = self._rbuf
+        buf = self._rbuf
+        buf.seek(0, 2)  # seek end
+        if buf.tell() > 0:
+            # check if we already have it in our buffer
+            buf.seek(0)
+            bline = buf.readline(size)
+            if bline.endswith('\n') or len(bline) == size:
+                self._rbuf = StringIO()
+                self._rbuf.write(buf.read())
+                return bline
+            del bline
         if size < 0:
             # Read until \n or EOF, whichever comes first
             if self._rbufsize <= 1:
                 # Speed up unbuffered case
-                assert data == ""
-                buffers = []
+                buf.seek(0)
+                buffers = [buf.read()]
+                self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
+                data = None
                 recv = self._sock.recv
                 while data != "\n":
                     data = recv(1)
@@ -333,61 +374,64 @@
                         break
                     buffers.append(data)
                 return "".join(buffers)
-            nl = data.find('\n')
-            if nl >= 0:
-                nl += 1
-                self._rbuf = data[nl:]
-                return data[:nl]
-            buffers = []
-            if data:
-                buffers.append(data)
-            self._rbuf = ""
+
+            buf.seek(0, 2)  # seek end
+            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
             while True:
                 data = self._sock.recv(self._rbufsize)
                 if not data:
                     break
-                buffers.append(data)
                 nl = data.find('\n')
                 if nl >= 0:
                     nl += 1
-                    self._rbuf = data[nl:]
-                    buffers[-1] = data[:nl]
+                    buf.write(buffer(data, 0, nl))
+                    self._rbuf.write(buffer(data, nl))
+                    del data
                     break
-            return "".join(buffers)
+                buf.write(data)
+            return buf.getvalue()
         else:
             # Read until size bytes or \n or EOF seen, whichever comes first
-            nl = data.find('\n', 0, size)
-            if nl >= 0:
-                nl += 1
-                self._rbuf = data[nl:]
-                return data[:nl]
-            buf_len = len(data)
+            buf.seek(0, 2)  # seek end
+            buf_len = buf.tell()
             if buf_len >= size:
-                self._rbuf = data[size:]
-                return data[:size]
-            buffers = []
-            if data:
-                buffers.append(data)
-            self._rbuf = ""
+                buf.seek(0)
+                rv = buf.read(size)
+                self._rbuf = StringIO()
+                self._rbuf.write(buf.read())
+                return rv
+            self._rbuf = StringIO()  # reset _rbuf.  we consume it via buf.
             while True:
                 data = self._sock.recv(self._rbufsize)
                 if not data:
                     break
-                buffers.append(data)
                 left = size - buf_len
+                # did we just receive a newline?
                 nl = data.find('\n', 0, left)
                 if nl >= 0:
                     nl += 1
-                    self._rbuf = data[nl:]
-                    buffers[-1] = data[:nl]
-                    break
+                    # save the excess data to _rbuf
+                    self._rbuf.write(buffer(data, nl))
+                    if buf_len:
+                        buf.write(buffer(data, 0, nl))
+                        break
+                    else:
+                        # Shortcut.  Avoid data copy through buf when returning
+                        # a substring of our first recv().
+                        return data[:nl]
                 n = len(data)
+                if n == size and not buf_len:
+                    # Shortcut.  Avoid data copy through buf when
+                    # returning exactly all of our first recv().
+                    return data
                 if n >= left:
-                    self._rbuf = data[left:]
-                    buffers[-1] = data[:left]
+                    buf.write(buffer(data, 0, left))
+                    self._rbuf.write(buffer(data, left))
                     break
+                buf.write(data)
                 buf_len += n
-            return "".join(buffers)
+                #assert buf_len == buf.tell()
+            return buf.getvalue()
 
     def readlines(self, sizehint=0):
         total = 0
Index: Lib/decimal.py
===================================================================
--- Lib/decimal.py	(.../tags/r252)	(Revision 65324)
+++ Lib/decimal.py	(.../branches/release25-maint)	(Revision 65324)
@@ -549,17 +549,17 @@
                 fracpart = m.group('frac')
                 exp = int(m.group('exp') or '0')
                 if fracpart is not None:
-                    self._int = (intpart+fracpart).lstrip('0') or '0'
+                    self._int = str((intpart+fracpart).lstrip('0') or '0')
                     self._exp = exp - len(fracpart)
                 else:
-                    self._int = intpart.lstrip('0') or '0'
+                    self._int = str(intpart.lstrip('0') or '0')
                     self._exp = exp
                 self._is_special = False
             else:
                 diag = m.group('diag')
                 if diag is not None:
                     # NaN
-                    self._int = diag.lstrip('0')
+                    self._int = str(diag.lstrip('0'))
                     if m.group('signal'):
                         self._exp = 'N'
                     else:
@@ -2316,6 +2316,9 @@
 
     def sqrt(self, context=None):
         """Return the square root of self."""
+        if context is None:
+            context = getcontext()
+
         if self._is_special:
             ans = self._check_nans(context=context)
             if ans:
@@ -2329,9 +2332,6 @@
             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
             return ans._fix(context)
 
-        if context is None:
-            context = getcontext()
-
         if self._sign == 1:
             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
 
Index: Lib/logging/__init__.py
===================================================================
--- Lib/logging/__init__.py	(.../tags/r252)	(Revision 65324)
+++ Lib/logging/__init__.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1247,7 +1247,7 @@
         hdlr.setFormatter(fmt)
         root.addHandler(hdlr)
         level = kwargs.get("level")
-        if level:
+        if level is not None:
             root.setLevel(level)
 
 #---------------------------------------------------------------------------
Index: Lib/sched.py
===================================================================
--- Lib/sched.py	(.../tags/r252)	(Revision 65324)
+++ Lib/sched.py	(.../branches/release25-maint)	(Revision 65324)
@@ -114,4 +114,4 @@
                     void = action(*argument)
                     delayfunc(0)   # Let other threads run
                 else:
-                    heapq.heappush(event)
+                    heapq.heappush(q, event)
Index: Lib/csv.py
===================================================================
--- Lib/csv.py	(.../tags/r252)	(Revision 65324)
+++ Lib/csv.py	(.../branches/release25-maint)	(Revision 65324)
@@ -75,6 +75,8 @@
         self.restkey = restkey          # key to catch long rows
         self.restval = restval          # default value for short rows
         self.reader = reader(f, dialect, *args, **kwds)
+        self.dialect = dialect
+        self.line_num = 0
 
     def __iter__(self):
         return self
@@ -84,6 +86,7 @@
         if self.fieldnames is None:
             self.fieldnames = row
             row = self.reader.next()
+        self.line_num = self.reader.line_num
 
         # unlike the basic reader, we prefer not to return blanks,
         # because we will typically wind up with a dict full of None
Index: Lib/platform.py
===================================================================
--- Lib/platform.py	(.../tags/r252)	(Revision 65324)
+++ Lib/platform.py	(.../branches/release25-maint)	(Revision 65324)
@@ -591,7 +591,17 @@
         major = (sysv & 0xFF00) >> 8
         minor = (sysv & 0x00F0) >> 4
         patch = (sysv & 0x000F)
-        release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
+
+        if (major, minor) >= (10, 4):
+            # the 'sysv' gestald cannot return patchlevels
+            # higher than 9. Apple introduced 3 new
+            # gestalt codes in 10.4 to deal with this
+            # issue (needed because patch levels can
+            # run higher than 9, such as 10.4.11)
+            major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
+            release = '%i.%i.%i' %(major, minor, patch)
+        else:
+            release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
     if sysu:
         major =  int((sysu & 0xFF000000L) >> 24)
         minor =  (sysu & 0x00F00000) >> 20
Index: Lib/lib-tk/Tkinter.py
===================================================================
--- Lib/lib-tk/Tkinter.py	(.../tags/r252)	(Revision 65324)
+++ Lib/lib-tk/Tkinter.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1055,6 +1055,18 @@
                 if k[-1] == '_': k = k[:-1]
                 if callable(v):
                     v = self._register(v)
+                elif isinstance(v, (tuple, list)):
+                    nv = []
+                    for item in v:
+                        if not isinstance(item, (basestring, int)):
+                            break
+                        elif isinstance(item, int):
+                            nv.append('%d' % item)
+                        else:
+                            # format it to proper Tcl code if it contains space
+                            nv.append(('{%s}' if ' ' in item else '%s') % item)
+                    else:
+                        v = ' '.join(nv)
                 res = res + ('-'+k, v)
         return res
     def nametowidget(self, name):
@@ -1094,7 +1106,6 @@
             if self._tclCommands is None:
                 self._tclCommands = []
             self._tclCommands.append(name)
-        #print '+ Tkinter created command', name
         return name
     register = _register
     def _root(self):
@@ -1747,10 +1758,11 @@
         after=widget - pack it after you have packed widget
         anchor=NSEW (or subset) - position widget according to
                                   given direction
-                before=widget - pack it before you will pack widget
+        before=widget - pack it before you will pack widget
         expand=bool - expand widget if parent size grows
         fill=NONE or X or Y or BOTH - fill widget if widget grows
         in=master - use master to contain this widget
+        in_=master - see 'in' option description
         ipadx=amount - add internal padding in x direction
         ipady=amount - add internal padding in y direction
         padx=amount - add padding in x direction
@@ -1788,29 +1800,26 @@
     Base class to use the methods place_* in every widget."""
     def place_configure(self, cnf={}, **kw):
         """Place a widget in the parent widget. Use as options:
-        in=master - master relative to which the widget is placed.
+        in=master - master relative to which the widget is placed
+        in_=master - see 'in' option description
         x=amount - locate anchor of this widget at position x of master
         y=amount - locate anchor of this widget at position y of master
         relx=amount - locate anchor of this widget between 0.0 and 1.0
                       relative to width of master (1.0 is right edge)
-            rely=amount - locate anchor of this widget between 0.0 and 1.0
+        rely=amount - locate anchor of this widget between 0.0 and 1.0
                       relative to height of master (1.0 is bottom edge)
-            anchor=NSEW (or subset) - position anchor according to given direction
+        anchor=NSEW (or subset) - position anchor according to given direction
         width=amount - width of this widget in pixel
         height=amount - height of this widget in pixel
         relwidth=amount - width of this widget between 0.0 and 1.0
                           relative to width of master (1.0 is the same width
-                  as the master)
-            relheight=amount - height of this widget between 0.0 and 1.0
+                          as the master)
+        relheight=amount - height of this widget between 0.0 and 1.0
                            relative to height of master (1.0 is the same
-                   height as the master)
-            bordermode="inside" or "outside" - whether to take border width of master widget
-                                               into account
-            """
-        for k in ['in_']:
-            if kw.has_key(k):
-                kw[k[:-1]] = kw[k]
-                del kw[k]
+                           height as the master)
+        bordermode="inside" or "outside" - whether to take border width of
+                                           master widget into account
+        """
         self.tk.call(
               ('place', 'configure', self._w)
               + self._options(cnf, kw))
@@ -1845,6 +1854,7 @@
         column=number - use cell identified with given column (starting with 0)
         columnspan=number - this widget will span several columns
         in=master - use master to contain this widget
+        in_=master - see 'in' option description
         ipadx=amount - add internal padding in x direction
         ipady=amount - add internal padding in y direction
         padx=amount - add padding in x direction
Index: Lib/urllib2.py
===================================================================
--- Lib/urllib2.py	(.../tags/r252)	(Revision 65324)
+++ Lib/urllib2.py	(.../branches/release25-maint)	(Revision 65324)
@@ -447,14 +447,14 @@
                        FTPHandler, FileHandler, HTTPErrorProcessor]
     if hasattr(httplib, 'HTTPS'):
         default_classes.append(HTTPSHandler)
-    skip = []
+    skip = set()
     for klass in default_classes:
         for check in handlers:
             if isclass(check):
                 if issubclass(check, klass):
-                    skip.append(klass)
+                    skip.add(klass)
             elif isinstance(check, klass):
-                skip.append(klass)
+                skip.add(klass)
     for klass in skip:
         default_classes.remove(klass)
 
Index: Lib/dummy_thread.py
===================================================================
--- Lib/dummy_thread.py	(.../tags/r252)	(Revision 65324)
+++ Lib/dummy_thread.py	(.../branches/release25-maint)	(Revision 65324)
@@ -107,18 +107,15 @@
         aren't triggered and throw a little fit.
 
         """
-        if waitflag is None:
+        if waitflag is None or waitflag:
             self.locked_status = True
-            return None
-        elif not waitflag:
+            return True
+        else:
             if not self.locked_status:
                 self.locked_status = True
                 return True
             else:
                 return False
-        else:
-            self.locked_status = True
-            return True
 
     __enter__ = acquire
 
Index: Lib/subprocess.py
===================================================================
--- Lib/subprocess.py	(.../tags/r252)	(Revision 65324)
+++ Lib/subprocess.py	(.../branches/release25-maint)	(Revision 65324)
@@ -660,8 +660,10 @@
                 self.stdin.close()
             elif self.stdout:
                 stdout = self.stdout.read()
+                self.stdout.close()
             elif self.stderr:
                 stderr = self.stderr.read()
+                self.stderr.close()
             self.wait()
             return (stdout, stderr)
 
Index: Lib/test/test_csv.py
===================================================================
--- Lib/test/test_csv.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_csv.py	(.../branches/release25-maint)	(Revision 65324)
@@ -269,16 +269,18 @@
             csv.field_size_limit(limit)
 
     def test_read_linenum(self):
-        r = csv.reader(['line,1', 'line,2', 'line,3'])
-        self.assertEqual(r.line_num, 0)
-        r.next()
-        self.assertEqual(r.line_num, 1)
-        r.next()
-        self.assertEqual(r.line_num, 2)
-        r.next()
-        self.assertEqual(r.line_num, 3)
-        self.assertRaises(StopIteration, r.next)
-        self.assertEqual(r.line_num, 3)
+        for r in (csv.reader(['line,1', 'line,2', 'line,3']),
+                  csv.DictReader(['line,1', 'line,2', 'line,3'],
+                                 fieldnames=['a', 'b', 'c'])):
+            self.assertEqual(r.line_num, 0)
+            r.next()
+            self.assertEqual(r.line_num, 1)
+            r.next()
+            self.assertEqual(r.line_num, 2)
+            r.next()
+            self.assertEqual(r.line_num, 3)
+            self.assertRaises(StopIteration, r.next)
+            self.assertEqual(r.line_num, 3)
 
 class TestDialectRegistry(unittest.TestCase):
     def test_registry_badargs(self):
Index: Lib/test/test_winsound.py
===================================================================
--- Lib/test/test_winsound.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_winsound.py	(.../branches/release25-maint)	(Revision 65324)
@@ -8,6 +8,13 @@
 
 
 class BeepTest(unittest.TestCase):
+    # As with PlaySoundTest, incorporate the _have_soundcard() check
+    # into our test methods.  If there's no audio device present,
+    # winsound.Beep returns 0 and GetLastError() returns 127, which
+    # is: ERROR_PROC_NOT_FOUND ("The specified procedure could not
+    # be found").  (FWIW, virtual/Hyper-V systems fall under this
+    # scenario as they have no sound devices whatsoever  (not even
+    # a legacy Beep device).)
 
     def test_errors(self):
         self.assertRaises(TypeError, winsound.Beep)
@@ -15,12 +22,25 @@
         self.assertRaises(ValueError, winsound.Beep, 32768, 75)
 
     def test_extremes(self):
-        winsound.Beep(37, 75)
-        winsound.Beep(32767, 75)
+        if _have_soundcard():
+            winsound.Beep(37, 75)
+            winsound.Beep(32767, 75)
+        else:
+            # The behaviour of winsound.Beep() seems to differ between
+            # different versions of Windows when there's either a) no
+            # sound card entirely, b) legacy beep driver has been disabled,
+            # or c) the legacy beep driver has been uninstalled.  Sometimes
+            # RuntimeErrors are raised, sometimes they're not.  Meh.
+            try:
+                winsound.Beep(37, 75)
+                winsound.Beep(32767, 75)
+            except RuntimeError:
+                pass
 
     def test_increasingfrequency(self):
-        for i in xrange(100, 2000, 100):
-            winsound.Beep(i, 75)
+        if _have_soundcard():
+            for i in xrange(100, 2000, 100):
+                winsound.Beep(i, 75)
 
 class MessageBeepTest(unittest.TestCase):
 
Index: Lib/test/tokenize_tests.txt
===================================================================
--- Lib/test/tokenize_tests.txt	(.../tags/r252)	(Revision 65324)
+++ Lib/test/tokenize_tests.txt	(.../branches/release25-maint)	(Revision 65324)
@@ -176,3 +176,5 @@
 @staticmethod
 def foo(): pass
 
+# Issue 2495
+x = '' ''
Index: Lib/test/test_itertools.py
===================================================================
--- Lib/test/test_itertools.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_itertools.py	(.../branches/release25-maint)	(Revision 65324)
@@ -449,6 +449,13 @@
         a = []
         self.makecycle(groupby([a]*2, lambda x:x), a)
 
+    def test_issue2246(self):
+        # Issue 2246 -- the _grouper iterator was not included in GC
+        n = 10
+        keyfunc = lambda x: x
+        for i, j in groupby(xrange(n), key=keyfunc):
+            keyfunc.__dict__.setdefault('x',[]).append(j)
+
     def test_ifilter(self):
         a = []
         self.makecycle(ifilter(lambda x:True, [a]*2), a)
Index: Lib/test/test_unicode.py
===================================================================
--- Lib/test/test_unicode.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_unicode.py	(.../branches/release25-maint)	(Revision 65324)
@@ -532,6 +532,9 @@
 
         self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd')
 
+        # Issue #2242: crash on some Windows/MSVC versions
+        self.assertRaises(UnicodeDecodeError, '+\xc1'.decode, 'utf-7')
+
     def test_codecs_utf8(self):
         self.assertEqual(u''.encode('utf-8'), '')
         self.assertEqual(u'\u20ac'.encode('utf-8'), '\xe2\x82\xac')
@@ -736,12 +739,25 @@
         print >>out, u'def\n'
 
     def test_ucs4(self):
-        if sys.maxunicode == 0xFFFF:
-            return
         x = u'\U00100000'
         y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
         self.assertEqual(x, y)
 
+        y = r'\U00100000'
+        x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
+        self.assertEqual(x, y)
+        y = r'\U00010000'
+        x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
+        self.assertEqual(x, y)
+
+        try:
+            '\U11111111'.decode("raw-unicode-escape")
+        except UnicodeDecodeError, e:
+            self.assertEqual(e.start, 0)
+            self.assertEqual(e.end, 10)
+        else:
+            self.fail("Should have raised UnicodeDecodeError")
+
     def test_conversion(self):
         # Make sure __unicode__() works properly
         class Foo0:
Index: Lib/test/test_resource.py
===================================================================
--- Lib/test/test_resource.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_resource.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1,71 +1,110 @@
-import os
+import unittest
+from test import test_support
+
 import resource
+import time
 
-from test.test_support import TESTFN, unlink
+# This test is checking a few specific problem spots with the resource module.
 
-# This test is checking a few specific problem spots.  RLIMIT_FSIZE
-# should be RLIM_INFINITY, which will be a really big number on a
-# platform with large file support.  On these platforms, we need to
-# test that the get/setrlimit functions properly convert the number to
-# a C long long and that the conversion doesn't raise an error.
+class ResourceTest(unittest.TestCase):
 
-try:
-    cur, max = resource.getrlimit(resource.RLIMIT_FSIZE)
-except AttributeError:
-    pass
-else:
-    print resource.RLIM_INFINITY == max
-    resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+    def test_args(self):
+        self.assertRaises(TypeError, resource.getrlimit)
+        self.assertRaises(TypeError, resource.getrlimit, 42, 42)
+        self.assertRaises(TypeError, resource.setrlimit)
+        self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42)
 
-# Now check to see what happens when the RLIMIT_FSIZE is small.  Some
-# versions of Python were terminated by an uncaught SIGXFSZ, but
-# pythonrun.c has been fixed to ignore that exception.  If so, the
-# write() should return EFBIG when the limit is exceeded.
+    def test_fsize_ismax(self):
+        try:
+            (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+        except AttributeError:
+            pass
+        else:
+            # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big
+            # number on a platform with large file support.  On these platforms,
+            # we need to test that the get/setrlimit functions properly convert
+            # the number to a C long long and that the conversion doesn't raise
+            # an error.
+            self.assertEqual(resource.RLIM_INFINITY, max)
+            resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
 
-# At least one platform has an unlimited RLIMIT_FSIZE and attempts to
-# change it raise ValueError instead.
+    def test_fsize_enforced(self):
+        try:
+            (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+        except AttributeError:
+            pass
+        else:
+            # Check to see what happens when the RLIMIT_FSIZE is small.  Some
+            # versions of Python were terminated by an uncaught SIGXFSZ, but
+            # pythonrun.c has been fixed to ignore that exception.  If so, the
+            # write() should return EFBIG when the limit is exceeded.
 
-try:
-    try:
-        resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max))
-        limit_set = 1
-    except ValueError:
-        limit_set = 0
-    f = open(TESTFN, "wb")
-    try:
-        f.write("X" * 1024)
+            # At least one platform has an unlimited RLIMIT_FSIZE and attempts
+            # to change it raise ValueError instead.
+            try:
+                try:
+                    resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max))
+                    limit_set = True
+                except ValueError:
+                    limit_set = False
+                f = open(test_support.TESTFN, "wb")
+                try:
+                    f.write("X" * 1024)
+                    try:
+                        f.write("Y")
+                        f.flush()
+                        # On some systems (e.g., Ubuntu on hppa) the flush()
+                        # doesn't always cause the exception, but the close()
+                        # does eventually.  Try flushing several times in
+                        # an attempt to ensure the file is really synced and
+                        # the exception raised.
+                        for i in range(5):
+                            time.sleep(.1)
+                            f.flush()
+                    except IOError:
+                        if not limit_set:
+                            raise
+                    if limit_set:
+                        # Close will attempt to flush the byte we wrote
+                        # Restore limit first to avoid getting a spurious error
+                        resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+                finally:
+                    f.close()
+            finally:
+                if limit_set:
+                    resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+                test_support.unlink(test_support.TESTFN)
+
+    def test_fsize_toobig(self):
+        # Be sure that setrlimit is checking for really large values
+        too_big = 10L**50
         try:
-            f.write("Y")
-            f.flush()
-            # On some systems (e.g., Ubuntu on hppa) the flush()
-            # doesn't always cause the exception, but the close()
-            # does eventually.  Try flushing several times in
-            # an attempt to ensure the file is really synced and
-            # the exception raised.
-            for i in range(5):
-                time.sleep(.1)
-                f.flush()
-        except IOError:
-            if not limit_set:
-                raise
-        if limit_set:
-            # Close will attempt to flush the byte we wrote
-            # Restore limit first to avoid getting a spurious error
-            resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
-    finally:
-        f.close()
-finally:
-    if limit_set:
-        resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
-    unlink(TESTFN)
+            (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+        except AttributeError:
+            pass
+        else:
+            try:
+                resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max))
+            except (OverflowError, ValueError):
+                pass
+            try:
+                resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big))
+            except (OverflowError, ValueError):
+                pass
 
-# And be sure that setrlimit is checking for really large values
-too_big = 10L**50
-try:
-    resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max))
-except (OverflowError, ValueError):
-    pass
-try:
-    resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big))
-except (OverflowError, ValueError):
-    pass
+    def test_getrusage(self):
+        self.assertRaises(TypeError, resource.getrusage)
+        self.assertRaises(TypeError, resource.getrusage, 42, 42)
+        usageself = resource.getrusage(resource.RUSAGE_SELF)
+        usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN)
+        # May not be available on all systems.
+        try:
+            usageboth = resource.getrusage(resource.RUSAGE_BOTH)
+        except (ValueError, AttributeError):
+            pass
+
+def test_main(verbose=None):
+    test_support.run_unittest(ResourceTest)
+
+if __name__ == "__main__":
+    test_main()
Index: Lib/test/test_socket.py
===================================================================
--- Lib/test/test_socket.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_socket.py	(.../branches/release25-maint)	(Revision 65324)
@@ -762,6 +762,33 @@
         self.cli_file.write(MSG)
         self.cli_file.flush()
 
+    def testReadlineAfterRead(self):
+        a_baloo_is = self.serv_file.read(len("A baloo is"))
+        self.assertEqual("A baloo is", a_baloo_is)
+        _a_bear = self.serv_file.read(len(" a bear"))
+        self.assertEqual(" a bear", _a_bear)
+        line = self.serv_file.readline()
+        self.assertEqual("\n", line)
+        line = self.serv_file.readline()
+        self.assertEqual("A BALOO IS A BEAR.\n", line)
+        line = self.serv_file.readline()
+        self.assertEqual(MSG, line)
+
+    def _testReadlineAfterRead(self):
+        self.cli_file.write("A baloo is a bear\n")
+        self.cli_file.write("A BALOO IS A BEAR.\n")
+        self.cli_file.write(MSG)
+        self.cli_file.flush()
+
+    def testReadlineAfterReadNoNewline(self):
+        end_of_ = self.serv_file.read(len("End Of "))
+        self.assertEqual("End Of ", end_of_)
+        line = self.serv_file.readline()
+        self.assertEqual("Line", line)
+
+    def _testReadlineAfterReadNoNewline(self):
+        self.cli_file.write("End Of Line")
+
     def testClosedAttr(self):
         self.assert_(not self.serv_file.closed)
 
Index: Lib/test/test_file.py
===================================================================
--- Lib/test/test_file.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_file.py	(.../branches/release25-maint)	(Revision 65324)
@@ -323,11 +323,30 @@
             os.unlink(TESTFN)
 
 
+class StdoutTests(unittest.TestCase):
+
+    def test_move_stdout_on_write(self):
+        # Issue 3242: sys.stdout can be replaced (and freed) during a
+        # print statement; prevent a segfault in this case
+        save_stdout = sys.stdout
+
+        class File:
+            def write(self, data):
+                if '\n' in data:
+                    sys.stdout = save_stdout
+
+        try:
+            sys.stdout = File()
+            print "some text"
+        finally:
+            sys.stdout = save_stdout
+
+
 def test_main():
     # Historically, these tests have been sloppy about removing TESTFN.
     # So get rid of it no matter what.
     try:
-        run_unittest(AutoFileTests, OtherFileTests)
+        run_unittest(AutoFileTests, OtherFileTests, StdoutTests)
     finally:
         if os.path.exists(TESTFN):
             os.unlink(TESTFN)
Index: Lib/test/output/test_resource
===================================================================
--- Lib/test/output/test_resource	(.../tags/r252)	(Revision 65324)
+++ Lib/test/output/test_resource	(.../branches/release25-maint)	(Revision 65324)
@@ -1,2 +0,0 @@
-test_resource
-True
Index: Lib/test/output/test_tokenize
===================================================================
--- Lib/test/output/test_tokenize	(.../tags/r252)	(Revision 65324)
+++ Lib/test/output/test_tokenize	(.../branches/release25-maint)	(Revision 65324)
@@ -656,4 +656,10 @@
 177,11-177,15:	NAME	'pass'
 177,15-177,16:	NEWLINE	'\n'
 178,0-178,1:	NL	'\n'
-179,0-179,0:	ENDMARKER	''
+179,0-179,13:	COMMENT	'# Issue 2495\n'
+180,0-180,1:	NAME	'x'
+180,2-180,3:	OP	'='
+180,4-180,6:	STRING	"''"
+180,7-180,9:	STRING	"''"
+180,9-180,10:	NEWLINE	'\n'
+181,0-181,0:	ENDMARKER	''
Index: Lib/test/test_os.py
===================================================================
--- Lib/test/test_os.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_os.py	(.../branches/release25-maint)	(Revision 65324)
@@ -59,6 +59,44 @@
     def test_tmpfile(self):
         if not hasattr(os, "tmpfile"):
             return
+        # As with test_tmpnam() below, the Windows implementation of tmpfile()
+        # attempts to create a file in the root directory of the current drive.
+        # On Vista and Server 2008, this test will always fail for normal users
+        # as writing to the root directory requires elevated privileges.  With
+        # XP and below, the semantics of tmpfile() are the same, but the user
+        # running the test is more likely to have administrative privileges on
+        # their account already.  If that's the case, then os.tmpfile() should
+        # work.  In order to make this test as useful as possible, rather than
+        # trying to detect Windows versions or whether or not the user has the
+        # right permissions, just try and create a file in the root directory
+        # and see if it raises a 'Permission denied' OSError.  If it does, then
+        # test that a subsequent call to os.tmpfile() raises the same error. If
+        # it doesn't, assume we're on XP or below and the user running the test
+        # has administrative privileges, and proceed with the test as normal.
+        if sys.platform == 'win32':
+            name = '\\python_test_os_test_tmpfile.txt'
+            if os.path.exists(name):
+                os.remove(name)
+            try:
+                fp = open(name, 'w')
+            except IOError, first:
+                # open() failed, assert tmpfile() fails in the same way.
+                # Although open() raises an IOError and os.tmpfile() raises an
+                # OSError(), 'args' will be (13, 'Permission denied') in both
+                # cases.
+                try:
+                    fp = os.tmpfile()
+                except OSError, second:
+                    self.assertEqual(first.args, second.args)
+                else:
+                    self.fail("expected os.tmpfile() to raise OSError")
+                return
+            else:
+                # open() worked, therefore, tmpfile() should work.  Close our
+                # dummy file and proceed with the test as normal.
+                fp.close()
+                os.remove(name)
+
         fp = os.tmpfile()
         fp.write("foobar")
         fp.seek(0,0)
Index: Lib/test/test_compile.py
===================================================================
--- Lib/test/test_compile.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_compile.py	(.../branches/release25-maint)	(Revision 65324)
@@ -209,6 +209,10 @@
         self.assertEqual(eval("000000000000007"), 7)
         self.assertEqual(eval("000000000000008."), 8.)
         self.assertEqual(eval("000000000000009."), 9.)
+        self.assertEqual(eval("020000000000.0"), 20000000000.0)
+        self.assertEqual(eval("037777777777e0"), 37777777777.0)
+        self.assertEqual(eval("01000000000000000000000.0"),
+                         1000000000000000000000.0)
 
     def test_unary_minus(self):
         # Verify treatment of unary minus on negative numbers SF bug #660455
@@ -398,6 +402,10 @@
         del d[..., ...]
         self.assertEqual((Ellipsis, Ellipsis) in d, False)
 
+    def test_nested_classes(self):
+        # Verify that it does not leak
+        compile("class A:\n    class B: pass", 'tmp', 'exec')
+
 def test_main():
     test_support.run_unittest(TestSpecifics)
 
Index: Lib/test/test_zlib.py
===================================================================
--- Lib/test/test_zlib.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_zlib.py	(.../branches/release25-maint)	(Revision 65324)
@@ -71,8 +71,13 @@
         # verify failure on building decompress object with bad params
         self.assertRaises(ValueError, zlib.decompressobj, 0)
 
+    def test_decompressobj_badflush(self):
+        # verify failure on calling decompressobj.flush with bad params
+        self.assertRaises(ValueError, zlib.decompressobj().flush, 0)
+        self.assertRaises(ValueError, zlib.decompressobj().flush, -1)
 
 
+
 class CompressTestCase(unittest.TestCase):
     # Test compression in one go (whole message compression)
     def test_speech(self):
Index: Lib/test/test_mmap.py
===================================================================
--- Lib/test/test_mmap.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_mmap.py	(.../branches/release25-maint)	(Revision 65324)
@@ -380,6 +380,23 @@
     finally:
         os.unlink(TESTFN)
 
+    # Test that setting access to PROT_READ gives exception
+    # rather than crashing
+    if hasattr(mmap, "PROT_READ"):
+        try:
+            mapsize = 10
+            open(TESTFN, "wb").write("a"*mapsize)
+            f = open(TESTFN, "rb")
+            m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
+            try:
+                m.write("foo")
+            except TypeError:
+                pass
+            else:
+                verify(0, "PROT_READ is not working")
+        finally:
+            os.unlink(TESTFN)
+
 def test_anon():
     print "  anonymous mmap.mmap(-1, PAGESIZE)..."
     m = mmap.mmap(-1, PAGESIZE)
Index: Lib/test/test_minidom.py
===================================================================
--- Lib/test/test_minidom.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_minidom.py	(.../branches/release25-maint)	(Revision 65324)
@@ -806,6 +806,14 @@
             "testNormalize -- single empty node removed")
     doc.unlink()
 
+def testBug1433694():
+    doc = parseString("<o><i/>t</o>")
+    node = doc.documentElement
+    node.childNodes[1].nodeValue = ""
+    node.normalize()
+    confirm(node.childNodes[-1].nextSibling == None,
+            "Final child's .nextSibling should be None")
+
 def testSiblings():
     doc = parseString("<doc><?pi?>text?<elm/></doc>")
     root = doc.documentElement
Index: Lib/test/test_cookielib.py
===================================================================
--- Lib/test/test_cookielib.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_cookielib.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1,4 +1,4 @@
-# -*- coding: utf-8 -*-
+# -*- coding: latin-1 -*-
 """Tests for cookielib.py."""
 
 import re, os, time
Index: Lib/test/test_dummy_thread.py
===================================================================
--- Lib/test/test_dummy_thread.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_dummy_thread.py	(.../branches/release25-maint)	(Revision 65324)
@@ -60,6 +60,7 @@
         #Make sure that an unconditional locking returns True.
         self.failUnless(self.lock.acquire(1) is True,
                         "Unconditional locking did not return True.")
+        self.failUnless(self.lock.acquire() is True)
 
     def test_uncond_acquire_blocking(self):
         #Make sure that unconditional acquiring of a locked lock blocks.
Index: Lib/test/test_grammar.py
===================================================================
--- Lib/test/test_grammar.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_grammar.py	(.../branches/release25-maint)	(Revision 65324)
@@ -260,6 +260,10 @@
 def d32v((x,)): pass
 d32v((1,))
 
+# Check ast errors in *args and *kwargs
+check_syntax("f(*g(1=2))")
+check_syntax("f(**g(1=2))")
+
 ### lambdef: 'lambda' [varargslist] ':' test
 print 'lambdef'
 l1 = lambda : 0
@@ -273,6 +277,7 @@
 verify(l5(1, 2) == 5)
 verify(l5(1, 2, 3) == 6)
 check_syntax("lambda x: x = 2")
+check_syntax("lambda (None,): None")
 
 ### stmt: simple_stmt | compound_stmt
 # Tested below
Index: Lib/test/test_decimal.py
===================================================================
--- Lib/test/test_decimal.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_decimal.py	(.../branches/release25-maint)	(Revision 65324)
@@ -429,6 +429,12 @@
         #just not a number
         self.assertEqual(str(Decimal('ugly')), 'NaN')
 
+        #unicode strings should be permitted
+        self.assertEqual(str(Decimal(u'0E-017')), '0E-17')
+        self.assertEqual(str(Decimal(u'45')), '45')
+        self.assertEqual(str(Decimal(u'-Inf')), '-Infinity')
+        self.assertEqual(str(Decimal(u'NaN123')), 'NaN123')
+
     def test_explicit_from_tuples(self):
 
         #zero
@@ -1032,6 +1038,16 @@
         self.assertEqual(str(d), '15.32')               # str
         self.assertEqual(repr(d), 'Decimal("15.32")')   # repr
 
+        # result type of string methods should be str, not unicode
+        unicode_inputs = [u'123.4', u'0.5E2', u'Infinity', u'sNaN',
+                          u'-0.0E100', u'-NaN001', u'-Inf']
+
+        for u in unicode_inputs:
+            d = Decimal(u)
+            self.assertEqual(type(str(d)), str)
+            self.assertEqual(type(repr(d)), str)
+            self.assertEqual(type(d.to_eng_string()), str)
+
     def test_tonum_methods(self):
         #Test float, int and long methods.
 
@@ -1192,7 +1208,13 @@
         d = d1.max(d2)
         self.assertTrue(type(d) is Decimal)
 
+    def test_implicit_context(self):
+        # Check results when context given implicitly.  (Issue 2478)
+        c = getcontext()
+        self.assertEqual(str(Decimal(0).sqrt()),
+                         str(c.sqrt(Decimal(0))))
 
+
 class DecimalPythonAPItests(unittest.TestCase):
 
     def test_pickle(self):
Index: Lib/test/test_weakref.py
===================================================================
--- Lib/test/test_weakref.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_weakref.py	(.../branches/release25-maint)	(Revision 65324)
@@ -645,7 +645,7 @@
         w = Target()
 
 
-class SubclassableWeakrefTestCase(unittest.TestCase):
+class SubclassableWeakrefTestCase(TestBase):
 
     def test_subclass_refs(self):
         class MyRef(weakref.ref):
@@ -709,7 +709,45 @@
         self.assertEqual(r.meth(), "abcdef")
         self.failIf(hasattr(r, "__dict__"))
 
+    def test_subclass_refs_with_cycle(self):
+        # Bug #3110
+        # An instance of a weakref subclass can have attributes.
+        # If such a weakref holds the only strong reference to the object,
+        # deleting the weakref will delete the object. In this case,
+        # the callback must not be called, because the ref object is
+        # being deleted.
+        class MyRef(weakref.ref):
+            pass
 
+        # Use a local callback, for "regrtest -R::"
+        # to detect refcounting problems
+        def callback(w):
+            self.cbcalled += 1
+
+        o = C()
+        r1 = MyRef(o, callback)
+        r1.o = o
+        del o
+
+        del r1 # Used to crash here
+
+        self.assertEqual(self.cbcalled, 0)
+
+        # Same test, with two weakrefs to the same object
+        # (since code paths are different)
+        o = C()
+        r1 = MyRef(o, callback)
+        r2 = MyRef(o, callback)
+        r1.r = r2
+        r2.o = o
+        del o
+        del r2
+
+        del r1 # Used to crash here
+
+        self.assertEqual(self.cbcalled, 0)
+
+
 class Object:
     def __init__(self, arg):
         self.arg = arg
@@ -1150,6 +1188,7 @@
         MappingTestCase,
         WeakValueDictionaryTestCase,
         WeakKeyDictionaryTestCase,
+        SubclassableWeakrefTestCase,
         )
     test_support.run_doctest(sys.modules[__name__])
 
Index: Lib/test/test_subprocess.py
===================================================================
--- Lib/test/test_subprocess.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_subprocess.py	(.../branches/release25-maint)	(Revision 65324)
@@ -304,6 +304,22 @@
         self.assertEqual(remove_stderr_debug_decorations(stderr),
                          "pineapple")
 
+    # This test is Linux specific for simplicity to at least have
+    # some coverage.  It is not a platform specific bug.
+    if os.path.isdir('/proc/%d/fd' % os.getpid()):
+        # Test for the fd leak reported in http://bugs.python.org/issue2791.
+        def test_communicate_pipe_fd_leak(self):
+            fd_directory = '/proc/%d/fd' % os.getpid()
+            num_fds_before_popen = len(os.listdir(fd_directory))
+            p = subprocess.Popen([sys.executable, '-c', 'print()'],
+                                 stdout=subprocess.PIPE)
+            p.communicate()
+            num_fds_after_communicate = len(os.listdir(fd_directory))
+            del p
+            num_fds_after_destruction = len(os.listdir(fd_directory))
+            self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
+            self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
+
     def test_communicate_returns(self):
         # communicate() should return None if no redirection is active
         p = subprocess.Popen([sys.executable, "-c",
Index: Lib/test/test_posix.py
===================================================================
--- Lib/test/test_posix.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_posix.py	(.../branches/release25-maint)	(Revision 65324)
@@ -9,6 +9,7 @@
 
 import time
 import os
+import pwd
 import sys
 import unittest
 import warnings
@@ -142,6 +143,33 @@
         if hasattr(posix, 'stat'):
             self.assert_(posix.stat(test_support.TESTFN))
 
+    if hasattr(posix, 'chown'):
+        def test_chown(self):
+            # raise an OSError if the file does not exist
+            os.unlink(test_support.TESTFN)
+            self.assertRaises(OSError, posix.chown, test_support.TESTFN, -1, -1)
+
+            # re-create the file
+            open(test_support.TESTFN, 'w').close()
+            if os.getuid() == 0:
+                try:
+                    # Many linux distros have a nfsnobody user as MAX_UID-2
+                    # that makes a good test case for signedness issues.
+                    #   http://bugs.python.org/issue1747858
+                    # This part of the test only runs when run as root.
+                    # Only scary people run their tests as root.
+                    ent = pwd.getpwnam('nfsnobody')
+                    posix.chown(test_support.TESTFN, ent.pw_uid, ent.pw_gid)
+                except KeyError:
+                    pass
+            else:
+                # non-root cannot chown to root, raises OSError
+                self.assertRaises(OSError, posix.chown,
+                                  test_support.TESTFN, 0, 0)
+
+            # test a successful chown call
+            posix.chown(test_support.TESTFN, os.getuid(), os.getgid())
+
     def test_chdir(self):
         if hasattr(posix, 'chdir'):
             posix.chdir(os.curdir)
Index: Lib/test/test_threading_local.py
===================================================================
--- Lib/test/test_threading_local.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_threading_local.py	(.../branches/release25-maint)	(Revision 65324)
@@ -2,6 +2,34 @@
 from doctest import DocTestSuite
 from test import test_support
 
+class ThreadingLocalTest(unittest.TestCase):
+    def test_derived(self):
+        # Issue 3088: if there is a threads switch inside the __init__
+        # of a threading.local derived class, the per-thread dictionary
+        # is created but not correctly set on the object.
+        # The first member set may be bogus.
+        import threading
+        import time
+        class Local(threading.local):
+            def __init__(self):
+                time.sleep(0.01)
+        local = Local()
+
+        def f(i):
+            local.x = i
+            # Simply check that the variable is correctly set
+            self.assertEqual(local.x, i)
+
+        threads= []
+        for i in range(10):
+            t = threading.Thread(target=f, args=(i,))
+            t.start()
+            threads.append(t)
+
+        for t in threads:
+            t.join()
+
+
 def test_main():
     suite = DocTestSuite('_threading_local')
 
@@ -19,6 +47,7 @@
         suite.addTest(DocTestSuite('_threading_local',
                                    setUp=setUp, tearDown=tearDown)
                       )
+        suite.addTest(unittest.makeSuite(ThreadingLocalTest))
 
     test_support.run_suite(suite)
 
Index: Lib/test/test_urllib2.py
===================================================================
--- Lib/test/test_urllib2.py	(.../tags/r252)	(Revision 65324)
+++ Lib/test/test_urllib2.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1038,6 +1038,12 @@
         o = build_opener(urllib2.HTTPHandler())
         self.opener_has_handler(o, urllib2.HTTPHandler)
 
+        # Issue2670: multiple handlers sharing the same base class
+        class MyOtherHTTPHandler(urllib2.HTTPHandler): pass
+        o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
+        self.opener_has_handler(o, MyHTTPHandler)
+        self.opener_has_handler(o, MyOtherHTTPHandler)
+
     def opener_has_handler(self, opener, handler_class):
         for h in opener.handlers:
             if h.__class__ == handler_class:
Index: Lib/plat-mac/Carbon/AppleEvents.py
===================================================================
--- Lib/plat-mac/Carbon/AppleEvents.py	(.../tags/r252)	(Revision 65324)
+++ Lib/plat-mac/Carbon/AppleEvents.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1,6 +1,7 @@
 # Generated from 'AEDataModel.h'
 
 def FOUR_CHAR_CODE(x): return x
+typeApplicationBundleID = FOUR_CHAR_CODE('bund')
 typeBoolean = FOUR_CHAR_CODE('bool')
 typeChar = FOUR_CHAR_CODE('TEXT')
 typeSInt16 = FOUR_CHAR_CODE('shor')
Index: Lib/plat-mac/macerrors.py
===================================================================
--- Lib/plat-mac/macerrors.py	(.../tags/r252)	(Revision 65324)
+++ Lib/plat-mac/macerrors.py	(.../branches/release25-maint)	(Revision 65324)
@@ -1,3 +1,4 @@
+# -coding=latin1-
 svTempDisable   =   -32768  #svTempDisable
 svDisabled  =   -32640  #Reserve range -32640 to -32768 for Apple temp disables.
 fontNotOutlineErr   =   -32615  #bitmap font passed to routine that does outlines only
Index: Lib/plat-mac/terminalcommand.py
===================================================================
--- Lib/plat-mac/terminalcommand.py	(.../tags/r252)	(Revision 65324)
+++ Lib/plat-mac/terminalcommand.py	(.../branches/release25-maint)	(Revision 65324)
@@ -27,7 +27,7 @@
 
 def run(command):
     """Run a shell command in a new Terminal.app window."""
-    termAddress = AE.AECreateDesc(typeApplSignature, TERMINAL_SIG)
+    termAddress = AE.AECreateDesc(typeApplicationBundleID, "com.apple.Terminal")
     theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
                                      kAutoGenerateReturnID, kAnyTransactionID)
     commandDesc = AE.AECreateDesc(typeChar, command)
Index: Lib/xml/dom/minidom.py
===================================================================
--- Lib/xml/dom/minidom.py	(.../tags/r252)	(Revision 65324)
+++ Lib/xml/dom/minidom.py	(.../branches/release25-maint)	(Revision 65324)
@@ -203,6 +203,8 @@
                 L.append(child)
                 if child.nodeType == Node.ELEMENT_NODE:
                     child.normalize()
+        if L:
+            L[-1].nextSibling = None
         self.childNodes[:] = L
 
     def cloneNode(self, deep):
Index: Modules/_ctypes/callbacks.c
===================================================================
--- Modules/_ctypes/callbacks.c	(.../tags/r252)	(Revision 65324)
+++ Modules/_ctypes/callbacks.c	(.../branches/release25-maint)	(Revision 65324)
@@ -12,6 +12,74 @@
 #endif
 #include "ctypes.h"
 
+/**************************************************************/
+
+static CThunkObject_dealloc(PyObject *_self)
+{
+	CThunkObject *self = (CThunkObject *)_self;
+	Py_XDECREF(self->converters);
+	Py_XDECREF(self->callable);
+	Py_XDECREF(self->restype);
+	if (self->pcl)
+		FreeClosure(self->pcl);
+	PyObject_Del(self);
+}
+
+static int
+CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg)
+{
+	CThunkObject *self = (CThunkObject *)_self;
+	Py_VISIT(self->converters);
+	Py_VISIT(self->callable);
+	Py_VISIT(self->restype);
+	return 0;
+}
+
+static int
+CThunkObject_clear(PyObject *_self)
+{
+	CThunkObject *self = (CThunkObject *)_self;
+	Py_CLEAR(self->converters);
+	Py_CLEAR(self->callable);
+	Py_CLEAR(self->restype);
+	return 0;
+}
+
+PyTypeObject CThunk_Type = {
+	PyObject_HEAD_INIT(NULL)
+	0,
+	"_ctypes.CThunkObject",
+	sizeof(CThunkObject),			/* tp_basicsize */
+	sizeof(ffi_type),			/* tp_itemsize */
+	CThunkObject_dealloc,			/* tp_dealloc */
+	0,					/* tp_print */
+	0,					/* tp_getattr */
+	0,					/* tp_setattr */
+	0,					/* tp_compare */
+	0,					/* tp_repr */
+	0,					/* tp_as_number */
+	0,					/* tp_as_sequence */
+	0,					/* tp_as_mapping */
+	0,					/* tp_hash */
+	0,					/* tp_call */
+	0,					/* tp_str */
+	0,					/* tp_getattro */
+	0,					/* tp_setattro */
+	0,					/* tp_as_buffer */
+	Py_TPFLAGS_DEFAULT,			/* tp_flags */
+	"CThunkObject",				/* tp_doc */
+	CThunkObject_traverse,			/* tp_traverse */
+	CThunkObject_clear,	       		/* tp_clear */
+	0,					/* tp_richcompare */
+	0,					/* tp_weaklistoffset */
+	0,					/* tp_iter */
+	0,					/* tp_iternext */
+	0,					/* tp_methods */
+	0,					/* tp_members */
+};
+
+/**************************************************************/
+
 static void
 PrintError(char *msg, ...)
 {
@@ -247,32 +315,56 @@
 			void **args,
 			void *userdata)
 {
-	ffi_info *p = userdata;
-
+ 	CThunkObject *p = (CThunkObject *)userdata;
+ 	
 	_CallPythonObject(resp,
-			  p->restype,
+			  p->ffi_restype,
 			  p->setfunc,
 			  p->callable,
 			  p->converters,
 			  args);
 }
 
-ffi_info *AllocFunctionCallback(PyObject *callable,
-				PyObject *converters,
-				PyObject *restype,
-				int is_cdecl)
+static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
 {
+	CThunkObject *p;
+	int i;
+
+	p = PyObject_NewVar(CThunkObject, &CThunk_Type, nArgs);
+	if (p == NULL) {
+		PyErr_NoMemory();
+		return NULL;
+	}
+
+	p->pcl = NULL;
+	memset(&p->cif, 0, sizeof(p->cif));
+	p->converters = NULL;
+	p->callable = NULL;
+	p->setfunc = NULL;
+	p->ffi_restype = NULL;
+	
+	for (i = 0; i < nArgs + 1; ++i)
+		p->atypes[i] = NULL;
+	return p;
+}
+
+CThunkObject *AllocFunctionCallback(PyObject *callable,
+				    PyObject *converters,
+				    PyObject *restype,
+				    int is_cdecl)
+{
 	int result;
-	ffi_info *p;
+	CThunkObject *p;
 	int nArgs, i;
 	ffi_abi cc;
 
 	nArgs = PySequence_Size(converters);
-	p = (ffi_info *)PyMem_Malloc(sizeof(ffi_info) + sizeof(ffi_type) * (nArgs));
-	if (p == NULL) {
-		PyErr_NoMemory();
+	p = CThunkObject_new(nArgs);
+	if (p == NULL)
 		return NULL;
-	}
+
+	assert(CThunk_CheckExact(p));
+
 	p->pcl = MallocClosure();
 	if (p->pcl == NULL) {
 		PyErr_NoMemory();
@@ -288,9 +380,11 @@
 	}
 	p->atypes[i] = NULL;
 
+	Py_INCREF(restype);
+	p->restype = restype;
 	if (restype == Py_None) {
 		p->setfunc = NULL;
-		p->restype = &ffi_type_void;
+		p->ffi_restype = &ffi_type_void;
 	} else {
 		StgDictObject *dict = PyType_stgdict(restype);
 		if (dict == NULL || dict->setfunc == NULL) {
@@ -299,7 +393,7 @@
 		  goto error;
 		}
 		p->setfunc = dict->setfunc;
-		p->restype = &dict->ffi_type_pointer;
+		p->ffi_restype = &dict->ffi_type_pointer;
 	}
 
 	cc = FFI_DEFAULT_ABI;
@@ -322,16 +416,14 @@
 		goto error;
 	}
 
+	Py_INCREF(converters);
 	p->converters = converters;
+	Py_INCREF(callable);
 	p->callable = callable;
 	return p;
 
   error:
-	if (p) {
-		if (p->pcl)
-			FreeClosure(p->pcl);
-		PyMem_Free(p);
-	}
+	Py_XDECREF(p);
 	return NULL;
 }
 
Index: Modules/_ctypes/_ctypes.c
===================================================================
--- Modules/_ctypes/_ctypes.c	(.../tags/r252)	(Revision 65324)
+++ Modules/_ctypes/_ctypes.c	(.../branches/release25-maint)	(Revision 65324)
@@ -2878,7 +2878,7 @@
 	CFuncPtrObject *self;
 	PyObject *callable;
 	StgDictObject *dict;
-	ffi_info *thunk;
+	CThunkObject *thunk;
 
 	if (PyTuple_GET_SIZE(args) == 0)
 		return GenericCData_new(type, args, kwds);
@@ -2935,11 +2935,6 @@
 		return NULL;
 	}
 
-	/*****************************************************************/
-	/* The thunk keeps unowned references to callable and dict->argtypes
-	   so we have to keep them alive somewhere else: callable is kept in self,
-	   dict->argtypes is in the type's stgdict.
-	*/
 	thunk = AllocFunctionCallback(callable,
 				      dict->argtypes,
 				      dict->restype,
@@ -2948,27 +2943,22 @@
 		return NULL;
 
 	self = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
-	if (self == NULL)
+	if (self == NULL) {
+		Py_DECREF(thunk);
 		return NULL;
+	}
 
 	Py_INCREF(callable);
 	self->callable = callable;
 
 	self->thunk = thunk;
-	*(void **)self->b_ptr = *(void **)thunk;
-
-	/* We store ourself in self->b_objects[0], because the whole instance
-	   must be kept alive if stored in a structure field, for example.
-	   Cycle GC to the rescue! And we have a unittest proving that this works
-	   correctly...
-	*/
-
-	Py_INCREF((PyObject *)self); /* for KeepRef */
-	if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)self)) {
+	*(void **)self->b_ptr = (void *)thunk->pcl;
+	
+	Py_INCREF((PyObject *)thunk); /* for KeepRef */
+	if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
 		Py_DECREF((PyObject *)self);
 		return NULL;
 	}
-
 	return (PyObject *)self;
 }
 
@@ -3415,6 +3405,7 @@
 	Py_VISIT(self->argtypes);
 	Py_VISIT(self->converters);
 	Py_VISIT(self->paramflags);
+	Py_VISIT(self->thunk);
 	return CData_traverse((CDataObject *)self, visit, arg);
 }
 
@@ -3428,13 +3419,7 @@
 	Py_CLEAR(self->argtypes);
 	Py_CLEAR(self->converters);
 	Py_CLEAR(self->paramflags);
-
-	if (self->thunk) {
-		FreeClosure(self->thunk->pcl);
-		PyMem_Free(self->thunk);
-		self->thunk = NULL;
-	}
-
+	Py_CLEAR(self->thunk);
 	return CData_clear((CDataObject *)self);
 }
 
@@ -4673,6 +4658,9 @@
 	if (PyType_Ready(&PyCArg_Type) < 0)
 		return;
 
+	if (PyType_Ready(&CThunk_Type) < 0)
+		return;
+
 	/* StgDict is derived from PyDict_Type */
 	StgDict_Type.tp_base = &PyDict_Type;
 	if (PyType_Ready(&StgDict_Type) < 0)
Index: Modules/_ctypes/ctypes.h
===================================================================
--- Modules/_ctypes/ctypes.h	(.../tags/r252)	(Revision 65324)
+++ Modules/_ctypes/ctypes.h	(.../branches/release25-maint)	(Revision 65324)
@@ -68,14 +68,18 @@
 };
 
 typedef struct {
+	PyObject_VAR_HEAD
 	ffi_closure *pcl; /* the C callable */
 	ffi_cif cif;
 	PyObject *converters;
 	PyObject *callable;
+	PyObject *restype;
 	SETFUNC setfunc;
-	ffi_type *restype;
+	ffi_type *ffi_restype;
 	ffi_type *atypes[1];
-} ffi_info;
+} CThunkObject;
+extern PyTypeObject CThunk_Type;
+#define CThunk_CheckExact(v)	    ((v)->ob_type == &CThunk_Type)
 
 typedef struct {
 	/* First part identical to tagCDataObject */
@@ -91,7 +95,7 @@
 	union value b_value;
 	/* end of tagCDataObject, additional fields follow */
 
-	ffi_info *thunk;
+	CThunkObject *thunk;
 	PyObject *callable;
 
 	/* These two fields will override the ones in the type's stgdict if
@@ -162,10 +166,10 @@
 
 extern PyMethodDef module_methods[];
 
-extern ffi_info *AllocFunctionCallback(PyObject *callable,
-				       PyObject *converters,
-				       PyObject *restype,
-				       int stdcall);
+extern CThunkObject *AllocFunctionCallback(PyObject *callable,
+					   PyObject *converters,
+					   PyObject *restype,
+					   int stdcall);
 /* a table entry describing a predefined ctypes type */
 struct fielddesc {
 	char code;
Index: Modules/mmapmodule.c
===================================================================
--- Modules/mmapmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/mmapmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -881,6 +881,10 @@
 				    "mmap invalid access parameter.");
 	}
 
+    if (prot == PROT_READ) {
+        access = ACCESS_READ;
+    }
+
 #ifdef HAVE_FSTAT
 #  ifdef __VMS
 	/* on OpenVMS we must ensure that all bytes are written to the file */
Index: Modules/almodule.c
===================================================================
--- Modules/almodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/almodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -1633,9 +1633,11 @@
 	if (nvals < 0)
 		goto cleanup;
 	if (nvals > setsize) {
+		ALvalue *old_return_set = return_set;
 		setsize = nvals;
 		PyMem_RESIZE(return_set, ALvalue, setsize);
 		if (return_set == NULL) {
+			return_set = old_return_set;
 			PyErr_NoMemory();
 			goto cleanup;
 		}
Index: Modules/_bsddb.c
===================================================================
--- Modules/_bsddb.c	(.../tags/r252)	(Revision 65324)
+++ Modules/_bsddb.c	(.../branches/release25-maint)	(Revision 65324)
@@ -834,7 +834,7 @@
             Py_DECREF(self->myenvobj);
             self->myenvobj = NULL;
         }
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
     return self;
@@ -955,7 +955,7 @@
     err = db_env_create(&self->db_env, flags);
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
     else {
@@ -1004,8 +1004,7 @@
 #endif
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        Py_DECREF(self->env);
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
     return self;
@@ -1062,7 +1061,7 @@
 #endif
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
 
@@ -1103,8 +1102,7 @@
     err = db_sequence_create(&self->sequence, self->mydb->db, flags);
     MYDB_END_ALLOW_THREADS;
     if (makeDBError(err)) {
-        Py_DECREF(self->mydb);
-        PyObject_Del(self);
+        Py_DECREF(self);
         self = NULL;
     }
 
Index: Modules/arraymodule.c
===================================================================
--- Modules/arraymodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/arraymodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -816,6 +816,7 @@
 array_do_extend(arrayobject *self, PyObject *bb)
 {
 	Py_ssize_t size;
+	char *old_item;
 
 	if (!array_Check(bb))
 		return array_iter_extend(self, bb);
@@ -831,10 +832,11 @@
 			return -1;
 	}
 	size = self->ob_size + b->ob_size;
+	old_item = self->ob_item;
         PyMem_RESIZE(self->ob_item, char, size*self->ob_descr->itemsize);
         if (self->ob_item == NULL) {
-                PyObject_Del(self);
-                PyErr_NoMemory();
+		self->ob_item = old_item;
+		PyErr_NoMemory();
 		return -1;
         }
 	memcpy(self->ob_item + self->ob_size*self->ob_descr->itemsize,
@@ -886,7 +888,7 @@
 			if (size > PY_SSIZE_T_MAX / n) {
 				return PyErr_NoMemory();
 			}
-			PyMem_Resize(items, char, n * size);
+			PyMem_RESIZE(items, char, n * size);
 			if (items == NULL)
 				return PyErr_NoMemory();
 			p = items;
Index: Modules/selectmodule.c
===================================================================
--- Modules/selectmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/selectmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -349,10 +349,12 @@
 {
 	Py_ssize_t i, pos;
 	PyObject *key, *value;
+        struct pollfd *old_ufds = self->ufds;
 
 	self->ufd_len = PyDict_Size(self->dict);
-	PyMem_Resize(self->ufds, struct pollfd, self->ufd_len);
+	PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
 	if (self->ufds == NULL) {
+                self->ufds = old_ufds;
 		PyErr_NoMemory();
 		return 0;
 	}
Index: Modules/timing.h
===================================================================
--- Modules/timing.h	(.../tags/r252)	(Revision 65324)
+++ Modules/timing.h	(.../branches/release25-maint)	(Revision 65324)
@@ -10,14 +10,11 @@
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *	This product includes software developed by George V. Neville-Neil
- * 4. The name, George Neville-Neil may not be used to endorse or promote 
- *    products derived from this software without specific prior 
+ * 3. The name, George Neville-Neil may not be used to endorse or promote
+ *    products derived from this software without specific prior
  *    written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
Index: Modules/zlibmodule.c
===================================================================
--- Modules/zlibmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/zlibmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -774,6 +774,10 @@
 
     if (!PyArg_ParseTuple(args, "|i:flush", &length))
 	return NULL;
+    if (length <= 0) {
+	PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
+	return NULL;
+    }
     if (!(retval = PyString_FromStringAndSize(NULL, length)))
 	return NULL;
 
Index: Modules/threadmodule.c
===================================================================
--- Modules/threadmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/threadmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -294,7 +294,10 @@
 		}
 		
 	}
-	else if (self->dict != ldict) {
+
+	/* The call to tp_init above may have caused another thread to run.
+	   Install our ldict again. */
+	if (self->dict != ldict) {
 		Py_CLEAR(self->dict);
 		Py_INCREF(ldict);
 		self->dict = ldict;
Index: Modules/_sqlite/cursor.c
===================================================================
--- Modules/_sqlite/cursor.c	(.../tags/r252)	(Revision 65324)
+++ Modules/_sqlite/cursor.c	(.../branches/release25-maint)	(Revision 65324)
@@ -851,15 +851,17 @@
         next_row = next_row_tuple;
     }
 
-    rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
-    if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
-        Py_DECREF(next_row);
-        _seterror(self->connection->db);
-        return NULL;
-    }
+    if (self->statement) {
+        rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
+        if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
+            Py_DECREF(next_row);
+            _seterror(self->connection->db);
+            return NULL;
+        }
 
-    if (rc == SQLITE_ROW) {
-        self->next_row = _fetch_one_row(self);
+        if (rc == SQLITE_ROW) {
+            self->next_row = _fetch_one_row(self);
+        }
     }
 
     return next_row;
@@ -979,11 +981,11 @@
     {"executescript", (PyCFunction)cursor_executescript, METH_VARARGS,
         PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
     {"fetchone", (PyCFunction)cursor_fetchone, METH_NOARGS,
+        PyDoc_STR("Fetches one row from the resultset.")},
+    {"fetchmany", (PyCFunction)cursor_fetchmany, METH_VARARGS,
         PyDoc_STR("Fetches several rows from the resultset.")},
-    {"fetchmany", (PyCFunction)cursor_fetchmany, METH_VARARGS,
+    {"fetchall", (PyCFunction)cursor_fetchall, METH_NOARGS,
         PyDoc_STR("Fetches all rows from the resultset.")},
-    {"fetchall", (PyCFunction)cursor_fetchall, METH_NOARGS,
-        PyDoc_STR("Fetches one row from the resultset.")},
     {"close", (PyCFunction)cursor_close, METH_NOARGS,
         PyDoc_STR("Closes the cursor.")},
     {"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
Index: Modules/posixmodule.c
===================================================================
--- Modules/posixmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/posixmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -1779,9 +1779,9 @@
 posix_chown(PyObject *self, PyObject *args)
 {
 	char *path = NULL;
-	int uid, gid;
+	long uid, gid;
 	int res;
-	if (!PyArg_ParseTuple(args, "etii:chown",
+	if (!PyArg_ParseTuple(args, "etll:chown",
 	                      Py_FileSystemDefaultEncoding, &path,
 	                      &uid, &gid))
 		return NULL;
Index: Modules/main.c
===================================================================
--- Modules/main.c	(.../tags/r252)	(Revision 65324)
+++ Modules/main.c	(.../branches/release25-maint)	(Revision 65324)
@@ -134,6 +134,15 @@
 			(void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
 			PyErr_Clear();
 			fclose(fp);
+               } else {
+			int save_errno;
+			save_errno = errno;
+			PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
+			errno = save_errno;
+			PyErr_SetFromErrnoWithFilename(PyExc_IOError,
+						       startup);
+			PyErr_Print();
+			PyErr_Clear();
 		}
 	}
 }
Index: Modules/itertoolsmodule.c
===================================================================
--- Modules/itertoolsmodule.c	(.../tags/r252)	(Revision 65324)
+++ Modules/itertoolsmodule.c	(.../branches/release25-maint)	(Revision 65324)
@@ -199,7 +199,7 @@
 {
 	_grouperobject *igo;
 
-	igo = PyObject_New(_grouperobject, &_grouper_type);
+	igo = PyObject_GC_New(_grouperobject, &_grouper_type);
 	if (igo == NULL)
 		return NULL;
 	igo->parent = (PyObject *)parent;
@@ -207,17 +207,27 @@
 	igo->tgtkey = tgtkey;
 	Py_INCREF(tgtkey);
 
+	PyObject_GC_Track(igo);
 	return (PyObject *)igo;
 }
 
 static void
 _grouper_dealloc(_grouperobject *igo)
 {
+	PyObject_GC_UnTrack(igo);
 	Py_DECREF(igo->parent);
 	Py_DECREF(igo->tgtkey);
-	PyObject_Del(igo);
+	PyObject_GC_Del(igo);
 }
 
+static int
+_grouper_traverse(_grouperobject *igo, visitproc visit, void *arg)
+{
+	Py_VISIT(igo->parent);
+	Py_VISIT(igo->tgtkey);
+	return 0;
+}
+
 static PyObject *
 _grouper_next(_grouperobject *igo)
 {
@@ -282,9 +292,9 @@
 	PyObject_GenericGetAttr,	/* tp_getattro */
 	0,				/* tp_setattro */
 	0,				/* tp_as_buffer */
-	Py_TPFLAGS_DEFAULT,		/* tp_flags */
+	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,	/* tp_flags */
 	0,				/* tp_doc */
-	0, 				/* tp_traverse */
+	(traverseproc)_grouper_traverse,/* tp_traverse */
 	0,				/* tp_clear */
 	0,				/* tp_richcompare */
 	0,				/* tp_weaklistoffset */
@@ -301,7 +311,7 @@
 	0,				/* tp_init */
 	0,				/* tp_alloc */
 	0,				/* tp_new */
-	PyObject_Del,			/* tp_free */
+	PyObject_GC_Del,		/* tp_free */
 };