Skip to content

Commit 9f4676d

Browse files
committed
throw CannotCastException from CastToJavaString i case the cast fails.
1 parent e84bcc5 commit 9f4676d

30 files changed

+325
-124
lines changed

graalpython/com.oracle.graal.python.test/src/tests/test_interop.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,18 @@ def test_key_info():
262262
assert not polyglot.__key_info__(builtinObj, "__len__", "removable")
263263
assert not polyglot.__key_info__(builtinObj, "__len__", "insertable")
264264

265+
def test_java_classpath():
266+
import java
267+
try:
268+
java.add_to_classpath(1)
269+
except TypeError as e:
270+
assert "classpath argument 1 must be string, not int" in str(e)
271+
272+
try:
273+
java.add_to_classpath('a', 1)
274+
except TypeError as e:
275+
assert "classpath argument 2 must be string, not int" in str(e)
276+
265277
def test_host_lookup():
266278
import java
267279
try:
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
2+
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3+
#
4+
# The Universal Permissive License (UPL), Version 1.0
5+
#
6+
# Subject to the condition set forth below, permission is hereby granted to any
7+
# person obtaining a copy of this software, associated documentation and/or
8+
# data (collectively the "Software"), free of charge and under any and all
9+
# copyright rights in the Software, and any and all patent rights owned or
10+
# freely licensable by each licensor hereunder covering either (i) the
11+
# unmodified Software as contributed to or provided by such licensor, or (ii)
12+
# the Larger Works (as defined below), to deal in both
13+
#
14+
# (a) the Software, and
15+
#
16+
# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
17+
# one is included with the Software each a "Larger Work" to which the Software
18+
# is contributed by such licensors),
19+
#
20+
# without restriction, including without limitation the rights to copy, create
21+
# derivative works of, display, perform, and distribute the Software and make,
22+
# use, sell, offer for sale, import, export, have made, and have sold the
23+
# Software and the Larger Work(s), and to sublicense the foregoing rights on
24+
# either these or other terms.
25+
#
26+
# This license is subject to the following condition:
27+
#
28+
# The above copyright notice and either this complete permission notice or at a
29+
# minimum a reference to the UPL must be included in all copies or substantial
30+
# portions of the Software.
31+
#
32+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
38+
# SOFTWARE.
39+
40+
def test_SemLock_raises_on_non_string_name():
41+
from _multiprocessing import SemLock
42+
try :
43+
SemLock(kind=1, value=1, name={1:2}, maxvalue=1, unlink=1)
44+
except TypeError:
45+
raised = True
46+
assert raised

graalpython/com.oracle.graal.python.test/src/tests/test_socket.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,12 @@ def test_inet_aton_errs(self):
5757
self.assertRaises(OSError, lambda : socket.inet_aton('oracle.com'))
5858
self.assertRaises(OSError, lambda : socket.inet_aton('0x7000000000000000'))
5959
self.assertRaises(OSError, lambda : socket.inet_aton('255.255.256.1'))
60-
self.assertRaises(TypeError, lambda : socket.inet_aton(255))
60+
self.assertRaises(TypeError, lambda : socket.inet_aton(255))
61+
62+
def test_get_name_info():
63+
import socket
64+
try :
65+
socket.getnameinfo((1, 0, 0, 0), 0)
66+
except TypeError:
67+
raised = True
68+
assert raised

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/BuiltinConstructors.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@
177177
import com.oracle.graal.python.nodes.object.IsBuiltinClassProfile;
178178
import com.oracle.graal.python.nodes.subscript.SliceLiteralNode;
179179
import com.oracle.graal.python.nodes.truffle.PythonArithmeticTypes;
180+
import com.oracle.graal.python.nodes.util.CannotCastException;
180181
import com.oracle.graal.python.nodes.util.CastToByteNode;
181182
import com.oracle.graal.python.nodes.util.CastToJavaIntNode;
182183
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
@@ -2197,7 +2198,12 @@ private String getModuleNameFromGlobals(PythonObject globals, HashingStorageLibr
21972198
CompilerDirectives.transferToInterpreterAndInvalidate();
21982199
throw new IllegalStateException("invalid globals object");
21992200
}
2200-
return ensureCastToStringNode().execute(nameAttr);
2201+
try {
2202+
return ensureCastToStringNode().execute(nameAttr);
2203+
} catch (CannotCastException e) {
2204+
CompilerDirectives.transferToInterpreterAndInvalidate();
2205+
throw new IllegalStateException();
2206+
}
22012207
}
22022208

22032209
@SuppressWarnings("try")

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/BuiltinFunctions.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@
153153
import com.oracle.graal.python.nodes.object.GetClassNode;
154154
import com.oracle.graal.python.nodes.object.IsBuiltinClassProfile;
155155
import com.oracle.graal.python.nodes.truffle.PythonArithmeticTypes;
156+
import com.oracle.graal.python.nodes.util.CannotCastException;
156157
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
157158
import com.oracle.graal.python.runtime.PythonContext;
158159
import com.oracle.graal.python.runtime.PythonCore;
@@ -1506,13 +1507,17 @@ PNone printGeneric(VirtualFrame frame, Object[] values, Object sepIn, Object end
15061507
@Cached("createIfTrueNode()") CoerceToBooleanNode castFlush,
15071508
@Cached PRaiseNode raiseNode,
15081509
@CachedLibrary(limit = "3") PythonObjectLibrary lib) {
1509-
String sep = sepIn instanceof PNone ? DEFAULT_SEPARATOR : castSep.execute(sepIn);
1510-
if (sep == null) {
1510+
String sep;
1511+
try {
1512+
sep = sepIn instanceof PNone ? DEFAULT_SEPARATOR : castSep.execute(sepIn);
1513+
} catch (CannotCastException e) {
15111514
throw raiseNode.raise(PythonBuiltinClassType.TypeError, "sep must be None or a string, not %p", sepIn);
15121515
}
15131516

1514-
String end = endIn instanceof PNone ? DEFAULT_END : castEnd.execute(endIn);
1515-
if (end == null) {
1517+
String end;
1518+
try {
1519+
end = endIn instanceof PNone ? DEFAULT_END : castEnd.execute(endIn);
1520+
} catch (CannotCastException e) {
15161521
throw raiseNode.raise(PythonBuiltinClassType.TypeError, "end must be None or a string, not %p", sepIn);
15171522
}
15181523

@@ -1587,8 +1592,13 @@ public abstract static class AsciiNode extends PythonUnaryBuiltinNode {
15871592
@Specialization(guards = "isString(obj)")
15881593
public Object asciiString(Object obj,
15891594
@Cached CastToJavaStringNode castToJavaStringNode) {
1590-
String str = castToJavaStringNode.execute(obj);
1591-
return doAsciiString(str);
1595+
try {
1596+
String str = castToJavaStringNode.execute(obj);
1597+
return doAsciiString(str);
1598+
} catch (CannotCastException e) {
1599+
CompilerDirectives.transferToInterpreterAndInvalidate();
1600+
throw new IllegalStateException("should not be reached");
1601+
}
15921602
}
15931603

15941604
@TruffleBoundary

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/CodecsModuleBuiltins.java

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
7777
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode;
7878
import com.oracle.graal.python.nodes.truffle.PythonArithmeticTypes;
79+
import com.oracle.graal.python.nodes.util.CannotCastException;
7980
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
8081
import com.oracle.graal.python.nodes.util.CastToJavaStringNodeGen;
8182
import com.oracle.graal.python.runtime.PythonCore;
@@ -322,7 +323,7 @@ public abstract static class CodecsEncodeNode extends EncodeBaseNode {
322323
@Specialization(guards = "isString(str)")
323324
Object encode(Object str, @SuppressWarnings("unused") PNone encoding, @SuppressWarnings("unused") PNone errors,
324325
@Shared("castStr") @Cached CastToJavaStringNode castStr) {
325-
String profiledStr = castStr.execute(str);
326+
String profiledStr = cast(castStr, str);
326327
PBytes bytes = encodeString(profiledStr, "utf-8", "strict");
327328
return factory().createTuple(new Object[]{bytes, getLength(bytes)});
328329
}
@@ -331,8 +332,8 @@ Object encode(Object str, @SuppressWarnings("unused") PNone encoding, @SuppressW
331332
Object encode(Object str, Object encoding, @SuppressWarnings("unused") PNone errors,
332333
@Shared("castStr") @Cached CastToJavaStringNode castStr,
333334
@Shared("castEncoding") @Cached CastToJavaStringNode castEncoding) {
334-
String profiledStr = castStr.execute(str);
335-
String profiledEncoding = castEncoding.execute(encoding);
335+
String profiledStr = cast(castStr, str);
336+
String profiledEncoding = cast(castEncoding, encoding);
336337
PBytes bytes = encodeString(profiledStr, profiledEncoding, "strict");
337338
return factory().createTuple(new Object[]{bytes, getLength(bytes)});
338339
}
@@ -341,8 +342,8 @@ Object encode(Object str, Object encoding, @SuppressWarnings("unused") PNone err
341342
Object encode(Object str, @SuppressWarnings("unused") PNone encoding, Object errors,
342343
@Shared("castStr") @Cached CastToJavaStringNode castStr,
343344
@Shared("castErrors") @Cached CastToJavaStringNode castErrors) {
344-
String profiledStr = castStr.execute(str);
345-
String profiledErrors = castErrors.execute(errors);
345+
String profiledStr = cast(castStr, str);
346+
String profiledErrors = cast(castErrors, errors);
346347
PBytes bytes = encodeString(profiledStr, "utf-8", profiledErrors);
347348
return factory().createTuple(new Object[]{bytes, getLength(bytes)});
348349
}
@@ -352,13 +353,22 @@ Object encode(Object str, Object encoding, Object errors,
352353
@Shared("castStr") @Cached CastToJavaStringNode castStr,
353354
@Shared("castEncoding") @Cached CastToJavaStringNode castEncoding,
354355
@Shared("castErrors") @Cached CastToJavaStringNode castErrors) {
355-
String profiledStr = castStr.execute(str);
356-
String profiledEncoding = castEncoding.execute(encoding);
357-
String profiledErrors = castErrors.execute(errors);
356+
String profiledStr = cast(castStr, str);
357+
String profiledEncoding = cast(castEncoding, encoding);
358+
String profiledErrors = cast(castErrors, errors);
358359
PBytes bytes = encodeString(profiledStr, profiledEncoding, profiledErrors);
359360
return factory().createTuple(new Object[]{bytes, getLength(bytes)});
360361
}
361362

363+
private static String cast(CastToJavaStringNode cast, Object obj) {
364+
try {
365+
return cast.execute(obj);
366+
} catch (CannotCastException e) {
367+
CompilerDirectives.transferToInterpreterAndInvalidate();
368+
throw new IllegalStateException("should not be reached");
369+
}
370+
}
371+
362372
@Fallback
363373
Object encode(Object str, @SuppressWarnings("unused") Object encoding, @SuppressWarnings("unused") Object errors) {
364374
throw raise(TypeError, "Can't convert '%p' object to str implicitly", str);
@@ -517,7 +527,12 @@ private String castToString(Object encodingObj) {
517527
CompilerDirectives.transferToInterpreterAndInvalidate();
518528
castEncodingToStringNode = insert(CastToJavaStringNodeGen.create());
519529
}
520-
return castEncodingToStringNode.execute(encodingObj);
530+
try {
531+
return castEncodingToStringNode.execute(encodingObj);
532+
} catch (CannotCastException e) {
533+
CompilerDirectives.transferToInterpreterAndInvalidate();
534+
throw new IllegalStateException("should not be reached");
535+
}
521536
}
522537

523538
private boolean castToBoolean(VirtualFrame frame, Object object) {
@@ -546,7 +561,13 @@ Object decode(PIBytesLike bytes, @SuppressWarnings("unused") PNone errors) {
546561
@Specialization(guards = {"isString(errors)"})
547562
Object decode(PIBytesLike bytes, Object errors,
548563
@Cached CastToJavaStringNode castStr) {
549-
String profiledErrors = castStr.execute(errors);
564+
String profiledErrors;
565+
try {
566+
profiledErrors = castStr.execute(errors);
567+
} catch (CannotCastException e) {
568+
CompilerDirectives.transferToInterpreterAndInvalidate();
569+
throw new IllegalStateException("should not be reached");
570+
}
550571
String string = decodeBytes(getBytesBuffer(bytes), profiledErrors);
551572
return factory().createTuple(new Object[]{string, string.length()});
552573
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GraalPythonModuleBuiltins.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,15 @@
7575
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
7676
import com.oracle.graal.python.nodes.subscript.GetItemNode;
7777
import com.oracle.graal.python.nodes.truffle.PythonArithmeticTypes;
78+
import com.oracle.graal.python.nodes.util.CannotCastException;
7879
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
7980
import com.oracle.graal.python.runtime.PythonContext;
8081
import com.oracle.graal.python.runtime.PythonCore;
8182
import com.oracle.graal.python.runtime.PythonOptions;
8283
import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage;
8384
import com.oracle.graal.python.util.PythonUtils;
8485
import com.oracle.truffle.api.CallTarget;
86+
import com.oracle.truffle.api.CompilerDirectives;
8587
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
8688
import com.oracle.truffle.api.RootCallTarget;
8789
import com.oracle.truffle.api.Truffle;
@@ -168,7 +170,12 @@ public Object run(String modulename, String moduleFile, PList modulepath,
168170
assert n <= pathList.length;
169171
String[] paths = new String[n];
170172
for (int i = 0; i < n; i++) {
171-
paths[i] = castString.execute(pathList[i]);
173+
try {
174+
paths[i] = castString.execute(pathList[i]);
175+
} catch (CannotCastException e) {
176+
CompilerDirectives.transferToInterpreterAndInvalidate();
177+
throw new IllegalStateException();
178+
}
172179
}
173180
return doCache(modulename, moduleFile, paths, ctxt, lang);
174181
}
@@ -211,7 +218,12 @@ public Object run(String modulename, PCode code, PList modulepath,
211218
Object[] pathList = modulepath.getSequenceStorage().getInternalArray();
212219
String[] paths = new String[pathList.length];
213220
for (int i = 0; i < pathList.length; i++) {
214-
paths[i] = castString.execute(pathList[i]);
221+
try {
222+
paths[i] = castString.execute(pathList[i]);
223+
} catch (CannotCastException e) {
224+
CompilerDirectives.transferToInterpreterAndInvalidate();
225+
throw new IllegalStateException();
226+
}
215227
}
216228
return cacheWithModulePath(modulename, paths, lang, ct);
217229
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/JavaModuleBuiltins.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
5757
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode;
5858
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
59+
import com.oracle.graal.python.nodes.util.CannotCastException;
5960
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
6061
import com.oracle.graal.python.runtime.PythonCore;
6162
import com.oracle.graal.python.runtime.exception.PythonErrorType;
@@ -128,12 +129,16 @@ PNone add(Object[] args,
128129
if (!env.isHostLookupAllowed()) {
129130
throw raise(PythonErrorType.NotImplementedError, "host access is not allowed");
130131
}
131-
for (Object arg : args) {
132-
String entry = castToString.execute(arg);
132+
for (int i = 0; i < args.length; i++) {
133+
Object arg = args[i];
134+
String entry = null;
133135
try {
136+
entry = castToString.execute(arg);
134137
// Always allow accessing JAR files in the language home; folders are allowed
135138
// implicitly
136139
env.addToHostClassPath(getContext().getPublicTruffleFileRelaxed(entry, ".jar"));
140+
} catch (CannotCastException e) {
141+
throw raise(PythonBuiltinClassType.TypeError, "classpath argument %d must be string, not %p", i + 1, arg);
137142
} catch (SecurityException e) {
138143
throw raise(TypeError, "invalid or unreadable classpath: '%s' - %m", entry, e);
139144
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/MarshalModuleBuiltins.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode;
7373
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
7474
import com.oracle.graal.python.nodes.object.IsBuiltinClassProfile;
75+
import com.oracle.graal.python.nodes.util.CannotCastException;
7576
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
7677
import com.oracle.graal.python.runtime.ExecutionContext.IndirectCallContext;
7778
import com.oracle.graal.python.runtime.PythonContext;
@@ -459,10 +460,10 @@ private PTuple internStrings(Object[] values) {
459460
castStrNode = insert(CastToJavaStringNode.create());
460461
}
461462
Object value = values[i];
462-
String strValue = castStrNode.execute(value);
463-
if (strValue != null) {
463+
try {
464+
String strValue = castStrNode.execute(value);
464465
interned[i] = new InternedString(strValue);
465-
} else {
466+
} catch (CannotCastException e) {
466467
interned[i] = value;
467468
}
468469
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/MultiprocessingModuleBuiltins.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode;
5555
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
5656
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
57+
import com.oracle.graal.python.nodes.util.CannotCastException;
5758
import com.oracle.graal.python.nodes.util.CastToJavaIntNode;
5859
import com.oracle.graal.python.nodes.util.CastToJavaStringNode;
5960
import com.oracle.graal.python.runtime.PythonCore;
@@ -98,7 +99,12 @@ PSemLock construct(LazyPythonClass cls, Object kindObj, Object valueObj, Object
9899
// on posix
99100
Semaphore semaphore = newSemaphore(value);
100101
int unlink = castUnlinkToIntNode.execute(unlinkObj);
101-
String name = castNameNode.execute(nameObj);
102+
String name;
103+
try {
104+
name = castNameNode.execute(nameObj);
105+
} catch (CannotCastException e) {
106+
throw raise(PythonBuiltinClassType.TypeError, "argument 4 must be str, not %p", nameObj);
107+
}
102108
if (unlink == 0) {
103109
// CPython creates a named semaphore, and if unlink != 0 unlinks
104110
// it directly so it cannot be access by other processes. We

0 commit comments

Comments
 (0)