cache.go 968 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package memloader
  2. import (
  3. "strings"
  4. "github.com/jchv/go-winloader/internal/loader"
  5. )
  6. // Cache implements a memory cache for PE modules.
  7. type Cache struct {
  8. next loader.Loader
  9. cache map[string]loader.Module
  10. }
  11. // NewCache creates a new cache with the specified options.
  12. func NewCache(next loader.Loader) *Cache {
  13. return &Cache{
  14. next: next,
  15. cache: make(map[string]loader.Module),
  16. }
  17. }
  18. // Load implements loader.Loader by loading from cache or falling back.
  19. func (c *Cache) Load(libname string) (loader.Module, error) {
  20. if m, ok := c.cache[strings.ToLower(libname)]; ok {
  21. return m, nil
  22. }
  23. if m, ok := c.cache[strings.ToLower(libname)+".dll"]; ok {
  24. return m, nil
  25. }
  26. return c.next.Load(libname)
  27. }
  28. // Add adds a module to the cache.
  29. func (c *Cache) Add(libname string, m loader.Module) error {
  30. libname = strings.ToLower(libname)
  31. if strings.HasSuffix(libname, ".dll") {
  32. libname = libname[0 : len(libname)-4]
  33. }
  34. c.cache[libname] = m
  35. return nil
  36. }