@@ -278,19 +278,31 @@ void rustscript_repl_source() {
278278 delay (10 );
279279 continue ;
280280 }
281- String header = Serial.readStringUntil (' \n ' );
282- header.trim ();
283- if (header.length () == 0 ) {
284- continue ;
285- }
286- // Binary protocol
287- if (header.startsWith (REPL_MAGIC ) && header.length () == strlen (REPL_MAGIC ) + 8 ) {
288- const uint32_t program_len = *reinterpret_cast <const uint32_t *>(header.c_str () + 4 );
289- const uint32_t state_len = *reinterpret_cast <const uint32_t *>(header.c_str () + 8 );
281+ if (Serial.peek () == ' R' ) {
282+ uint8_t frame_header[REPL_FRAME_HEADER_SIZE ] = {};
283+ if (!read_serial_payload (frame_header, sizeof (frame_header))) {
284+ continue ;
285+ }
286+ if (std::memcmp (frame_header, REPL_REQUEST_MAGIC , 4 ) != 0 ) {
287+ Serial.println (" rss:error=invalid-repl-magic" );
288+ continue ;
289+ }
290+ uint32_t program_len = 0 ;
291+ uint32_t state_len = 0 ;
292+ std::memcpy (&program_len, frame_header + 4 , sizeof (program_len));
293+ std::memcpy (&state_len, frame_header + 8 , sizeof (state_len));
294+ if (program_len == 0 || state_len == 0 ||
295+ program_len > REPL_MAX_FRAME_SIZE || state_len > REPL_MAX_FRAME_SIZE ||
296+ program_len > REPL_MAX_FRAME_SIZE - state_len) {
297+ Serial.println (" rss:error=invalid-repl-length" );
298+ continue ;
299+ }
290300 uint8_t *program = read_serial_binary (program_len);
291- if (program == nullptr ) continue ;
292- uint8_t *state = state_len > 0 ? read_serial_binary (state_len) : nullptr ;
293- if (state_len > 0 && state == nullptr ) {
301+ if (program == nullptr ) {
302+ continue ;
303+ }
304+ uint8_t *state = read_serial_binary (state_len);
305+ if (state == nullptr ) {
294306 std::free (program);
295307 continue ;
296308 }
@@ -303,14 +315,24 @@ void rustscript_repl_source() {
303315 );
304316 std::free (program);
305317 std::free (state);
318+
319+ uint8_t response_header[REPL_FRAME_HEADER_SIZE ] = {};
320+ std::memcpy (response_header, REPL_RESPONSE_MAGIC , 4 );
321+ const uint32_t output_len = static_cast <uint32_t >(output.len );
322+ std::memcpy (response_header + 4 , &status, sizeof (status));
323+ std::memcpy (response_header + 8 , &output_len, sizeof (output_len));
324+ Serial.write (response_header, sizeof (response_header));
306325 if (output.len > 0 ) {
307- Serial.printf (" rss:%c%04x" , ' D' , static_cast <unsigned >(output.len ));
308326 Serial.write (output.data , output.len );
309327 rustscript_buffer_free (output);
310- } else {
311- Serial.printf (" rss:repl-status=%d\n " , static_cast <int >(status));
312328 }
313- Serial.print (" rss:pd-vm> " );
329+ Serial.flush ();
330+ continue ;
331+ }
332+
333+ String header = Serial.readStringUntil (' \n ' );
334+ header.trim ();
335+ if (header.length () == 0 ) {
314336 continue ;
315337 }
316338 // Legacy commands
0 commit comments