Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package checks;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class IntegerToLongTimestampCastCheckSample {

static final int INT_CONSTANT = 1234567890;

void noncompliantImplicitWidening() {
int intVar = 1000;
new Date(intVar); // Noncompliant {{Use a "long" value to represent this timestamp.}}
// ^^^^^^
Instant.ofEpochSecond(intVar); // Noncompliant
Instant.ofEpochMilli(intVar); // Noncompliant
new Timestamp(intVar); // Noncompliant
}

void noncompliantExplicitCast() {
int intVar = 1000;
new Date((long) intVar); // Noncompliant
Instant.ofEpochSecond((long) intVar); // Noncompliant
Instant.ofEpochMilli((long) intVar); // Noncompliant
new Timestamp((long) intVar); // Noncompliant
}

void noncompliantArithmeticOverflow() {
int days = 365;
new Date((long) (days * 24 * 60 * 60 * 1000)); // Noncompliant
}

void noncompliantCalendar() {
int intVar = 1000;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(intVar); // Noncompliant
cal.setTimeInMillis((long) intVar); // Noncompliant
}

void noncompliantGregorianCalendar() {
int intVar = 1000;
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(intVar); // Noncompliant
}

void noncompliantNarrowingCast() {
long longVar = 1234567890L;
new Date((int) longVar); // Noncompliant
}

void noncompliantOtherNarrowTypes() {
short shortVar = 100;
byte byteVar = 10;
char charVar = 'A';
new Date((long) shortVar); // Noncompliant
new Date((long) byteVar); // Noncompliant
new Date((long) charVar); // Noncompliant
}

void noncompliantMethodReturn() {
new Date(getSeconds()); // Noncompliant
}

void noncompliantIntConstant() {
Instant.ofEpochSecond(INT_CONSTANT); // Noncompliant
}

void noncompliantOfEpochSecondTwoArgs() {
int intVar = 1000;
Instant.ofEpochSecond(intVar, 0L); // Noncompliant
}

void noncompliantParenthesized() {
int intVar = 1000;
new Date((intVar)); // Noncompliant
}

void compliantIntLiteral() {
new Date(0);
new Date(-1);
new Date(+1);
new Date((long) (0));
}

void compliantLongVariable() {
long longVar = 1234567890L;
new Date(longVar);
Instant.ofEpochSecond(longVar);
Instant.ofEpochMilli(longVar);
new Timestamp(longVar);
}

void compliantCurrentTimeMillis() {
new Date(System.currentTimeMillis());
}

void compliantLongLiteral() {
new Date(1234567890L);
}

void compliantCalendar() {
long longVar = 1234567890L;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(longVar);
}

void compliantLongMethodReturn() {
new Date(getMillis());
}

void compliantNonTimestampCast() {
int intVar = 1000;
long result = (long) intVar;
}

int getSeconds() {
return 1000;
}

long getMillis() {
return System.currentTimeMillis();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.sonar.check.Rule;
import org.sonar.java.checks.methods.AbstractMethodDetection;
import org.sonar.java.model.ExpressionUtils;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.semantic.Type;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.NewClassTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TypeCastTree;
import org.sonar.plugins.java.api.tree.UnaryExpressionTree;

@Rule(key = "S9346")
public class IntegerToLongTimestampCastCheck extends AbstractMethodDetection {

private static final String MESSAGE = "Use a \"long\" value to represent this timestamp.";

private static final MethodMatchers CONSTRUCTOR_MATCHERS = MethodMatchers.or(
MethodMatchers.create()
.ofTypes("java.util.Date")
.constructor()
.addParametersMatcher("long")
.build(),
MethodMatchers.create()
.ofTypes("java.sql.Timestamp")
.constructor()
.addParametersMatcher("long")
.build());

private static final MethodMatchers METHOD_MATCHERS = MethodMatchers.or(
MethodMatchers.create()
.ofTypes("java.time.Instant")
.names("ofEpochSecond")
.addParametersMatcher("long")
.addParametersMatcher("long", "long")
.build(),
MethodMatchers.create()
.ofTypes("java.time.Instant")
.names("ofEpochMilli")
.addParametersMatcher("long")
.build(),
MethodMatchers.create()
.ofSubTypes("java.util.Calendar")
.names("setTimeInMillis")
.addParametersMatcher("long")
.build());

@Override
protected MethodMatchers getMethodInvocationMatchers() {
return MethodMatchers.or(CONSTRUCTOR_MATCHERS, METHOD_MATCHERS);
}

@Override
protected void onMethodInvocationFound(MethodInvocationTree mit) {
checkArgument(mit.arguments().get(0));
}

@Override
protected void onConstructorFound(NewClassTree nct) {
checkArgument(nct.arguments().get(0));
}

private void checkArgument(ExpressionTree argument) {
ExpressionTree arg = ExpressionUtils.skipParentheses(argument);
if (arg.is(Tree.Kind.TYPE_CAST)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve narrowing casts. This unwraps every TYPE_CAST, so new Date((int) millis) inspects millis as long and reports nothing, even though the argument has been truncated to int and then implicitly widened back to long. Only unwrap casts to long; otherwise inspect the cast expression type. Please add this case to the sample.

TypeCastTree cast = (TypeCastTree) arg;
Type castType = cast.type().symbolType();
if (castType.isPrimitive(Type.Primitives.LONG)) {
arg = ExpressionUtils.skipParentheses(cast.expression());
}
}
if (isIntegerLiteral(arg)) {
return;
}
Type type = arg.symbolType();
if (type.isUnknown()) {
return;
}
if (isNarrowIntegerType(type)) {
reportIssue(argument, MESSAGE);
}
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.

private static boolean isIntegerLiteral(ExpressionTree expression) {
if (expression.is(Tree.Kind.INT_LITERAL)) {
return true;
}
if (expression.is(Tree.Kind.UNARY_MINUS, Tree.Kind.UNARY_PLUS)) {
return ((UnaryExpressionTree) expression).expression().is(Tree.Kind.INT_LITERAL);
}
return false;
}

private static boolean isNarrowIntegerType(Type type) {
Comment thread
gitar-bot[bot] marked this conversation as resolved.
return type.isPrimitive(Type.Primitives.INT)
|| type.isPrimitive(Type.Primitives.SHORT)
|| type.isPrimitive(Type.Primitives.BYTE)
|| type.isPrimitive(Type.Primitives.CHAR);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class IntegerToLongTimestampCastCheckTest {

@Test
void test() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/IntegerToLongTimestampCastCheckSample.java"))
.withCheck(new IntegerToLongTimestampCastCheck())
.verifyIssues();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<p>Using 32-bit signed integer types for timestamps can lead to serious reliability issues such as incorrect time representation,
system failures, and the Year 2038 problem.</p>
<h2>Why is this an issue?</h2>
<p>A 32-bit signed integer can hold values from -2,147,483,648 to 2,147,483,647. While this might seem like a large range, it's insufficient for
representing timestamps:</p>
<ul>
<li><strong>Milliseconds since epoch</strong>: A 32-bit integer can only represent approximately 24.8 days of milliseconds. Any timestamp beyond
this range will overflow.</li>
<li><strong>Seconds since epoch</strong>: A 32-bit integer can represent about 68 years, covering dates from 1970 to 2038.</li>
</ul>
<p>When you cast a 32-bit integer to a 64-bit integer for use as a timestamp, you're not fixing the underlying problem &mdash; the value is already
corrupted or limited by the 32-bit constraint before the cast happens.</p>
<h3>Noncompliant code example</h3>
<pre data-diff-id="1" data-diff-type="noncompliant">
int timestamp = 1234567890;
Date date = new Date(timestamp); // Noncompliant — int implicitly widened
Date date2 = new Date((long) timestamp); // Noncompliant — cast doesn't fix overflow
</pre>
<h3>Compliant solution</h3>
<pre data-diff-id="1" data-diff-type="compliant">
long timestamp = 1234567890L;
Date date = new Date(timestamp);
Date date2 = new Date(timestamp);
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">Oracle Java Documentation - Primitive Data Types</a></li>
<li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/System.html#currentTimeMillis()">Oracle Java Documentation -
System.currentTimeMillis()</a></li>
<li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Instant.html">Oracle Java Documentation - Class Instant</a>
</li>
</ul>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"title": "Integer values should not be cast to long for use as timestamps",
"type": "BUG",
"code": {
"impacts": {
"RELIABILITY": "HIGH"
},
"attribute": "LOGICAL"
},
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": ["pitfall", "datetime"],
"defaultSeverity": "Critical",
"ruleSpecification": "RSPEC-9346",
"sqKey": "S9346",
"scope": "All",
"quickfix": "unknown"
}
Empty file.
Loading