Skip to content

ext/random: Optimized getBytes loop processing #14891

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
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
28 changes: 21 additions & 7 deletions ext/random/randomizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

#include "Zend/zend_enum.h"
#include "Zend/zend_exceptions.h"
#include "zend_portability.h"

static inline void randomizer_common_init(php_random_randomizer *randomizer, zend_object *engine_object) {
if (engine_object->ce->type == ZEND_INTERNAL_CLASS) {
Expand Down Expand Up @@ -278,7 +279,6 @@ PHP_METHOD(Random_Randomizer, getBytes)

zend_string *retval;
zend_long user_length;
size_t total_size = 0;

ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(user_length)
Expand All @@ -291,22 +291,36 @@ PHP_METHOD(Random_Randomizer, getBytes)

size_t length = (size_t)user_length;
retval = zend_string_alloc(length, 0);
char *rptr = ZSTR_VAL(retval);

while (total_size < length) {
size_t to_read = length;
while (to_read > 0) {
php_random_result result = engine.algo->generate(engine.state);
if (EG(exception)) {
zend_string_free(retval);
RETURN_THROWS();
}
for (size_t i = 0; i < result.size; i++) {
ZSTR_VAL(retval)[total_size++] = (result.result >> (i * 8)) & 0xff;
if (total_size >= length) {
break;
uint64_t tmp_ret = result.result;
if (to_read >= sizeof(uint64_t) && result.size == sizeof(uint64_t)) {
#ifdef WORDS_BIGENDIAN
tmp_ret = ZEND_BYTES_SWAP64(tmp_ret);
#endif
memcpy(rptr, &tmp_ret, sizeof(uint64_t));
to_read -= sizeof(uint64_t);
rptr += sizeof(uint64_t);
} else {
Copy link
Member Author

Choose a reason for hiding this comment

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

Is there a possibility that this else will be executed?

Copy link
Member

Choose a reason for hiding this comment

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

Yes. It can happen with userland engines that return single bytes:

final class MyEngine implements \Random\Engine {
  public function generate(): string { return 'x'; }
}

$r = new \Random\Randomizer(new MyEngine());

var_dump($r->getBytes(10));

for (size_t i = 0; i < result.size; i++) {
*rptr++ = tmp_ret & 0xff;
tmp_ret >>= 8;
to_read--;
if (to_read == 0) {
break;
}
}
}
}

ZSTR_VAL(retval)[length] = '\0';
*rptr = '\0';
RETURN_STR(retval);
}
/* }}} */
Expand Down
Loading