Skip to content

buffer: buf.write(string, offset) with negative offset #27043

Description

@vsemozhetbyt

All other Node.js Buffer methods either support negative offsets or throw errors for all negative integers stating that offset must be >= 0.

However, buf.write(string, offset) does not check if an offset is negative, but just converts it to uint32:

offset = offset >>> 0;

This may cause some slightly confusing effects:

  1. If -offset is > -buffer.constants.MAX_LENGTH, this produces not so clear error:
'use strict';

const buf = Buffer.alloc(10);

try {
  const len = buf.write('a', -1);
  console.log(buf.indexOf('a'));
} catch (err) {
  console.error(err.toString());
}

// Prints: RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
  1. If -offset is < -buffer.constants.MAX_LENGTH, string can be written in an unexpected place:
'use strict';

const buf = Buffer.alloc(10);

try {
  const len = buf.write('a', -4294967296);
  console.log(buf.indexOf('a'));
} catch (err) {
  console.error(err);
}

// Prints: 0

So should the method check the sign before the converting?

Activity

  1. added
    bufferIssues and PRs related to the buffer subsystem.
    on Apr 1, 2019
  2. changed the title [-]buf.write(string, offset) with nagative offset[/-] [+]buffer: buf.write(string, offset) with nagative offset[/+] on Apr 1, 2019
  3. changed the title [-]buffer: buf.write(string, offset) with nagative offset[/-] [+]buffer: buf.write(string, offset) with negative offset[/+] on Apr 1, 2019
  4. BridgeAR commented on Apr 1, 2019

    @BridgeAR
    Member

    @vsemozhetbyt instead of checking for the sign, we could just use stricter input validation.

  5. added a commit that references this issue on Apr 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bufferIssues and PRs related to the buffer subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions