...
| Code Block |
|---|
|
final class Wrap {
private char[] dataArray;
public Wrap () {
dataArray = new char[10];
// initialize
}
public CharBuffer getBufferCopy() {
return CharBuffer.wrap(dataArray);
}
}
|
Noncompliant Code Example
Compliant Solution
This compliant solution returns a read-only view This noncompliant code example uses the duplicate() method to create and return a copy of the char array. The returned buffer allows the caller to indirectly , in the form of a CharBuffer. Attempts to modify the elements of the array CharBuffer result in a java.nio.ReadOnlyBufferException.
| Code Block |
|---|
|
final class Wrap {
private char[] dataArray;
public Wrap () {
dataArray = new char[10];
// initialize
}
public CharBuffer getBufferCopy() {
CharBuffer cb = CharBuffer.allocate(10);
return cb.duplicateasReadOnlyBuffer();
}
}
|
Compliant Solution
This compliant solution returns a read-only view allocates a new CharBuffer and explicitly inserts the contents of the char array, in the form of a CharBuffer. Attempts to modify the elements of the CharBuffer result in a java.nio.ReadOnlyBufferException.before returning it.
| Code Block |
|---|
|
final class Wrap {
private char[] dataArray;
Wrap () {
dataArray = new char[10];
// initialize
}
public CharBuffer getBufferCopy() {
CharBuffer cb = CharBuffer.allocate(10);
cb.put(dataArray);
return cb;
}
}
|
Noncompliant Code Example
This noncompliant code example uses the duplicate() method to create and return a copy of the CharBuffer. The returned buffer allows the caller to indirectly modify the elements of the original buffer.
| Code Block |
|---|
|
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// initialize
}
public CharBuffer getBufferCopy() {
return cb.duplicate();
}
}
|
If the CharBuffer obtained by the duplicate() method is based on a CharBuffer obtained by using the wrap() method, then the contents of the backing char array can be modified maliciously by modifying the particular CharBuffer.
Noncompliant Code Example
Creating a new CharBuffer, allocating it using allocate() and duplicating and storing another CharBuffer into it, does not prevent the contents of the duplicated buffer from being modified.
| Code Block |
|---|
|
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// initialize
}
public CharBuffer getBufferCopy() {
CharBuffer copy = CharBuffer.allocate(10);
copy = cb.duplicate();
return copy;
}
}
|
Compliant Solution
This compliant solution exposes a read-only view of the CharBuffer to untrusted code.
| Code Block |
|---|
|
final class Dup {
CharBuffer cb;
public Dup() {
cb = CharBuffer.allocate(10);
// initialize
}
public CharBuffer getBufferCopy() {
return cb.asReadOnlyBuffer();
}
}
|
...