@@ -451,8 +451,9 @@ pub(crate) fn draw_text(
451451
452452/// Set an image localted in the guest memory as the draw target for all graphic operations.
453453pub ( crate ) fn set_canvas ( mut caller : C , ptr : u32 , len : u32 ) {
454- const HEADER : usize = 5 + 8 ;
455454 let state = caller. data_mut ( ) ;
455+ state. called = "graphics.set_canvas" ;
456+
456457 let Some ( memory) = state. memory else {
457458 state. log_error ( HostError :: MemoryNotFound ) ;
458459 return ;
@@ -465,6 +466,19 @@ pub(crate) fn set_canvas(mut caller: C, ptr: u32, len: u32) {
465466 state. log_error ( HostError :: OomPointer ) ;
466467 return ;
467468 } ;
469+ if image_bytes. len ( ) < 3 {
470+ state. log_error ( "canvas is too small" ) ;
471+ return ;
472+ }
473+ match image_bytes[ 0 ] {
474+ 0x21 => set_canvas_v1 ( state, ptr, len, image_bytes) ,
475+ 0x22 => set_canvas_v2 ( state, ptr, len, image_bytes) ,
476+ _ => state. log_error ( "invalid magic number" ) ,
477+ }
478+ }
479+
480+ fn set_canvas_v1 ( state : & mut Box < State < ' _ > > , ptr : u32 , len : u32 , image_bytes : & [ u8 ] ) {
481+ const HEADER : usize = 5 + 8 ;
468482 if image_bytes. len ( ) <= HEADER {
469483 state. log_error ( "canvas is too small" ) ;
470484 return ;
@@ -476,14 +490,25 @@ pub(crate) fn set_canvas(mut caller: C, ptr: u32, len: u32) {
476490 }
477491 let width = u16:: from_le_bytes ( [ image_bytes[ 2 ] , image_bytes[ 3 ] ] ) as u32 ;
478492 let image_bytes = & image_bytes[ HEADER ..] ;
479- if image_bytes. len ( ) * 2 % width as usize != 0 {
493+ if ! ( image_bytes. len ( ) * 2 ) . is_multiple_of ( width as usize ) {
480494 state. log_error ( HostError :: InvalidWidth ) ;
481495 return ;
482496 }
483497 let canvas = Canvas :: new ( ptr + HEADER as u32 , len - HEADER as u32 , width) ;
484498 state. canvas = Some ( canvas)
485499}
486500
501+ fn set_canvas_v2 ( state : & mut Box < State < ' _ > > , ptr : u32 , len : u32 , image_bytes : & [ u8 ] ) {
502+ let width = u16:: from_le_bytes ( [ image_bytes[ 1 ] , image_bytes[ 2 ] ] ) as u32 ;
503+ let image_bytes = & image_bytes[ 3 ..] ;
504+ if !( image_bytes. len ( ) * 2 ) . is_multiple_of ( width as usize ) {
505+ state. log_error ( HostError :: InvalidWidth ) ;
506+ return ;
507+ }
508+ let canvas = Canvas :: new ( ptr + 3 , len - 3 , width) ;
509+ state. canvas = Some ( canvas)
510+ }
511+
487512pub ( crate ) fn unset_canvas ( mut caller : C ) {
488513 let state = caller. data_mut ( ) ;
489514 state. called = "graphics.drop_canvas" ;
0 commit comments