code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
public void testRenameTo() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
final int totalByteCount = 4096;
byte[] bytes = new byte[totalByteCount];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf content = Unpooled.wrappedBuffer(bytes);
test.setContent(content);
boolean succ = test.renameTo(tmpFile);
assertTrue(succ);
FileInputStream fis = new FileInputStream(tmpFile);
try {
byte[] buf = new byte[totalByteCount];
int count = 0;
int offset = 0;
int size = totalByteCount;
while ((count = fis.read(buf, offset, size)) > 0) {
offset += count;
size -= count;
if (offset >= totalByteCount || size <= 0) {
break;
}
}
assertArrayEquals(bytes, buf);
assertEquals(0, fis.available());
} finally {
fis.close();
}
} finally {
//release the ByteBuf in AbstractMemoryHttpData
test.delete();
}
} | CWE-379 | 83 |
public NettyHttpHeaders() {
this.nettyHeaders = new DefaultHttpHeaders(false);
this.conversionService = ConversionService.SHARED;
} | CWE-444 | 41 |
public void setProperty(String name, Object value) throws SAXException {
getXMLReader().setProperty(name, value);
} | CWE-611 | 13 |
public VFSLeaf createChildLeaf(String name) {
File fNewFile = new File(getBasefile(), name);
try {
if(!fNewFile.getParentFile().exists()) {
fNewFile.getParentFile().mkdirs();
}
if (!fNewFile.createNewFile()) {
log.warn("Could not create a new leaf::" + name + " in container::" + getBasefile().getAbsolutePath() + " - file alreay exists");
return null;
}
} catch (Exception e) {
log.error("Error while creating child leaf::" + name + " in container::" + getBasefile().getAbsolutePath(), e);
return null;
}
return new LocalFileImpl(fNewFile, this);
} | CWE-22 | 2 |
public static final Binder fromPath(Path path)
throws IOException {
try(InputStream inStream = Files.newInputStream(path)) {
return (Binder)myStream.fromXML(inStream);
} catch (Exception e) {
log.error("Cannot import this map: " + path, e);
return null;
}
} | CWE-91 | 78 |
public void testUpdateMapper_serializade_withExpirationDate() {
//create a mapper
String mapperId = UUID.randomUUID().toString();
String sessionId = UUID.randomUUID().toString().substring(0, 32);
PersistentMapper sMapper = new PersistentMapper("mapper-to-persist-until");
PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, 60000);
Assert.assertNotNull(pMapper);
dbInstance.commitAndCloseSession();
//load the mapper
PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper);
Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());
Assert.assertTrue(objReloaded instanceof PersistentMapper);
PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;
Assert.assertEquals("mapper-to-persist-until", sMapperReloaded.getKey());
Assert.assertNotNull(loadedMapper.getExpirationDate());
//update
PersistentMapper sMapper2 = new PersistentMapper("mapper-to-update-until");
boolean updated = mapperDao.updateConfiguration(mapperId, sMapper2, 120000);
Assert.assertTrue(updated);
dbInstance.commitAndCloseSession();
//load the updated mapper
PersistedMapper loadedMapper2 = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper2);
Object objReloaded2 = XStreamHelper.createXStreamInstance().fromXML(loadedMapper2.getXmlConfiguration());
Assert.assertTrue(objReloaded2 instanceof PersistentMapper);
PersistentMapper sMapperReloaded2 = (PersistentMapper)objReloaded2;
Assert.assertEquals("mapper-to-update-until", sMapperReloaded2.getKey());
Assert.assertNotNull(loadedMapper2.getExpirationDate());
} | CWE-91 | 78 |
public void testLoadMapper_serializade() {
//create a mapper
String mapperId = UUID.randomUUID().toString();
String sessionId = UUID.randomUUID().toString().substring(0, 32);
PersistentMapper sMapper = new PersistentMapper("mapper-to-persist");
PersistedMapper pMapper = mapperDao.persistMapper(sessionId, mapperId, sMapper, -1);
Assert.assertNotNull(pMapper);
dbInstance.commitAndCloseSession();
//load the mapper
PersistedMapper loadedMapper = mapperDao.loadByMapperId(mapperId);
Assert.assertNotNull(loadedMapper);
Assert.assertEquals(pMapper, loadedMapper);
Assert.assertEquals(mapperId, loadedMapper.getMapperId());
Object objReloaded = XStreamHelper.createXStreamInstance().fromXML(pMapper.getXmlConfiguration());
Assert.assertTrue(objReloaded instanceof PersistentMapper);
PersistentMapper sMapperReloaded = (PersistentMapper)objReloaded;
Assert.assertEquals("mapper-to-persist", sMapperReloaded.getKey());
} | CWE-91 | 78 |
public Operation.OperationResult executeFixedCostOperation(
final MessageFrame frame, final EVM evm) {
Bytes shiftAmount = frame.popStackItem();
if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
frame.popStackItem();
frame.pushStackItem(UInt256.ZERO);
} else {
final int shiftAmountInt = shiftAmount.toInt();
final Bytes value = leftPad(frame.popStackItem());
if (shiftAmountInt >= 256) {
frame.pushStackItem(UInt256.ZERO);
} else {
frame.pushStackItem(value.shiftRight(shiftAmountInt));
}
}
return successResponse;
} | CWE-681 | 59 |
public static String compileMustache(Map<String, Object> context, String template) {
if (context == null || StringUtils.isBlank(template)) {
return "";
}
Writer writer = new StringWriter();
try {
Mustache.compiler().escapeHTML(false).emptyStringIsFalse(true).compile(template).execute(context, writer);
} finally {
try {
writer.close();
} catch (IOException e) {
logger.error(null, e);
}
}
return writer.toString();
} | CWE-79 | 1 |
public void testSetRequestMethod() {
HttpURLConnection conn = createHttpUrlConnection(convertToUrl(TEST_URL), "", 0, "", "");
Utils.setRequestMethod(conn, Utils.RequestMethod.POST);
Assert.assertEquals(conn.getRequestMethod(), "POST");
} | CWE-306 | 79 |
CreateCommentResponse saveComment() {
CreateCommentRequest createCommentRequest = ZrLogUtil.convertRequestParam(getRequest().getParameterMap(), CreateCommentRequest.class);
createCommentRequest.setIp(WebTools.getRealIp(getRequest()));
createCommentRequest.setUserAgent(getHeader("User-Agent"));
return commentService.save(createCommentRequest);
} | CWE-79 | 1 |
public void testMatchUse() {
JWKMatcher matcher = new JWKMatcher.Builder().keyUse(KeyUse.ENCRYPTION).build();
assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").keyUse(KeyUse.ENCRYPTION).build()));
assertFalse(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()));
assertEquals("use=enc", matcher.toString());
} | CWE-347 | 25 |
public String getHeader(String name) {
//logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
//logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
} | CWE-79 | 1 |
public static Object deserialize(byte[] data)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
} | CWE-470 | 84 |
public void encodeByteArrayDeepInJson() throws JSONException {
JSONObject data = new JSONObject("{a: \"hi\", b: {}, c: {a: \"bye\", b: {}}}");
data.getJSONObject("b").put("why", new byte[3]);
data.getJSONObject("c").getJSONObject("b").put("a", new byte[6]);
Packet<JSONObject> packet = new Packet<>(Parser.BINARY_EVENT);
packet.data = data;
packet.id = 999;
packet.nsp = "/deep";
Helpers.testBin(packet);
} | CWE-476 | 46 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(enciv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | CWE-125 | 47 |
public void headerMultipleContentLengthValidationShouldPropagate() {
LastInboundHandler inboundHandler = new LastInboundHandler();
request.addLong(HttpHeaderNames.CONTENT_LENGTH, 0);
request.addLong(HttpHeaderNames.CONTENT_LENGTH, 1);
Http2StreamChannel channel = newInboundStream(3, false, inboundHandler);
try {
inboundHandler.checkException();
fail();
} catch (Exception e) {
assertThat(e, CoreMatchers.<Exception>instanceOf(StreamException.class));
}
assertNull(inboundHandler.readInbound());
assertFalse(channel.isActive());
} | CWE-444 | 41 |
private static boolean nameContainsForbiddenSequence(String name) {
boolean result = false;
if (name != null) {
name = name.toLowerCase();
result = name.startsWith(".") ||
name.contains("../") ||
name.contains("..\\") ||
name.startsWith("/") ||
name.startsWith("\\") ||
name.endsWith("/") ||
name.contains("..%2f") ||
name.contains("..%5c") ||
name.startsWith("%2f") ||
name.startsWith("%5c") ||
name.endsWith("%2f") ||
name.contains("..\\u002f") ||
name.contains("..\\u005c") ||
name.startsWith("\\u002f") ||
name.startsWith("\\u005c") ||
name.endsWith("\\u002f")
;
}
return result;
} | CWE-22 | 2 |
public Optional<URL> getResource(String path) {
boolean isDirectory = isDirectory(path);
if (!isDirectory) {
URL url = classLoader.getResource(prefixPath(path));
return Optional.ofNullable(url);
}
return Optional.empty();
} | CWE-22 | 2 |
public void write(byte[] b, int offset, int length) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (offset < 0 || offset + length > b.length) {
throw new ArrayIndexOutOfBoundsException();
}
write(fd, b, offset, length);
} | CWE-787 | 24 |
private String marshallToString(Document document) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
} | CWE-611 | 13 |
public void encodeByteArray2() {
Packet<byte[]> packet = new Packet<>(Parser.BINARY_EVENT);
packet.data = new byte[2];
packet.id = 0;
packet.nsp = "/";
Helpers.testBin(packet);
} | CWE-476 | 46 |
public void onTaskSelectionEvent(@Observes TaskSelectionEvent event){
selectedTaskId = event.getTaskId();
selectedTaskName = event.getTaskName();
view.getTaskIdAndName().setText(String.valueOf(selectedTaskId) + " - "+selectedTaskName);
view.getContent().clear();
String placeToGo;
if(event.getPlace() != null && !event.getPlace().equals("")){
placeToGo = event.getPlace();
}else{
placeToGo = "Task Details";
}
DefaultPlaceRequest defaultPlaceRequest = new DefaultPlaceRequest(placeToGo);
//Set Parameters here:
defaultPlaceRequest.addParameter("taskId", String.valueOf(selectedTaskId));
defaultPlaceRequest.addParameter("taskName", selectedTaskName);
Set<Activity> activities = activityManager.getActivities(defaultPlaceRequest);
AbstractWorkbenchScreenActivity activity = ((AbstractWorkbenchScreenActivity) activities.iterator().next());
activitiesMap.put(placeToGo, activity);
IsWidget widget = activity.getWidget();
activity.launch(place, null);
activity.onStartup(defaultPlaceRequest);
view.getContent().add(widget);
activity.onOpen();
} | CWE-79 | 1 |
ReservedChar(int rawChar, String percentEncodedChar, byte marker) {
this.rawChar = rawChar;
this.percentEncodedChar = percentEncodedChar;
this.marker = marker;
} | CWE-22 | 2 |
public void testCurveCheckNegative_P256_attackPt2()
throws Exception {
// The malicious JWE contains a public key with order 2447
String maliciousJWE = "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiWE9YR1E5XzZRQ3ZCZzN1OHZDSS1VZEJ2SUNBRWNOTkJyZnFkN3RHN29RNCIsInkiOiJoUW9XTm90bk56S2x3aUNuZUprTElxRG5UTnc3SXNkQkM1M1ZVcVZqVkpjIiwiY3J2IjoiUC0yNTYifX0.UGb3hX3ePAvtFB9TCdWsNkFTv9QWxSr3MpYNiSBdW630uRXRBT3sxw.6VpU84oMob16DxOR98YTRw.y1UslvtkoWdl9HpugfP0rSAkTw1xhm_LbK1iRXzGdpYqNwIG5VU33UBpKAtKFBoA1Kk_sYtfnHYAvn-aes4FTg.UZPN8h7FcvA5MIOq-Pkj8A";
JWEObject jweObject = JWEObject.parse(maliciousJWE);
ECPublicKey ephemeralPublicKey = jweObject.getHeader().getEphemeralPublicKey().toECPublicKey();
ECPrivateKey privateKey = generateECPrivateKey(ECKey.Curve.P_256);
try {
ECDH.ensurePointOnCurve(ephemeralPublicKey, privateKey);
fail();
} catch (JOSEException e) {
assertEquals("Invalid ephemeral public key: Point not on expected curve", e.getMessage());
}
} | CWE-347 | 25 |
public SpotProtocolDecoder(Protocol protocol) {
super(protocol);
try {
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
xPath = XPathFactory.newInstance().newXPath();
messageExpression = xPath.compile("//messageList/message");
} catch (ParserConfigurationException | XPathExpressionException e) {
throw new RuntimeException(e);
}
} | CWE-611 | 13 |
void equal() {
final PathAndQuery res = PathAndQuery.parse("/=?a=b=1");
assertThat(res).isNotNull();
assertThat(res.path()).isEqualTo("/=");
assertThat(res.query()).isEqualTo("a=b=1");
// '%3D' in a query string should never be decoded into '='.
final PathAndQuery res2 = PathAndQuery.parse("/%3D?a%3db=1");
assertThat(res2).isNotNull();
assertThat(res2.path()).isEqualTo("/=");
assertThat(res2.query()).isEqualTo("a%3Db=1");
} | CWE-22 | 2 |
protected Class<?> getClassForNode(Node node) {
Class<?> type = node.getType();
if (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {
ImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);
for (Class<?> implementationClass: registry.getImplementations(node.getType())) {
String implementationTag = new Tag("!" + implementationClass.getSimpleName()).getValue();
if (implementationTag.equals(node.getTag().getValue()))
return implementationClass;
}
}
return super.getClassForNode(node);
}
| CWE-502 | 15 |
public void setStringInternEnabled(boolean stringInternEnabled) {
this.stringInternEnabled = stringInternEnabled;
} | CWE-611 | 13 |
private static boolean appendOneByte(Bytes buf, int cp, boolean wasSlash, boolean isPath) {
if (cp == 0x7F) {
// Reject the control character: 0x7F
return false;
}
if (cp >>> 5 == 0) {
// Reject the control characters: 0x00..0x1F
if (isPath) {
return false;
} else if (cp != 0x0A && cp != 0x0D && cp != 0x09) {
// .. except 0x0A (LF), 0x0D (CR) and 0x09 (TAB) because they are used in a form.
return false;
}
}
if (cp == '/' && isPath) {
if (!wasSlash) {
buf.ensure(1);
buf.add((byte) '/');
} else {
// Remove the consecutive slashes: '/path//with///consecutive////slashes'.
}
} else {
buf.ensure(1);
buf.add((byte) cp);
}
return true;
} | CWE-22 | 2 |
public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)
throws IOException
{
XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());
this.treeDigest = keyParams.getTreeDigest().getAlgorithm();
XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());
try
{
XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters
.Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))
.withIndex(xmssPrivateKey.getIndex())
.withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())
.withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())
.withPublicSeed(xmssPrivateKey.getPublicSeed())
.withRoot(xmssPrivateKey.getRoot());
if (xmssPrivateKey.getBdsState() != null)
{
keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));
}
this.keyParams = keyBuilder.build();
}
catch (ClassNotFoundException e)
{
throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage());
}
} | CWE-502 | 15 |
public RainbowParameters(int[] vi)
{
this.vi = vi;
try
{
checkParams();
}
catch (Exception e)
{
e.printStackTrace();
}
} | CWE-470 | 84 |
private String stripComments(String theScript) {
return BLOCK_COMMENT_STRIPPER.matcher(theScript).replaceAll("");
} | CWE-94 | 14 |
void colon() {
assertThat(PathAndQuery.parse("/:")).isNotNull();
assertThat(PathAndQuery.parse("/:/")).isNotNull();
assertThat(PathAndQuery.parse("/a/:")).isNotNull();
assertThat(PathAndQuery.parse("/a/:/")).isNotNull();
} | CWE-22 | 2 |
public void resetPassword(UserReference userReference, String newPassword)
throws ResetPasswordException
{
this.checkUserReference(userReference);
XWikiContext context = this.contextProvider.get();
DocumentUserReference documentUserReference = (DocumentUserReference) userReference;
DocumentReference reference = documentUserReference.getReference();
try {
XWikiDocument userDocument = context.getWiki().getDocument(reference, context);
userDocument.removeXObjects(RESET_PASSWORD_REQUEST_CLASS_REFERENCE);
BaseObject userXObject = userDocument.getXObject(USER_CLASS_REFERENCE);
userXObject.setStringValue("password", newPassword);
String saveComment = this.localizationManager.getTranslationPlain(
"xe.admin.passwordReset.step2.versionComment.passwordReset");
context.getWiki().saveDocument(userDocument, saveComment, true, context);
} catch (XWikiException e) {
throw new ResetPasswordException("Cannot open user document to perform reset password.", e);
}
} | CWE-640 | 20 |
public void setSetContentFromFileExceptionally() throws Exception {
final long maxSize = 4;
DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
f1.setMaxSize(maxSize);
try {
f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
File originalFile = f1.getFile();
assertNotNull(originalFile);
assertEquals(maxSize, originalFile.length());
assertEquals(maxSize, f1.length());
byte[] bytes = new byte[8];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
try {
f1.setContent(tmpFile);
fail("should not reach here!");
} catch (IOException e) {
assertNotNull(f1.getFile());
assertEquals(originalFile, f1.getFile());
assertEquals(maxSize, f1.length());
}
} finally {
f1.delete();
}
} | CWE-378 | 80 |
private static void appendHexNibble(StringBuilder buf, int nibble) {
if (nibble < 10) {
buf.append((char) ('0' + nibble));
} else {
buf.append((char) ('A' + nibble - 10));
}
} | CWE-22 | 2 |
public void shouldNotAllowToListFileOutsideRoot() throws Exception {
// given
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(containsString("this String argument must not contain the substring [..]"));
// when
logViewEndpoint.view("../somefile", null, null, null);
} | CWE-22 | 2 |
public void setIncludeInternalDTDDeclarations(boolean include) {
this.includeInternalDTDDeclarations = include;
} | CWE-611 | 13 |
protected int addFileNames(String[] file) { // This appears to only be used by unit tests
for (int i = 0; file != null && i < file.length; i++) {
workUnitList.add(new WorkUnit(file[i]));
}
return size();
} | CWE-502 | 15 |
private JWTClaimsSet fetchOidcProfile(BearerAccessToken accessToken) {
final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(),
accessToken);
final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
configuration.configureHttpRequest(userInfoHttpRequest);
try {
final var httpResponse = userInfoHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(),
httpResponse.getContent());
final var userInfoResponse = UserInfoResponse.parse(httpResponse);
if (userInfoResponse instanceof UserInfoErrorResponse) {
logger.error("Bad User Info response, error={}",
((UserInfoErrorResponse) userInfoResponse).getErrorObject().toJSONObject());
throw new AuthenticationException();
} else {
final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
final JWTClaimsSet userInfoClaimsSet;
if (userInfoSuccessResponse.getUserInfo() != null) {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
} else {
userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
}
return userInfoClaimsSet;
}
} catch (IOException | ParseException | java.text.ParseException | AuthenticationException e) {
throw new TechnicalException(e);
}
} | CWE-347 | 25 |
public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
{
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
| CWE-79 | 1 |
public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
Assert.state(doesNotContainFileColon(path), "Path must not contain 'file:'");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
} | CWE-22 | 2 |
protected String getContent(SxSource sxSource, FilesystemExportContext exportContext)
{
String content;
// We know we're inside a SX file located at "<S|J>sx/<Space>/<Page>/<s|j>sx<NNN>.<css|js>". Inside this CSS
// there can be URLs and we need to ensure that the prefix for these URLs lead to the root of the path, i.e.
// 3 levels up ("../../../").
// To make this happen we reuse the Doc Parent Level from FileSystemExportContext to a fixed value of 3.
// We also make sure to put back the original value
int originalDocParentLevel = exportContext.getDocParentLevel();
try {
exportContext.setDocParentLevels(3);
content = sxSource.getContent();
} finally {
exportContext.setDocParentLevels(originalDocParentLevel);
}
return content;
} | CWE-22 | 2 |
public static HColor unlinear(HColor color1, HColor color2, int completion) {
if (completion == 0) {
return color1;
}
if (completion == 100) {
return color2;
}
if (color1 instanceof HColorSimple && color2 instanceof HColorSimple) {
return HColorSimple.unlinear((HColorSimple) color1, (HColorSimple) color2, completion);
}
return color1;
} | CWE-918 | 16 |
function findLateSubscriptionSortedByPriority() {
if (late_subscriptions.length === 0) {
return null;
}
late_subscriptions.sort(compare_subscriptions);
// istanbul ignore next
if (doDebug) {
debugLog(
late_subscriptions
.map(
(s: Subscription) =>
"[ id = " +
s.id +
" prio=" +
s.priority +
" t=" +
s.timeToExpiration +
" ka=" +
s.timeToKeepAlive +
" m?=" +
s.hasUncollectedMonitoredItemNotifications +
" " +
SubscriptionState[s.state] +
" " + s.messageSent +
"]"
)
.join(" \n")
);
}
return late_subscriptions[late_subscriptions.length - 1];
} | CWE-770 | 37 |
public Mapper retrieveMapperById(String mapperId) {
List<PersistedMapper> mappers = dbInstance.getCurrentEntityManager()
.createNamedQuery("loadMapperByKey", PersistedMapper.class)
.setParameter("mapperId", mapperId)
.getResultList();
PersistedMapper pm = mappers.isEmpty() ? null : mappers.get(0);
if(pm != null && StringHelper.containsNonWhitespace(pm.getXmlConfiguration())) {
String configuration = pm.getXmlConfiguration();
Object obj = XStreamHelper.createXStreamInstance().fromXML(configuration);
if(obj instanceof Mapper) {
return (Mapper)obj;
}
}
return null;
} | CWE-91 | 78 |
final protected FontConfiguration getFontConfiguration() {
if (UseStyle.useBetaStyle() == false)
return FontConfiguration.create(skinParam, FontParam.TIMING, null);
return FontConfiguration.create(skinParam, StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram)
.getMergedStyle(skinParam.getCurrentStyleBuilder()));
} | CWE-918 | 16 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
ghash.update(ciphertext, ciphertextOffset, dataLen);
ghash.pad(ad != null ? ad.length : 0, dataLen);
ghash.finish(enciv, 0, 16);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | CWE-787 | 24 |
public void testWhitespaceBeforeTransferEncoding01() {
String requestStr = "GET /some/path HTTP/1.1\r\n" +
" Transfer-Encoding : chunked\r\n" +
"Content-Length: 1\r\n" +
"Host: netty.io\r\n\r\n" +
"a";
testInvalidHeaders0(requestStr);
} | CWE-444 | 41 |
public void testSetContentFromFile() throws Exception {
TestHttpData test = new TestHttpData("test", UTF_8, 0);
try {
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] bytes = new byte[4096];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
test.setContent(tmpFile);
ByteBuf buf = test.getByteBuf();
assertEquals(buf.readerIndex(), 0);
assertEquals(buf.writerIndex(), bytes.length);
assertArrayEquals(bytes, test.get());
assertArrayEquals(bytes, ByteBufUtil.getBytes(buf));
} finally {
//release the ByteBuf
test.delete();
}
} | CWE-378 | 80 |
private void ondata(byte[] data) {
try {
this.decoder.add(data);
} catch (DecodingException e) {
this.onerror(e);
}
} | CWE-476 | 46 |
public static boolean saveLinkList(HashMap<String, PortletInstitution> portletMap){
XStream xstream = XStreamHelper.createXStreamInstance();
xstream.alias("LinksPortlet", Map.class);
xstream.alias(ELEM_LINK, PortletLink.class);
xstream.alias(ELEM_INSTITUTION, PortletInstitution.class);
xstream.aliasAttribute(PortletInstitution.class, ATTR_INSTITUTION_NAME, ATTR_INSTITUTION_NAME);
String output = xstream.toXML(portletMap);
XStreamHelper.writeObject(xstream, fxConfXStreamFile, portletMap);
return (output.length() != 0);
} | CWE-91 | 78 |
public static void fillArticleInfo(Log data, HttpServletRequest request, String suffix) {
data.put("alias", data.get("alias") + suffix);
data.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + data.get("alias"));
data.put("noSchemeUrl", WebTools.getHomeUrlWithHost(request) + Constants.getArticleUri() + data.get("alias"));
data.put("typeUrl", WebTools.getHomeUrl(request) + Constants.getArticleUri() + "sort/" + data.get("typeAlias") + suffix);
Log lastLog = data.get("lastLog");
Log nextLog = data.get("nextLog");
nextLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + nextLog.get("alias") + suffix);
lastLog.put("url", WebTools.getHomeUrl(request) + Constants.getArticleUri() + lastLog.get("alias") + suffix);
//没有使用md的toc目录的文章才尝试使用系统提取的目录
if (data.getStr("markdown") != null && !data.getStr("markdown").toLowerCase().contains("[toc]")
&& !data.getStr("markdown").toLowerCase().contains("[tocm]")) {
//最基础的实现方式,若需要更强大的实现方式建议使用JavaScript完成(页面输入toc对象)
OutlineVO outlineVO = OutlineUtil.extractOutline(data.getStr("content"));
data.put("tocHtml", OutlineUtil.buildTocHtml(outlineVO, ""));
data.put("toc", outlineVO);
}
if (!new CommentService().isAllowComment()) {
data.set("canComment", false);
}
} | CWE-79 | 1 |
public void testPrivateKeyParsingSHA256()
throws IOException, ClassNotFoundException
{
XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest());
XMSSMT mt = new XMSSMT(params, new SecureRandom());
mt.generateKeys();
byte[] privateKey = mt.exportPrivateKey();
byte[] publicKey = mt.exportPublicKey();
mt.importState(privateKey, publicKey);
assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey()));
} | CWE-470 | 84 |
private static boolean doesNotContainFileColon(String path) {
return !path.contains("file:");
} | CWE-22 | 2 |
public void toScientificString(StringBuilder result) {
assert(!isApproximate);
if (isNegative()) {
result.append('-');
}
if (precision == 0) {
result.append("0E+0");
return;
}
// NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from
// rOptPos (aka -maxFrac) due to overflow.
int upperPos = Math.min(precision + scale, lOptPos) - scale - 1;
int lowerPos = Math.max(scale, rOptPos) - scale;
int p = upperPos;
result.append((char) ('0' + getDigitPos(p)));
if ((--p) >= lowerPos) {
result.append('.');
for (; p >= lowerPos; p--) {
result.append((char) ('0' + getDigitPos(p)));
}
}
result.append('E');
int _scale = upperPos + scale;
if (_scale < 0) {
_scale *= -1;
result.append('-');
} else {
result.append('+');
}
if (_scale == 0) {
result.append('0');
}
int insertIndex = result.length();
while (_scale > 0) {
int quot = _scale / 10;
int rem = _scale % 10;
result.insert(insertIndex, (char) ('0' + rem));
_scale = quot;
}
} | CWE-190 | 19 |
public void error(SAXParseException e) {
} | CWE-611 | 13 |
private File tempFile() throws IOException {
String newpostfix;
String diskFilename = getDiskFilename();
if (diskFilename != null) {
newpostfix = '_' + diskFilename;
} else {
newpostfix = getPostfix();
}
File tmpFile;
if (getBaseDirectory() == null) {
// create a temporary file
tmpFile = File.createTempFile(getPrefix(), newpostfix);
} else {
tmpFile = File.createTempFile(getPrefix(), newpostfix, new File(
getBaseDirectory()));
}
if (deleteOnExit()) {
// See https://github.com/netty/netty/issues/10351
DeleteFileOnExitHook.add(tmpFile.getPath());
}
return tmpFile;
} | CWE-378 | 80 |
public void setSetContentFromFileExceptionally() throws Exception {
final long maxSize = 4;
DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
f1.setMaxSize(maxSize);
try {
f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
File originalFile = f1.getFile();
assertNotNull(originalFile);
assertEquals(maxSize, originalFile.length());
assertEquals(maxSize, f1.length());
byte[] bytes = new byte[8];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
tmpFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpFile);
try {
fos.write(bytes);
fos.flush();
} finally {
fos.close();
}
try {
f1.setContent(tmpFile);
fail("should not reach here!");
} catch (IOException e) {
assertNotNull(f1.getFile());
assertEquals(originalFile, f1.getFile());
assertEquals(maxSize, f1.length());
}
} finally {
f1.delete();
}
} | CWE-379 | 83 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input2->type);
output->type = input2->type;
data->requires_broadcast = !HaveSameShapes(input1, input2);
TfLiteIntArray* output_size = nullptr;
if (data->requires_broadcast) {
TF_LITE_ENSURE_OK(context, CalculateShapeForBroadcast(
context, input1, input2, &output_size));
} else {
output_size = TfLiteIntArrayCopy(input1->dims);
}
return context->ResizeTensor(context, output, output_size);
} | CWE-787 | 24 |
TfLiteStatus L2Eval(TfLiteContext* context, TfLiteNode* node) {
auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
OpData* data = reinterpret_cast<OpData*>(node->user_data);
TfLiteTensor* output = GetOutput(context, node, 0);
const TfLiteTensor* input = GetInput(context, node, 0);
switch (input->type) { // Already know in/out types are same.
case kTfLiteFloat32:
L2EvalFloat<kernel_type>(context, node, params, data, input, output);
break;
case kTfLiteUInt8:
// We don't have a quantized implementation, so just fall through to the
// 'default' case.
default:
context->ReportError(context, "Type %d not currently supported.",
input->type);
return kTfLiteError;
}
return kTfLiteOk;
} | CWE-125 | 47 |
TfLiteStatus PrepareHashtableSize(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input_resource_id_tensor =
GetInput(context, node, kInputResourceIdTensor);
TF_LITE_ENSURE_EQ(context, input_resource_id_tensor->type, kTfLiteInt32);
TF_LITE_ENSURE_EQ(context, NumDimensions(input_resource_id_tensor), 1);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(input_resource_id_tensor, 0), 1);
TfLiteTensor* output_tensor = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE(context, output_tensor != nullptr);
TF_LITE_ENSURE_EQ(context, output_tensor->type, kTfLiteInt64);
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(1);
outputSize->data[0] = 1;
return context->ResizeTensor(context, output_tensor, outputSize);
} | CWE-125 | 47 |
inline void StringData::setSize(int len) {
assertx(!isImmutable() && !hasMultipleRefs());
assertx(len >= 0 && len <= capacity());
mutableData()[len] = 0;
m_lenAndHash = len;
assertx(m_hash == 0);
assertx(checkSane());
} | CWE-125 | 47 |
Status CreateTempFile(Env* env, float value, uint64 size, string* filename) {
const string dir = testing::TmpDir();
*filename = io::JoinPath(dir, strings::StrCat("file_", value));
std::unique_ptr<WritableFile> file;
TF_RETURN_IF_ERROR(env->NewWritableFile(*filename, &file));
for (uint64 i = 0; i < size; ++i) {
StringPiece sp(static_cast<char*>(static_cast<void*>(&value)),
sizeof(value));
TF_RETURN_IF_ERROR(file->Append(sp));
}
TF_RETURN_IF_ERROR(file->Close());
return Status::OK();
} | CWE-125 | 47 |
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (!sz) {
return NULL;
}
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;
// if (buffer + offset > buffer + sz) return NULL;
attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
return attr;
} | CWE-805 | 63 |
int TLSOutStream::writeTLS(const U8* data, int length)
{
int n;
n = gnutls_record_send(session, data, length);
if (n == GNUTLS_E_INTERRUPTED || n == GNUTLS_E_AGAIN)
return 0;
if (n < 0)
throw TLSException("writeTLS", n);
return n;
} | CWE-787 | 24 |
bool PamBackend::start(const QString &user) {
bool result;
QString service = QStringLiteral("sddm");
if (user == QStringLiteral("sddm") && m_greeter)
service = QStringLiteral("sddm-greeter");
else if (m_app->session()->path().isEmpty())
service = QStringLiteral("sddm-check");
else if (m_autologin)
service = QStringLiteral("sddm-autologin");
result = m_pam->start(service, user);
if (!result)
m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL);
return result;
} | CWE-613 | 7 |
AuthenticationFeature::AuthenticationFeature(application_features::ApplicationServer& server)
: ApplicationFeature(server, "Authentication"),
_userManager(nullptr),
_authCache(nullptr),
_authenticationUnixSockets(true),
_authenticationSystemOnly(true),
_localAuthentication(true),
_active(true),
_authenticationTimeout(0.0) {
setOptional(false);
startsAfter<application_features::BasicFeaturePhaseServer>();
#ifdef USE_ENTERPRISE
startsAfter<LdapFeature>();
#endif
} | CWE-613 | 7 |
int FdInStream::pos()
{
return offset + ptr - start;
} | CWE-787 | 24 |
void fx_DataView(txMachine* the)
{
txSlot* slot;
txBoolean flag = 0;
txInteger offset, size;
txSlot* info;
txSlot* instance;
txSlot* view;
txSlot* buffer;
if (mxIsUndefined(mxTarget))
mxTypeError("call: DataView");
if ((mxArgc > 0) && (mxArgv(0)->kind == XS_REFERENCE_KIND)) {
slot = mxArgv(0)->value.reference->next;
if (slot && ((slot->kind == XS_ARRAY_BUFFER_KIND) || (slot->kind == XS_HOST_KIND))) {
flag = 1;
}
}
if (!flag)
mxTypeError("buffer is no ArrayBuffer instance");
offset = fxArgToByteLength(the, 1, 0);
info = fxGetBufferInfo(the, mxArgv(0));
if (info->value.bufferInfo.length < offset)
mxRangeError("out of range byteOffset %ld", offset);
size = fxArgToByteLength(the, 2, -1);
if (size >= 0) {
if (info->value.bufferInfo.length < (offset + size))
mxRangeError("out of range byteLength %ld", size);
}
else {
if (info->value.bufferInfo.maxLength < 0)
size = info->value.bufferInfo.length - offset;
}
mxPushSlot(mxTarget);
fxGetPrototypeFromConstructor(the, &mxDataViewPrototype);
instance = fxNewDataViewInstance(the);
mxPullSlot(mxResult);
view = instance->next;
buffer = view->next;
buffer->kind = XS_REFERENCE_KIND;
buffer->value.reference = mxArgv(0)->value.reference;
info = fxGetBufferInfo(the, buffer);
if (info->value.bufferInfo.maxLength >= 0) {
if (info->value.bufferInfo.length < offset)
mxRangeError("out of range byteOffset %ld", offset);
else if (size >= 0) {
if (info->value.bufferInfo.length < (offset + size))
mxRangeError("out of range byteLength %ld", size);
}
}
view->value.dataView.offset = offset;
view->value.dataView.size = size;
} | CWE-125 | 47 |
QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly)
{
QString mount_point = mountPoint(device);
if (!mount_point.isEmpty())
return mount_point;
mount_point = "%1/.%2/mount/%3";
const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
mount_point = mount_point.arg(tmp_paths.isEmpty() ? "/tmp" : tmp_paths.first()).arg(qApp->applicationName()).arg(name);
if (!QDir::current().mkpath(mount_point)) {
dCError("mkpath \"%s\" failed", qPrintable(mount_point));
return QString();
}
if (!mountDevice(device, mount_point, readonly)) {
dCError("Mount the device \"%s\" to \"%s\" failed", qPrintable(device), qPrintable(mount_point));
return QString();
}
return mount_point;
} | CWE-59 | 36 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
int num_inputs = NumInputs(node);
TF_LITE_ENSURE(context, num_inputs >= 2);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
output->type = input1->type;
// Check that all input tensors have the same shape and type.
for (int i = kInputTensor1 + 1; i < num_inputs; ++i) {
const TfLiteTensor* input = GetInput(context, node, i);
TF_LITE_ENSURE(context, HaveSameShapes(input1, input));
TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type);
}
// Use the first input node's dimension to be the dimension of the output
// node.
TfLiteIntArray* input1_dims = input1->dims;
TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims);
return context->ResizeTensor(context, output, output_dims);
} | CWE-125 | 47 |
TEST_F(ZNCTest, AwayNotify) {
auto znc = Run();
auto ircd = ConnectIRCd();
auto client = ConnectClient();
client.Write("CAP LS");
client.Write("PASS :hunter2");
client.Write("NICK nick");
client.Write("USER user/test x x :x");
QByteArray cap_ls;
client.ReadUntilAndGet(" LS :", cap_ls);
ASSERT_THAT(cap_ls.toStdString(), AllOf(HasSubstr("cap-notify"), Not(HasSubstr("away-notify"))));
client.Write("CAP REQ :cap-notify");
client.ReadUntil("ACK :cap-notify");
client.Write("CAP END");
client.ReadUntil(" 001 ");
ircd.ReadUntil("USER");
ircd.Write("CAP user LS :away-notify");
ircd.ReadUntil("CAP REQ :away-notify");
ircd.Write("CAP user ACK :away-notify");
ircd.ReadUntil("CAP END");
ircd.Write(":server 001 user :welcome");
client.ReadUntil("CAP user NEW :away-notify");
client.Write("CAP REQ :away-notify");
client.ReadUntil("ACK :away-notify");
ircd.Write(":x!y@z AWAY :reason");
client.ReadUntil(":x!y@z AWAY :reason");
ircd.Close();
client.ReadUntil("DEL :away-notify");
} | CWE-476 | 46 |
void operator()(OpKernelContext* ctx, const Index num_segments,
const TensorShape& segment_ids_shape,
typename TTypes<Index>::ConstFlat segment_ids,
const Index data_size, const T* data,
typename TTypes<T, 2>::Tensor output) {
if (output.size() == 0) {
return;
}
// Set 'output' to initial value.
GPUDevice d = ctx->template eigen_device<GPUDevice>();
GpuLaunchConfig config = GetGpuLaunchConfig(output.size(), d);
TF_CHECK_OK(GpuLaunchKernel(
SetToValue<T>, config.block_count, config.thread_per_block, 0,
d.stream(), output.size(), output.data(), InitialValueF()()));
if (data_size == 0 || segment_ids_shape.num_elements() == 0) {
return;
}
// Launch kernel to compute unsorted segment reduction.
// Notes:
// *) 'data_size' is the total number of elements to process.
// *) 'segment_ids.shape' is a prefix of data's shape.
// *) 'input_outer_dim_size' is the total number of segments to process.
const Index input_outer_dim_size = segment_ids.dimension(0);
const Index input_inner_dim_size = data_size / input_outer_dim_size;
config = GetGpuLaunchConfig(data_size, d);
TF_CHECK_OK(
GpuLaunchKernel(UnsortedSegmentCustomKernel<T, Index, ReductionF>,
config.block_count, config.thread_per_block, 0,
d.stream(), input_outer_dim_size, input_inner_dim_size,
num_segments, segment_ids.data(), data, output.data()));
} | CWE-681 | 59 |
inline void skip(int bytes) {
while (bytes > 0) {
int n = check(1, bytes);
ptr += n;
bytes -= n;
}
} | CWE-787 | 24 |
int FdInStream::readWithTimeoutOrCallback(void* buf, int len, bool wait)
{
struct timeval before, after;
if (timing)
gettimeofday(&before, 0);
int n;
while (true) {
do {
fd_set fds;
struct timeval tv;
struct timeval* tvp = &tv;
if (!wait) {
tv.tv_sec = tv.tv_usec = 0;
} else if (timeoutms != -1) {
tv.tv_sec = timeoutms / 1000;
tv.tv_usec = (timeoutms % 1000) * 1000;
} else {
tvp = 0;
}
FD_ZERO(&fds);
FD_SET(fd, &fds);
n = select(fd+1, &fds, 0, 0, tvp);
} while (n < 0 && errno == EINTR);
if (n > 0) break;
if (n < 0) throw SystemException("select",errno);
if (!wait) return 0;
if (!blockCallback) throw TimedOut();
blockCallback->blockCallback();
}
do {
n = ::recv(fd, (char*)buf, len, 0);
} while (n < 0 && errno == EINTR);
if (n < 0) throw SystemException("read",errno);
if (n == 0) throw EndOfStream();
if (timing) {
gettimeofday(&after, 0);
int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 +
(after.tv_usec - before.tv_usec) / 100);
int newKbits = n * 8 / 1000;
// limit rate to between 10kbit/s and 40Mbit/s
if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
timeWaitedIn100us += newTimeWaited;
timedKbits += newKbits;
}
return n;
} | CWE-787 | 24 |
void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
} | CWE-190 | 19 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 3);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 2);
const TfLiteTensor* lookup = GetInput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(lookup), 1);
TF_LITE_ENSURE_EQ(context, lookup->type, kTfLiteInt32);
const TfLiteTensor* key = GetInput(context, node, 1);
TF_LITE_ENSURE_EQ(context, NumDimensions(key), 1);
TF_LITE_ENSURE_EQ(context, key->type, kTfLiteInt32);
const TfLiteTensor* value = GetInput(context, node, 2);
TF_LITE_ENSURE(context, NumDimensions(value) >= 1);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(key, 0),
SizeOfDimension(value, 0));
if (value->type == kTfLiteString) {
TF_LITE_ENSURE_EQ(context, NumDimensions(value), 1);
}
TfLiteTensor* hits = GetOutput(context, node, 1);
TF_LITE_ENSURE_EQ(context, hits->type, kTfLiteUInt8);
TfLiteIntArray* hitSize = TfLiteIntArrayCreate(1);
hitSize->data[0] = SizeOfDimension(lookup, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_EQ(context, value->type, output->type);
TfLiteStatus status = kTfLiteOk;
if (output->type != kTfLiteString) {
TfLiteIntArray* outputSize = TfLiteIntArrayCreate(NumDimensions(value));
outputSize->data[0] = SizeOfDimension(lookup, 0);
for (int i = 1; i < NumDimensions(value); i++) {
outputSize->data[i] = SizeOfDimension(value, i);
}
status = context->ResizeTensor(context, output, outputSize);
}
if (context->ResizeTensor(context, hits, hitSize) != kTfLiteOk) {
status = kTfLiteError;
}
return status;
} | CWE-125 | 47 |
ALWAYS_INLINE String serialize_impl(const Variant& value,
const SerializeOptions& opts) {
switch (value.getType()) {
case KindOfClass:
case KindOfLazyClass:
case KindOfPersistentString:
case KindOfString: {
auto const str =
isStringType(value.getType()) ? value.getStringData() :
isClassType(value.getType()) ? classToStringHelper(value.toClassVal()) :
lazyClassToStringHelper(value.toLazyClassVal());
auto const size = str->size();
if (size >= RuntimeOption::MaxSerializedStringSize) {
throw Exception("Size of serialized string (%d) exceeds max", size);
}
StringBuffer sb;
sb.append("s:");
sb.append(size);
sb.append(":\"");
sb.append(str->data(), size);
sb.append("\";");
return sb.detach();
}
case KindOfResource:
return s_Res;
case KindOfUninit:
case KindOfNull:
case KindOfBoolean:
case KindOfInt64:
case KindOfFunc:
case KindOfPersistentVec:
case KindOfVec:
case KindOfPersistentDict:
case KindOfDict:
case KindOfPersistentKeyset:
case KindOfKeyset:
case KindOfPersistentDArray:
case KindOfDArray:
case KindOfPersistentVArray:
case KindOfVArray:
case KindOfDouble:
case KindOfObject:
case KindOfClsMeth:
case KindOfRClsMeth:
case KindOfRFunc:
case KindOfRecord:
break;
}
VariableSerializer vs(VariableSerializer::Type::Serialize);
if (opts.keepDVArrays) vs.keepDVArrays();
if (opts.forcePHPArrays) vs.setForcePHPArrays();
if (opts.warnOnHackArrays) vs.setHackWarn();
if (opts.warnOnPHPArrays) vs.setPHPWarn();
if (opts.ignoreLateInit) vs.setIgnoreLateInit();
if (opts.serializeProvenanceAndLegacy) vs.setSerializeProvenanceAndLegacy();
// Keep the count so recursive calls to serialize() embed references properly.
return vs.serialize(value, true, true);
} | CWE-787 | 24 |
NO_INLINE JsVar *jspeFactorDelete() {
JSP_ASSERT_MATCH(LEX_R_DELETE);
JsVar *parent = 0;
JsVar *a = jspeFactorMember(jspeFactor(), &parent);
JsVar *result = 0;
if (JSP_SHOULD_EXECUTE) {
bool ok = false;
if (jsvIsName(a) && !jsvIsNewChild(a)) {
// if no parent, check in root?
if (!parent && jsvIsChild(execInfo.root, a))
parent = jsvLockAgain(execInfo.root);
if (jsvHasChildren(parent)) {
// else remove properly.
if (jsvIsArray(parent)) {
// For arrays, we must make sure we don't change the length
JsVarInt l = jsvGetArrayLength(parent);
jsvRemoveChild(parent, a);
jsvSetArrayLength(parent, l, false);
} else {
jsvRemoveChild(parent, a);
}
ok = true;
}
}
result = jsvNewFromBool(ok);
}
jsvUnLock2(a, parent);
return result;
} | CWE-787 | 24 |
void test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
} | CWE-120 | 44 |
TfLiteStatus MockCustom::Invoke(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = tflite::GetInput(context, node, 0);
const int32_t* input_data = input->data.i32;
const TfLiteTensor* weight = tflite::GetInput(context, node, 1);
const uint8_t* weight_data = weight->data.uint8;
TfLiteTensor* output = GetOutput(context, node, 0);
int32_t* output_data = output->data.i32;
output_data[0] =
0; // Catch output tensor sharing memory with an input tensor
output_data[0] = input_data[0] + weight_data[0];
return kTfLiteOk;
} | CWE-125 | 47 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 5);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* ids = GetInput(context, node, 0);
TF_LITE_ENSURE_EQ(context, NumDimensions(ids), 1);
TF_LITE_ENSURE_EQ(context, ids->type, kTfLiteInt32);
const TfLiteTensor* indices = GetInput(context, node, 1);
TF_LITE_ENSURE_EQ(context, NumDimensions(indices), 2);
TF_LITE_ENSURE_EQ(context, indices->type, kTfLiteInt32);
const TfLiteTensor* shape = GetInput(context, node, 2);
TF_LITE_ENSURE_EQ(context, NumDimensions(shape), 1);
TF_LITE_ENSURE_EQ(context, shape->type, kTfLiteInt32);
const TfLiteTensor* weights = GetInput(context, node, 3);
TF_LITE_ENSURE_EQ(context, NumDimensions(weights), 1);
TF_LITE_ENSURE_EQ(context, weights->type, kTfLiteFloat32);
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(ids, 0));
TF_LITE_ENSURE_EQ(context, SizeOfDimension(indices, 0),
SizeOfDimension(weights, 0));
const TfLiteTensor* value = GetInput(context, node, 4);
TF_LITE_ENSURE(context, NumDimensions(value) >= 2);
// Mark the output as a dynamic tensor.
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_TYPES_EQ(context, output->type, kTfLiteFloat32);
output->allocation_type = kTfLiteDynamic;
return kTfLiteOk;
} | CWE-125 | 47 |
FdInStream::FdInStream(int fd_, int timeoutms_, int bufSize_,
bool closeWhenDone_)
: fd(fd_), closeWhenDone(closeWhenDone_),
timeoutms(timeoutms_), blockCallback(0),
timing(false), timeWaitedIn100us(5), timedKbits(0),
bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
{
ptr = end = start = new U8[bufSize];
} | CWE-787 | 24 |
TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) {
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type);
return context->ResizeTensor(context, output,
TfLiteIntArrayCopy(input->dims));
} | CWE-787 | 24 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
OpData* data = reinterpret_cast<OpData*>(node->user_data);
const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1);
const TfLiteTensor* input2 = GetInput(context, node, kInputTensor2);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteInt32: {
// TensorFlow does not support negative for int32.
TF_LITE_ENSURE_OK(context, CheckValue(context, input2));
PowImpl<int32_t>(input1, input2, output, data->requires_broadcast);
break;
}
case kTfLiteFloat32: {
PowImpl<float>(input1, input2, output, data->requires_broadcast);
break;
}
default: {
context->ReportError(context, "Unsupported data type: %d", output->type);
return kTfLiteError;
}
}
return kTfLiteOk;
} | CWE-787 | 24 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
output->type = input->type;
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_size);
} | CWE-125 | 47 |
absl::Status IsSupported(const TfLiteContext* context,
const TfLiteNode* tflite_node,
const TfLiteRegistration* registration) final {
if (mirror_pad_) {
const TfLiteMirrorPaddingParams* tf_options;
RETURN_IF_ERROR(RetrieveBuiltinData(tflite_node, &tf_options));
if (tf_options->mode !=
TfLiteMirrorPaddingMode::kTfLiteMirrorPaddingReflect) {
return absl::InvalidArgumentError(
"Only Reflective padding is supported for Mirror Pad operation.");
}
}
RETURN_IF_ERROR(CheckMaxSupportedOpVersion(registration, 2));
RETURN_IF_ERROR(CheckInputsOutputs(context, tflite_node,
/*runtime_inputs=*/1, /*outputs=*/1));
RETURN_IF_ERROR(CheckTensorIsAvailable(context, tflite_node, 1));
auto pad_tensor = tflite::GetInput(context, tflite_node, 1);
if (pad_tensor->dims->size != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor dimension: expected 2 dim, got ",
pad_tensor->dims->size, " dim"));
}
bool supported =
pad_tensor->dims->data[0] == 3 || pad_tensor->dims->data[0] == 4;
if (!supported || pad_tensor->dims->data[1] != 2) {
return absl::InvalidArgumentError(absl::StrCat(
"Invalid paddings tensor shape: expected 4x2 or 3x2, got ",
pad_tensor->dims->data[0], "x", pad_tensor->dims->data[1]));
}
return absl::OkStatus();
} | CWE-787 | 24 |
TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
const TfLiteTensor* input = GetInput(context, node, kInputTensor);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);
TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteFloat32);
output->type = input->type;
TfLiteIntArray* output_size = TfLiteIntArrayCopy(input->dims);
return context->ResizeTensor(context, output, output_size);
} | CWE-125 | 47 |
TfLiteTensor* GetOutput(TfLiteContext* context, const TfLiteNode* node,
int index) {
if (context->tensors != nullptr) {
return &context->tensors[node->outputs->data[index]];
} else {
return context->GetTensor(context, node->outputs->data[index]);
}
} | CWE-787 | 24 |
int GetU8 (int nPos, bool *pbSuccess)
{
//*pbSuccess = true;
if ( nPos < 0 || nPos >= m_nLen )
{
*pbSuccess = false;
return 0;
}
return m_sFile[ nPos ];
} | CWE-787 | 24 |
int FdOutStream::writeWithTimeout(const void* data, int length, int timeoutms)
{
int n;
do {
fd_set fds;
struct timeval tv;
struct timeval* tvp = &tv;
if (timeoutms != -1) {
tv.tv_sec = timeoutms / 1000;
tv.tv_usec = (timeoutms % 1000) * 1000;
} else {
tvp = NULL;
}
FD_ZERO(&fds);
FD_SET(fd, &fds);
n = select(fd+1, 0, &fds, 0, tvp);
} while (n < 0 && errno == EINTR);
if (n < 0)
throw SystemException("select", errno);
if (n == 0)
return 0;
do {
// select only guarantees that you can write SO_SNDLOWAT without
// blocking, which is normally 1. Use MSG_DONTWAIT to avoid
// blocking, when possible.
#ifndef MSG_DONTWAIT
n = ::send(fd, (const char*)data, length, 0);
#else
n = ::send(fd, (const char*)data, length, MSG_DONTWAIT);
#endif
} while (n < 0 && (errno == EINTR));
if (n < 0)
throw SystemException("write", errno);
gettimeofday(&lastWrite, NULL);
return n;
} | CWE-787 | 24 |
TfLiteStatus HardSwishEval(TfLiteContext* context, TfLiteNode* node) {
HardSwishData* data = static_cast<HardSwishData*>(node->user_data);
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output = GetOutput(context, node, 0);
switch (input->type) {
case kTfLiteFloat32: {
if (kernel_type == kReference) {
reference_ops::HardSwish(
GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
} else {
optimized_ops::HardSwish(
GetTensorShape(input), GetTensorData<float>(input),
GetTensorShape(output), GetTensorData<float>(output));
}
return kTfLiteOk;
} break;
case kTfLiteUInt8: {
HardSwishParams& params = data->params;
if (kernel_type == kReference) {
reference_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<uint8_t>(input),
GetTensorShape(output), GetTensorData<uint8_t>(output));
} else {
optimized_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<uint8_t>(input),
GetTensorShape(output), GetTensorData<uint8_t>(output));
}
return kTfLiteOk;
} break;
case kTfLiteInt8: {
HardSwishParams& params = data->params;
if (kernel_type == kReference) {
reference_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<int8_t>(input),
GetTensorShape(output), GetTensorData<int8_t>(output));
} else {
optimized_ops::HardSwish(
params, GetTensorShape(input), GetTensorData<int8_t>(input),
GetTensorShape(output), GetTensorData<int8_t>(output));
}
return kTfLiteOk;
} break;
default:
TF_LITE_KERNEL_LOG(
context,
"Only float32, uint8 and int8 are supported currently, got %s.",
TfLiteTypeGetName(input->type));
return kTfLiteError;
}
} | CWE-787 | 24 |
int FdOutStream::length()
{
return offset + ptr - sentUpTo;
} | CWE-787 | 24 |
static TfLiteRegistration DynamicCopyOpRegistration() {
TfLiteRegistration reg = {nullptr, nullptr, nullptr, nullptr};
reg.prepare = [](TfLiteContext* context, TfLiteNode* node) {
// Output 0 is dynamic
TfLiteTensor* output0 = GetOutput(context, node, 0);
SetTensorToDynamic(output0);
// Output 1 has the same shape as input.
const TfLiteTensor* input = GetInput(context, node, 0);
TfLiteTensor* output1 = GetOutput(context, node, 1);
TF_LITE_ENSURE_STATUS(context->ResizeTensor(
context, output1, TfLiteIntArrayCopy(input->dims)));
return kTfLiteOk;
};
reg.invoke = [](TfLiteContext* context, TfLiteNode* node) {
// Not implemented since this isn't required in testing.
return kTfLiteOk;
};
return reg;
} | CWE-125 | 47 |
inline int StringData::size() const { return m_len; } | CWE-787 | 24 |
static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream)
{
unsigned int header_len;
// The first field at the start of a level 3 header is supposed to
// indicate word size, with the idea being that the header format
// can be extended beyond 32-bit words in the future. In practise,
// nothing supports anything other than 32-bit (4 bytes), and neither
// do we.
if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) {
return 0;
}
// Read the full header.
if (!extend_raw_data(header, stream,
LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) {
return 0;
}
// Read the header length field (including extended headers), and
// extend to this full length. Because this is a 32-bit value,
// we must place a sensible limit on the amount of data that will
// be read, to avoid possibly allocating gigabytes of memory.
header_len = lha_decode_uint32(&RAW_DATA(header, 24));
if (header_len > LEVEL_3_MAX_HEADER_LEN) {
return 0;
}
if (!extend_raw_data(header, stream,
header_len - RAW_DATA_LEN(header))) {
return 0;
}
// Compression method:
memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5);
(*header)->compress_method[5] = '\0';
// File lengths:
(*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7));
(*header)->length = lha_decode_uint32(&RAW_DATA(header, 11));
// Unix-style timestamp.
(*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15));
// CRC.
(*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21));
// OS type:
(*header)->os_type = RAW_DATA(header, 23);
if (!decode_extended_headers(header, 28)) {
return 0;
}
return 1;
} | CWE-190 | 19 |
int64_t OutputFile::readImpl(char* /*buffer*/, int64_t /*length*/) {
raise_warning("cannot read from a php://output stream");
return -1;
} | CWE-125 | 47 |
TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
const TfLitePackParams* data =
reinterpret_cast<TfLitePackParams*>(node->builtin_data);
TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
switch (output->type) {
case kTfLiteFloat32: {
return PackImpl<float>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteUInt8: {
return PackImpl<uint8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt8: {
return PackImpl<int8_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt16: {
return PackImpl<int16_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt32: {
return PackImpl<int32_t>(context, node, output, data->values_count,
data->axis);
}
case kTfLiteInt64: {
return PackImpl<int64_t>(context, node, output, data->values_count,
data->axis);
}
default: {
context->ReportError(context, "Type '%s' is not supported by pack.",
TfLiteTypeGetName(output->type));
return kTfLiteError;
}
}
return kTfLiteOk;
} | CWE-787 | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.