Skip to content
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

Add support for extracting an image. #568

Merged
merged 4 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion cmd/jag/commands/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func crashDecode(ctx context.Context, envelope string, backtrace string) error {
}
}

firmwareElf, err := ExtractFirmware(ctx, sdk, envelopePath, "elf")
firmwareElf, err := ExtractFirmware(ctx, sdk, envelopePath, "elf", nil)
if err != nil {
return err
}
Expand Down
57 changes: 57 additions & 0 deletions cmd/jag/commands/firmware.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func FirmwareCmd() *cobra.Command {
},
}
cmd.AddCommand(FirmwareUpdateCmd())
cmd.AddCommand(FirmwareExtractCmd())
cmd.Flags().StringP("device", "d", "", "use device with a given name, id, or address")
return cmd
}
Expand Down Expand Up @@ -111,3 +112,59 @@ func FirmwareUpdateCmd() *cobra.Command {
addFirmwareFlashFlags(cmd, "", "new name of the device, if given")
return cmd
}

func FirmwareExtractCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "extract [envelope]",
Short: "Build the firmware image of a Jaguar device",
Copy link
Member

Choose a reason for hiding this comment

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

Not sure if we typically end the short help with dots.

Suggested change
Short: "Build the firmware image of a Jaguar device",
Short: "Build the firmware image of a Jaguar device.",

Copy link
Member Author

Choose a reason for hiding this comment

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

We do in Toit, but not in Go...

Long: "Build the firmware image of a Jaguar device, for flashing, Wokwi, or QEMU." +
"\n" +
"Wokwi\n" +
"-----\n" +
"Remember to use the WiFi SSID \"Wokwi-GUEST\" without a password.\n" +
"You need a Club subscription to be able to connect to your device, but\n" +
"the device is able to reach the Internet without a subscription.\n" +
"\n" +
"To run the image go to https://wokwi.com/projects/new/esp32, then\n" +
"press F1 and run the command \"Upload Firmware and Start Simulation\".\n",
Args: cobra.MaximumNArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()

output, err := cmd.Flags().GetString("output")
if err != nil {
return err
}
if output == "" {
return fmt.Errorf("missing output file")
}

return withFirmware(cmd, args, nil, func(newID string, envelopeFile *os.File, config map[string]interface{}) error {

sdk, err := GetSDK(ctx)
if err != nil {
return err
}

imageFile, err := ExtractFirmware(ctx, sdk, envelopeFile.Name(), "image", config)
if err != nil {
return err
}
defer os.Remove(imageFile.Name())

imageBin, err := os.ReadFile(imageFile.Name())
if err != nil {
return err
}
Comment on lines +143 to +159
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Oh behave! The output validation isn't quite as groovy as we thought, baby!

Looking at the complete firmware command implementation, I can see that the output flag is already validated earlier in the code with a proper error message if it's empty. However, the suggestion to check write permissions is still totally shagadelic! But we should modify the approach slightly:

  • The unix package isn't imported or used anywhere in the codebase, yeah!
  • We should use Go's standard library instead for cross-platform compatibility, baby!
 return withFirmware(cmd, args, nil, func(newID string, envelopeFile *os.File, config map[string]interface{}) error {
+    // Verify output path is writable
+    outputDir := filepath.Dir(output)
+    if _, err := os.CreateTemp(outputDir, ""); err != nil {
+        return fmt.Errorf("Yeah baby, we can't write to output directory %s: %v", outputDir, err)
+    }
 
     sdk, err := GetSDK(ctx)
     if err != nil {
🔗 Analysis chain

Verify the output path before extraction, baby!

We should check if we can write to the output location before starting the extraction process. This would save time if the path is invalid or we don't have permissions.

 return withFirmware(cmd, args, nil, func(newID string, envelopeFile *os.File, config map[string]interface{}) error {
+    // Verify output path is writable
+    outputDir := filepath.Dir(output)
+    if err := unix.Access(outputDir, unix.W_OK); err != nil {
+        return fmt.Errorf("Oh no! Can't write to output directory %s: %v", outputDir, err)
+    }
 
     sdk, err := GetSDK(ctx)
     if err != nil {
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if similar validation exists in other commands
rg -A 3 "os.WriteFile.*0644" 

Length of output: 208


Script:

#!/bin/bash
# Let's see where this output variable comes from, baby!
rg -B 10 "output :=" cmd/jag/commands/firmware.go

# And check if there's any existing validation, yeah!
ast-grep --pattern 'if err := unix.Access($_, $_); err != nil { $$$ }'

Length of output: 124


Script:

#!/bin/bash
# Let's get groovy with the firmware command structure, baby!
cat cmd/jag/commands/firmware.go

# And let's see if we're using unix package anywhere else, yeah!
rg "unix\." -A 2

Length of output: 5133


return os.WriteFile(output, imageBin, 0644)
})
},
}

cmd.Flags().StringP("device", "d", "", "use device with a given name, id, or address")
addFirmwareFlashFlags(cmd, "esp32", "name of the device")
cmd.Flags().StringP("output", "o", "", "write the firmware image to a file")
return cmd
}
32 changes: 17 additions & 15 deletions cmd/jag/commands/firmware_flash.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,12 +246,12 @@ func ExtractFirmwareBin(ctx context.Context, sdk *SDK, envelopePath string, conf
return binaryFile, nil
}

func ExtractFirmware(ctx context.Context, sdk *SDK, envelopePath string, format string) (*os.File, error) {
func ExtractFirmware(ctx context.Context, sdk *SDK, envelopePath string, format string, config map[string]interface{}) (*os.File, error) {
outputFile, err := os.CreateTemp("", "firmware-"+format+".*")
if err != nil {
return nil, err
}
if err := runFirmwareTool(ctx, sdk, envelopePath, "extract", "--format", format, "-o", outputFile.Name()); err != nil {
if err := runFirmwareToolWithConfig(ctx, sdk, envelopePath, config, "extract", "--format", format, "-o", outputFile.Name()); err != nil {
outputFile.Close()
return nil, err
}
Expand All @@ -263,22 +263,24 @@ func setFirmwareProperty(ctx context.Context, sdk *SDK, envelope *os.File, key s
}

func runFirmwareToolWithConfig(ctx context.Context, sdk *SDK, envelopePath string, config map[string]interface{}, args ...string) error {
configFile, err := os.CreateTemp("", "*.json.config")
if err != nil {
return err
}
defer os.Remove(configFile.Name())
if config != nil {
configFile, err := os.CreateTemp("", "*.json.config")
if err != nil {
return err
}
defer os.Remove(configFile.Name())

configBytes, err := json.Marshal(config)
if err != nil {
return err
}
configBytes, err := json.Marshal(config)
if err != nil {
return err
}

if err := os.WriteFile(configFile.Name(), configBytes, 0666); err != nil {
return err
}
if err := os.WriteFile(configFile.Name(), configBytes, 0666); err != nil {
return err
}

args = append(args, "--config", configFile.Name())
args = append(args, "--config", configFile.Name())
}
return runFirmwareTool(ctx, sdk, envelopePath, args...)
}

Expand Down