python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2009, Wind River Systems Inc * Implemented by [email protected] and [email protected] */ #include <linux/export.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <asm/cacheflush.h> #include <asm/cpuinfo.h> static void __flush_dcache(unsigned long start, unsigned long end) { unsigned long addr; start &= ~(cpuinfo.dcache_line_size - 1); end += (cpuinfo.dcache_line_size - 1); end &= ~(cpuinfo.dcache_line_size - 1); if (end > start + cpuinfo.dcache_size) end = start + cpuinfo.dcache_size; for (addr = start; addr < end; addr += cpuinfo.dcache_line_size) { __asm__ __volatile__ (" flushd 0(%0)\n" : /* Outputs */ : /* Inputs */ "r"(addr) /* : No clobber */); } } static void __invalidate_dcache(unsigned long start, unsigned long end) { unsigned long addr; start &= ~(cpuinfo.dcache_line_size - 1); end += (cpuinfo.dcache_line_size - 1); end &= ~(cpuinfo.dcache_line_size - 1); for (addr = start; addr < end; addr += cpuinfo.dcache_line_size) { __asm__ __volatile__ (" initda 0(%0)\n" : /* Outputs */ : /* Inputs */ "r"(addr) /* : No clobber */); } } static void __flush_icache(unsigned long start, unsigned long end) { unsigned long addr; start &= ~(cpuinfo.icache_line_size - 1); end += (cpuinfo.icache_line_size - 1); end &= ~(cpuinfo.icache_line_size - 1); if (end > start + cpuinfo.icache_size) end = start + cpuinfo.icache_size; for (addr = start; addr < end; addr += cpuinfo.icache_line_size) { __asm__ __volatile__ (" flushi %0\n" : /* Outputs */ : /* Inputs */ "r"(addr) /* : No clobber */); } __asm__ __volatile(" flushp\n"); } static void flush_aliases(struct address_space *mapping, struct folio *folio) { struct mm_struct *mm = current->active_mm; struct vm_area_struct *vma; unsigned long flags; pgoff_t pgoff; unsigned long nr = folio_nr_pages(folio); pgoff = folio->index; flush_dcache_mmap_lock_irqsave(mapping, flags); vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff + nr - 1) { unsigned long start; if (vma->vm_mm != mm) continue; if (!(vma->vm_flags & VM_MAYSHARE)) continue; start = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT); flush_cache_range(vma, start, start + nr * PAGE_SIZE); } flush_dcache_mmap_unlock_irqrestore(mapping, flags); } void flush_cache_all(void) { __flush_dcache(0, cpuinfo.dcache_size); __flush_icache(0, cpuinfo.icache_size); } void flush_cache_mm(struct mm_struct *mm) { flush_cache_all(); } void flush_cache_dup_mm(struct mm_struct *mm) { flush_cache_all(); } void flush_icache_range(unsigned long start, unsigned long end) { __flush_dcache(start, end); __flush_icache(start, end); } void flush_dcache_range(unsigned long start, unsigned long end) { __flush_dcache(start, end); __flush_icache(start, end); } EXPORT_SYMBOL(flush_dcache_range); void invalidate_dcache_range(unsigned long start, unsigned long end) { __invalidate_dcache(start, end); } EXPORT_SYMBOL(invalidate_dcache_range); void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { __flush_dcache(start, end); if (vma == NULL || (vma->vm_flags & VM_EXEC)) __flush_icache(start, end); } void flush_icache_pages(struct vm_area_struct *vma, struct page *page, unsigned int nr) { unsigned long start = (unsigned long) page_address(page); unsigned long end = start + nr * PAGE_SIZE; __flush_dcache(start, end); __flush_icache(start, end); } void flush_cache_page(struct vm_area_struct *vma, unsigned long vmaddr, unsigned long pfn) { unsigned long start = vmaddr; unsigned long end = start + PAGE_SIZE; __flush_dcache(start, end); if (vma->vm_flags & VM_EXEC) __flush_icache(start, end); } static void __flush_dcache_folio(struct folio *folio) { /* * Writeback any data associated with the kernel mapping of this * page. This ensures that data in the physical page is mutually * coherent with the kernels mapping. */ unsigned long start = (unsigned long)folio_address(folio); __flush_dcache(start, start + folio_size(folio)); } void flush_dcache_folio(struct folio *folio) { struct address_space *mapping; /* * The zero page is never written to, so never has any dirty * cache lines, and therefore never needs to be flushed. */ if (is_zero_pfn(folio_pfn(folio))) return; mapping = folio_flush_mapping(folio); /* Flush this page if there are aliases. */ if (mapping && !mapping_mapped(mapping)) { clear_bit(PG_dcache_clean, &folio->flags); } else { __flush_dcache_folio(folio); if (mapping) { unsigned long start = (unsigned long)folio_address(folio); flush_aliases(mapping, folio); flush_icache_range(start, start + folio_size(folio)); } set_bit(PG_dcache_clean, &folio->flags); } } EXPORT_SYMBOL(flush_dcache_folio); void flush_dcache_page(struct page *page) { flush_dcache_folio(page_folio(page)); } EXPORT_SYMBOL(flush_dcache_page); void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma, unsigned long address, pte_t *ptep, unsigned int nr) { pte_t pte = *ptep; unsigned long pfn = pte_pfn(pte); struct folio *folio; struct address_space *mapping; reload_tlb_page(vma, address, pte); if (!pfn_valid(pfn)) return; /* * The zero page is never written to, so never has any dirty * cache lines, and therefore never needs to be flushed. */ if (is_zero_pfn(pfn)) return; folio = page_folio(pfn_to_page(pfn)); if (!test_and_set_bit(PG_dcache_clean, &folio->flags)) __flush_dcache_folio(folio); mapping = folio_flush_mapping(folio); if (mapping) { flush_aliases(mapping, folio); if (vma->vm_flags & VM_EXEC) flush_icache_pages(vma, &folio->page, folio_nr_pages(folio)); } } void copy_user_page(void *vto, void *vfrom, unsigned long vaddr, struct page *to) { __flush_dcache(vaddr, vaddr + PAGE_SIZE); __flush_icache(vaddr, vaddr + PAGE_SIZE); copy_page(vto, vfrom); __flush_dcache((unsigned long)vto, (unsigned long)vto + PAGE_SIZE); __flush_icache((unsigned long)vto, (unsigned long)vto + PAGE_SIZE); } void clear_user_page(void *addr, unsigned long vaddr, struct page *page) { __flush_dcache(vaddr, vaddr + PAGE_SIZE); __flush_icache(vaddr, vaddr + PAGE_SIZE); clear_page(addr); __flush_dcache((unsigned long)addr, (unsigned long)addr + PAGE_SIZE); __flush_icache((unsigned long)addr, (unsigned long)addr + PAGE_SIZE); } void copy_from_user_page(struct vm_area_struct *vma, struct page *page, unsigned long user_vaddr, void *dst, void *src, int len) { flush_cache_page(vma, user_vaddr, page_to_pfn(page)); memcpy(dst, src, len); __flush_dcache((unsigned long)src, (unsigned long)src + len); if (vma->vm_flags & VM_EXEC) __flush_icache((unsigned long)src, (unsigned long)src + len); } void copy_to_user_page(struct vm_area_struct *vma, struct page *page, unsigned long user_vaddr, void *dst, void *src, int len) { flush_cache_page(vma, user_vaddr, page_to_pfn(page)); memcpy(dst, src, len); __flush_dcache((unsigned long)dst, (unsigned long)dst + len); if (vma->vm_flags & VM_EXEC) __flush_icache((unsigned long)dst, (unsigned long)dst + len); }
linux-master
arch/nios2/mm/cacheflush.c
/* * Copyright (C) 2010 Tobias Klauser <[email protected]> * Copyright (C) 2009 Wind River Systems Inc * Implemented by [email protected] and [email protected] * Copyright (C) 2004 Microtronix Datacom Ltd. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/export.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/io.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> static inline void remap_area_pte(pte_t *pte, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; unsigned long pfn; pgprot_t pgprot = __pgprot(_PAGE_GLOBAL | _PAGE_PRESENT | _PAGE_READ | _PAGE_WRITE | flags); address &= ~PMD_MASK; end = address + size; if (end > PMD_SIZE) end = PMD_SIZE; if (address >= end) BUG(); pfn = PFN_DOWN(phys_addr); do { if (!pte_none(*pte)) { pr_err("remap_area_pte: page already exists\n"); BUG(); } set_pte(pte, pfn_pte(pfn, pgprot)); address += PAGE_SIZE; pfn++; pte++; } while (address && (address < end)); } static inline int remap_area_pmd(pmd_t *pmd, unsigned long address, unsigned long size, unsigned long phys_addr, unsigned long flags) { unsigned long end; address &= ~PGDIR_MASK; end = address + size; if (end > PGDIR_SIZE) end = PGDIR_SIZE; phys_addr -= address; if (address >= end) BUG(); do { pte_t *pte = pte_alloc_kernel(pmd, address); if (!pte) return -ENOMEM; remap_area_pte(pte, address, end - address, address + phys_addr, flags); address = (address + PMD_SIZE) & PMD_MASK; pmd++; } while (address && (address < end)); return 0; } static int remap_area_pages(unsigned long address, unsigned long phys_addr, unsigned long size, unsigned long flags) { int error; pgd_t *dir; unsigned long end = address + size; phys_addr -= address; dir = pgd_offset(&init_mm, address); flush_cache_all(); if (address >= end) BUG(); do { p4d_t *p4d; pud_t *pud; pmd_t *pmd; error = -ENOMEM; p4d = p4d_alloc(&init_mm, dir, address); if (!p4d) break; pud = pud_alloc(&init_mm, p4d, address); if (!pud) break; pmd = pmd_alloc(&init_mm, pud, address); if (!pmd) break; if (remap_area_pmd(pmd, address, end - address, phys_addr + address, flags)) break; error = 0; address = (address + PGDIR_SIZE) & PGDIR_MASK; dir++; } while (address && (address < end)); flush_tlb_all(); return error; } #define IS_MAPPABLE_UNCACHEABLE(addr) (addr < 0x20000000UL) /* * Map some physical address range into the kernel address space. */ void __iomem *ioremap(unsigned long phys_addr, unsigned long size) { struct vm_struct *area; unsigned long offset; unsigned long last_addr; void *addr; /* Don't allow wraparound or zero size */ last_addr = phys_addr + size - 1; if (!size || last_addr < phys_addr) return NULL; /* Don't allow anybody to remap normal RAM that we're using */ if (phys_addr > PHYS_OFFSET && phys_addr < virt_to_phys(high_memory)) { char *t_addr, *t_end; struct page *page; t_addr = __va(phys_addr); t_end = t_addr + (size - 1); for (page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++) if (!PageReserved(page)) return NULL; } /* * Map uncached objects in the low part of address space to * CONFIG_NIOS2_IO_REGION_BASE */ if (IS_MAPPABLE_UNCACHEABLE(phys_addr) && IS_MAPPABLE_UNCACHEABLE(last_addr)) return (void __iomem *)(CONFIG_NIOS2_IO_REGION_BASE + phys_addr); /* Mappings have to be page-aligned */ offset = phys_addr & ~PAGE_MASK; phys_addr &= PAGE_MASK; size = PAGE_ALIGN(last_addr + 1) - phys_addr; /* Ok, go for it */ area = get_vm_area(size, VM_IOREMAP); if (!area) return NULL; addr = area->addr; if (remap_area_pages((unsigned long) addr, phys_addr, size, 0)) { vunmap(addr); return NULL; } return (void __iomem *) (offset + (char *)addr); } EXPORT_SYMBOL(ioremap); /* * iounmap unmaps nearly everything, so be careful * it doesn't free currently pointer/page tables anymore but it * wasn't used anyway and might be added later. */ void iounmap(void __iomem *addr) { struct vm_struct *p; if ((unsigned long) addr > CONFIG_NIOS2_IO_REGION_BASE) return; p = remove_vm_area((void *) (PAGE_MASK & (unsigned long __force) addr)); if (!p) pr_err("iounmap: bad address %p\n", addr); kfree(p); } EXPORT_SYMBOL(iounmap);
linux-master
arch/nios2/mm/ioremap.c
/* * Copyright (C) 2009 Wind River Systems Inc * Implemented by [email protected] and [email protected] * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/mm.h> #include <linux/sched.h> #include <asm/cpuinfo.h> /* pteaddr: * ptbase | vpn* | zero * 31-22 | 21-2 | 1-0 * * *vpn is preserved on double fault * * tlbacc: * IG |*flags| pfn * 31-25|24-20 | 19-0 * * *crwxg * * tlbmisc: * resv |way |rd | we|pid |dbl|bad|perm|d * 31-24 |23-20 |19 | 20|17-4|3 |2 |1 |0 * */ /* * Initialize a new pgd / pmd table with invalid pointers. */ static void pgd_init(pgd_t *pgd) { unsigned long *p = (unsigned long *) pgd; int i; for (i = 0; i < USER_PTRS_PER_PGD; i += 8) { p[i + 0] = (unsigned long) invalid_pte_table; p[i + 1] = (unsigned long) invalid_pte_table; p[i + 2] = (unsigned long) invalid_pte_table; p[i + 3] = (unsigned long) invalid_pte_table; p[i + 4] = (unsigned long) invalid_pte_table; p[i + 5] = (unsigned long) invalid_pte_table; p[i + 6] = (unsigned long) invalid_pte_table; p[i + 7] = (unsigned long) invalid_pte_table; } } pgd_t *pgd_alloc(struct mm_struct *mm) { pgd_t *ret, *init; ret = (pgd_t *) __get_free_page(GFP_KERNEL); if (ret) { init = pgd_offset(&init_mm, 0UL); pgd_init(ret); memcpy(ret + USER_PTRS_PER_PGD, init + USER_PTRS_PER_PGD, (PTRS_PER_PGD - USER_PTRS_PER_PGD) * sizeof(pgd_t)); } return ret; } void __init pagetable_init(void) { /* Initialize the entire pgd. */ pgd_init(swapper_pg_dir); pgd_init(swapper_pg_dir + USER_PTRS_PER_PGD); }
linux-master
arch/nios2/mm/pgtable.c
/* * Copyright (C) 2009 Wind River Systems Inc * Implemented by [email protected] and [email protected] * * based on arch/mips/mm/fault.c which is: * * Copyright (C) 1995-2000 Ralf Baechle * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/signal.h> #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/types.h> #include <linux/ptrace.h> #include <linux/mman.h> #include <linux/mm.h> #include <linux/extable.h> #include <linux/uaccess.h> #include <linux/perf_event.h> #include <asm/mmu_context.h> #include <asm/traps.h> #define EXC_SUPERV_INSN_ACCESS 9 /* Supervisor only instruction address */ #define EXC_SUPERV_DATA_ACCESS 11 /* Supervisor only data address */ #define EXC_X_PROTECTION_FAULT 13 /* TLB permission violation (x) */ #define EXC_R_PROTECTION_FAULT 14 /* TLB permission violation (r) */ #define EXC_W_PROTECTION_FAULT 15 /* TLB permission violation (w) */ /* * This routine handles page faults. It determines the address, * and the problem, and then passes it off to one of the appropriate * routines. */ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long cause, unsigned long address) { struct vm_area_struct *vma = NULL; struct task_struct *tsk = current; struct mm_struct *mm = tsk->mm; int code = SEGV_MAPERR; vm_fault_t fault; unsigned int flags = FAULT_FLAG_DEFAULT; cause >>= 2; /* Restart the instruction */ regs->ea -= 4; /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. */ if (unlikely(address >= VMALLOC_START && address <= VMALLOC_END)) { if (user_mode(regs)) goto bad_area_nosemaphore; else goto vmalloc_fault; } if (unlikely(address >= TASK_SIZE)) goto bad_area_nosemaphore; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (faulthandler_disabled() || !mm) goto bad_area_nosemaphore; if (user_mode(regs)) flags |= FAULT_FLAG_USER; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address); retry: vma = lock_mm_and_find_vma(mm, address, regs); if (!vma) goto bad_area_nosemaphore; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ code = SEGV_ACCERR; switch (cause) { case EXC_SUPERV_INSN_ACCESS: goto bad_area; case EXC_SUPERV_DATA_ACCESS: goto bad_area; case EXC_X_PROTECTION_FAULT: if (!(vma->vm_flags & VM_EXEC)) goto bad_area; break; case EXC_R_PROTECTION_FAULT: if (!(vma->vm_flags & VM_READ)) goto bad_area; break; case EXC_W_PROTECTION_FAULT: if (!(vma->vm_flags & VM_WRITE)) goto bad_area; flags = FAULT_FLAG_WRITE; break; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(vma, address, flags, regs); if (fault_signal_pending(fault, regs)) { if (!user_mode(regs)) goto no_context; return; } /* The fault is fully completed (including releasing mmap lock) */ if (fault & VM_FAULT_COMPLETED) return; if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGSEGV) goto bad_area; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (fault & VM_FAULT_RETRY) { flags |= FAULT_FLAG_TRIED; /* * No need to mmap_read_unlock(mm) as we would * have already released it in __lock_page_or_retry * in mm/filemap.c. */ goto retry; } mmap_read_unlock(mm); return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: mmap_read_unlock(mm); bad_area_nosemaphore: /* User mode accesses just cause a SIGSEGV */ if (user_mode(regs)) { if (unhandled_signal(current, SIGSEGV) && printk_ratelimit()) { pr_info("%s: unhandled page fault (%d) at 0x%08lx, " "cause %ld\n", current->comm, SIGSEGV, address, cause); show_regs(regs); } _exception(SIGSEGV, regs, code, address); return; } no_context: /* Are we prepared to handle this kernel fault? */ if (fixup_exception(regs)) return; /* * Oops. The kernel tried to access some bad page. We'll have to * terminate things with extreme prejudice. */ bust_spinlocks(1); pr_alert("Unable to handle kernel %s at virtual address %08lx", address < PAGE_SIZE ? "NULL pointer dereference" : "paging request", address); pr_alert("ea = %08lx, ra = %08lx, cause = %ld\n", regs->ea, regs->ra, cause); panic("Oops"); return; /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: mmap_read_unlock(mm); if (!user_mode(regs)) goto no_context; pagefault_out_of_memory(); return; do_sigbus: mmap_read_unlock(mm); /* Kernel mode? Handle exceptions or die */ if (!user_mode(regs)) goto no_context; _exception(SIGBUS, regs, BUS_ADRERR, address); return; vmalloc_fault: { /* * Synchronize this task's top level page-table * with the 'reference' page table. * * Do _not_ use "tsk" here. We might be inside * an interrupt in the middle of a task switch.. */ int offset = pgd_index(address); pgd_t *pgd, *pgd_k; p4d_t *p4d, *p4d_k; pud_t *pud, *pud_k; pmd_t *pmd, *pmd_k; pte_t *pte_k; pgd = pgd_current + offset; pgd_k = init_mm.pgd + offset; if (!pgd_present(*pgd_k)) goto no_context; set_pgd(pgd, *pgd_k); p4d = p4d_offset(pgd, address); p4d_k = p4d_offset(pgd_k, address); if (!p4d_present(*p4d_k)) goto no_context; pud = pud_offset(p4d, address); pud_k = pud_offset(p4d_k, address); if (!pud_present(*pud_k)) goto no_context; pmd = pmd_offset(pud, address); pmd_k = pmd_offset(pud_k, address); if (!pmd_present(*pmd_k)) goto no_context; set_pmd(pmd, *pmd_k); pte_k = pte_offset_kernel(pmd_k, address); if (!pte_present(*pte_k)) goto no_context; flush_tlb_kernel_page(address); return; } }
linux-master
arch/nios2/mm/fault.c
/* * Nios2 TLB handling * * Copyright (C) 2009, Wind River Systems Inc * Implemented by [email protected] and [email protected] * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <asm/tlb.h> #include <asm/mmu_context.h> #include <asm/cpuinfo.h> #define TLB_INDEX_MASK \ ((((1UL << (cpuinfo.tlb_ptr_sz - cpuinfo.tlb_num_ways_log2))) - 1) \ << PAGE_SHIFT) static void get_misc_and_pid(unsigned long *misc, unsigned long *pid) { *misc = RDCTL(CTL_TLBMISC); *misc &= (TLBMISC_PID | TLBMISC_WAY); *pid = *misc & TLBMISC_PID; } /* * This provides a PTEADDR value for addr that will cause a TLB miss * (fast TLB miss). TLB invalidation replaces entries with this value. */ static unsigned long pteaddr_invalid(unsigned long addr) { return ((addr | 0xC0000000UL) >> PAGE_SHIFT) << 2; } /* * This one is only used for pages with the global bit set so we don't care * much about the ASID. */ static void replace_tlb_one_pid(unsigned long addr, unsigned long mmu_pid, unsigned long tlbacc) { unsigned int way; unsigned long org_misc, pid_misc; /* remember pid/way until we return. */ get_misc_and_pid(&org_misc, &pid_misc); WRCTL(CTL_PTEADDR, (addr >> PAGE_SHIFT) << 2); for (way = 0; way < cpuinfo.tlb_num_ways; way++) { unsigned long pteaddr; unsigned long tlbmisc; unsigned long pid; tlbmisc = TLBMISC_RD | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); pteaddr = RDCTL(CTL_PTEADDR); if (((pteaddr >> 2) & 0xfffff) != (addr >> PAGE_SHIFT)) continue; tlbmisc = RDCTL(CTL_TLBMISC); pid = (tlbmisc >> TLBMISC_PID_SHIFT) & TLBMISC_PID_MASK; if (pid != mmu_pid) continue; tlbmisc = (mmu_pid << TLBMISC_PID_SHIFT) | TLBMISC_WE | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); if (tlbacc == 0) WRCTL(CTL_PTEADDR, pteaddr_invalid(addr)); WRCTL(CTL_TLBACC, tlbacc); /* * There should be only a single entry that maps a * particular {address,pid} so break after a match. */ break; } WRCTL(CTL_TLBMISC, org_misc); } static void flush_tlb_one_pid(unsigned long addr, unsigned long mmu_pid) { pr_debug("Flush tlb-entry for vaddr=%#lx\n", addr); replace_tlb_one_pid(addr, mmu_pid, 0); } static void reload_tlb_one_pid(unsigned long addr, unsigned long mmu_pid, pte_t pte) { pr_debug("Reload tlb-entry for vaddr=%#lx\n", addr); replace_tlb_one_pid(addr, mmu_pid, pte_val(pte)); } void flush_tlb_range(struct vm_area_struct *vma, unsigned long start, unsigned long end) { unsigned long mmu_pid = get_pid_from_context(&vma->vm_mm->context); while (start < end) { flush_tlb_one_pid(start, mmu_pid); start += PAGE_SIZE; } } void reload_tlb_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte) { unsigned long mmu_pid = get_pid_from_context(&vma->vm_mm->context); reload_tlb_one_pid(addr, mmu_pid, pte); } /* * This one is only used for pages with the global bit set so we don't care * much about the ASID. */ static void flush_tlb_one(unsigned long addr) { unsigned int way; unsigned long org_misc, pid_misc; pr_debug("Flush tlb-entry for vaddr=%#lx\n", addr); /* remember pid/way until we return. */ get_misc_and_pid(&org_misc, &pid_misc); WRCTL(CTL_PTEADDR, (addr >> PAGE_SHIFT) << 2); for (way = 0; way < cpuinfo.tlb_num_ways; way++) { unsigned long pteaddr; unsigned long tlbmisc; tlbmisc = TLBMISC_RD | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); pteaddr = RDCTL(CTL_PTEADDR); if (((pteaddr >> 2) & 0xfffff) != (addr >> PAGE_SHIFT)) continue; pr_debug("Flush entry by writing way=%dl pid=%ld\n", way, (pid_misc >> TLBMISC_PID_SHIFT)); tlbmisc = TLBMISC_WE | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); WRCTL(CTL_PTEADDR, pteaddr_invalid(addr)); WRCTL(CTL_TLBACC, 0); } WRCTL(CTL_TLBMISC, org_misc); } void flush_tlb_kernel_range(unsigned long start, unsigned long end) { while (start < end) { flush_tlb_one(start); start += PAGE_SIZE; } } void dump_tlb_line(unsigned long line) { unsigned int way; unsigned long org_misc; pr_debug("dump tlb-entries for line=%#lx (addr %08lx)\n", line, line << (PAGE_SHIFT + cpuinfo.tlb_num_ways_log2)); /* remember pid/way until we return */ org_misc = (RDCTL(CTL_TLBMISC) & (TLBMISC_PID | TLBMISC_WAY)); WRCTL(CTL_PTEADDR, line << 2); for (way = 0; way < cpuinfo.tlb_num_ways; way++) { unsigned long pteaddr; unsigned long tlbmisc; unsigned long tlbacc; WRCTL(CTL_TLBMISC, TLBMISC_RD | (way << TLBMISC_WAY_SHIFT)); pteaddr = RDCTL(CTL_PTEADDR); tlbmisc = RDCTL(CTL_TLBMISC); tlbacc = RDCTL(CTL_TLBACC); if ((tlbacc << PAGE_SHIFT) != 0) { pr_debug("-- way:%02x vpn:0x%08lx phys:0x%08lx pid:0x%02lx flags:%c%c%c%c%c\n", way, (pteaddr << (PAGE_SHIFT-2)), (tlbacc << PAGE_SHIFT), ((tlbmisc >> TLBMISC_PID_SHIFT) & TLBMISC_PID_MASK), (tlbacc & _PAGE_READ ? 'r' : '-'), (tlbacc & _PAGE_WRITE ? 'w' : '-'), (tlbacc & _PAGE_EXEC ? 'x' : '-'), (tlbacc & _PAGE_GLOBAL ? 'g' : '-'), (tlbacc & _PAGE_CACHED ? 'c' : '-')); } } WRCTL(CTL_TLBMISC, org_misc); } void dump_tlb(void) { unsigned int i; for (i = 0; i < cpuinfo.tlb_num_lines; i++) dump_tlb_line(i); } void flush_tlb_pid(unsigned long mmu_pid) { unsigned long addr = 0; unsigned int line; unsigned int way; unsigned long org_misc, pid_misc; /* remember pid/way until we return */ get_misc_and_pid(&org_misc, &pid_misc); for (line = 0; line < cpuinfo.tlb_num_lines; line++) { WRCTL(CTL_PTEADDR, pteaddr_invalid(addr)); for (way = 0; way < cpuinfo.tlb_num_ways; way++) { unsigned long tlbmisc; unsigned long pid; tlbmisc = TLBMISC_RD | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); tlbmisc = RDCTL(CTL_TLBMISC); pid = (tlbmisc >> TLBMISC_PID_SHIFT) & TLBMISC_PID_MASK; if (pid != mmu_pid) continue; tlbmisc = TLBMISC_WE | (way << TLBMISC_WAY_SHIFT); WRCTL(CTL_TLBMISC, tlbmisc); WRCTL(CTL_TLBACC, 0); } addr += PAGE_SIZE; } WRCTL(CTL_TLBMISC, org_misc); } /* * All entries common to a mm share an asid. To effectively flush these * entries, we just bump the asid. */ void flush_tlb_mm(struct mm_struct *mm) { if (current->mm == mm) { unsigned long mmu_pid = get_pid_from_context(&mm->context); flush_tlb_pid(mmu_pid); } else { memset(&mm->context, 0, sizeof(mm_context_t)); } } void flush_tlb_all(void) { unsigned long addr = 0; unsigned int line; unsigned int way; unsigned long org_misc, pid_misc; /* remember pid/way until we return */ get_misc_and_pid(&org_misc, &pid_misc); /* Start at way 0, way is auto-incremented after each TLBACC write */ WRCTL(CTL_TLBMISC, TLBMISC_WE); /* Map each TLB entry to physcal address 0 with no-access and a bad ptbase */ for (line = 0; line < cpuinfo.tlb_num_lines; line++) { WRCTL(CTL_PTEADDR, pteaddr_invalid(addr)); for (way = 0; way < cpuinfo.tlb_num_ways; way++) WRCTL(CTL_TLBACC, 0); addr += PAGE_SIZE; } /* restore pid/way */ WRCTL(CTL_TLBMISC, org_misc); } void set_mmu_pid(unsigned long pid) { unsigned long tlbmisc; tlbmisc = RDCTL(CTL_TLBMISC); tlbmisc = (tlbmisc & TLBMISC_WAY); tlbmisc |= (pid & TLBMISC_PID_MASK) << TLBMISC_PID_SHIFT; WRCTL(CTL_TLBMISC, tlbmisc); }
linux-master
arch/nios2/mm/tlb.c
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2009, Wind River Systems Inc * Implemented by [email protected] and [email protected] */ #include <linux/export.h> #include <linux/uaccess.h> asm(".global raw_copy_from_user\n" " .type raw_copy_from_user, @function\n" "raw_copy_from_user:\n" " movi r2,7\n" " mov r3,r4\n" " bge r2,r6,1f\n" " xor r2,r4,r5\n" " andi r2,r2,3\n" " movi r7,3\n" " beq r2,zero,4f\n" "1: addi r6,r6,-1\n" " movi r2,-1\n" " beq r6,r2,3f\n" " mov r7,r2\n" "2: ldbu r2,0(r5)\n" " addi r6,r6,-1\n" " addi r5,r5,1\n" " stb r2,0(r3)\n" " addi r3,r3,1\n" " bne r6,r7,2b\n" "3:\n" " addi r2,r6,1\n" " ret\n" "13:mov r2,r6\n" " ret\n" "4: andi r2,r4,1\n" " cmpeq r2,r2,zero\n" " beq r2,zero,7f\n" "5: andi r2,r3,2\n" " beq r2,zero,6f\n" "9: ldhu r2,0(r5)\n" " addi r6,r6,-2\n" " addi r5,r5,2\n" " sth r2,0(r3)\n" " addi r3,r3,2\n" "6: bge r7,r6,1b\n" "10:ldw r2,0(r5)\n" " addi r6,r6,-4\n" " addi r5,r5,4\n" " stw r2,0(r3)\n" " addi r3,r3,4\n" " br 6b\n" "7: ldbu r2,0(r5)\n" " addi r6,r6,-1\n" " addi r5,r5,1\n" " addi r3,r4,1\n" " stb r2,0(r4)\n" " br 5b\n" ".section __ex_table,\"a\"\n" ".word 2b,3b\n" ".word 9b,13b\n" ".word 10b,13b\n" ".word 7b,13b\n" ".previous\n" ); EXPORT_SYMBOL(raw_copy_from_user); asm( " .global raw_copy_to_user\n" " .type raw_copy_to_user, @function\n" "raw_copy_to_user:\n" " movi r2,7\n" " mov r3,r4\n" " bge r2,r6,1f\n" " xor r2,r4,r5\n" " andi r2,r2,3\n" " movi r7,3\n" " beq r2,zero,4f\n" /* Bail if we try to copy zero bytes */ "1: addi r6,r6,-1\n" " movi r2,-1\n" " beq r6,r2,3f\n" /* Copy byte by byte for small copies and if src^dst != 0 */ " mov r7,r2\n" "2: ldbu r2,0(r5)\n" " addi r5,r5,1\n" "9: stb r2,0(r3)\n" " addi r6,r6,-1\n" " addi r3,r3,1\n" " bne r6,r7,2b\n" "3: addi r2,r6,1\n" " ret\n" "13:mov r2,r6\n" " ret\n" /* If 'to' is an odd address byte copy */ "4: andi r2,r4,1\n" " cmpeq r2,r2,zero\n" " beq r2,zero,7f\n" /* If 'to' is not divideable by four copy halfwords */ "5: andi r2,r3,2\n" " beq r2,zero,6f\n" " ldhu r2,0(r5)\n" " addi r5,r5,2\n" "10:sth r2,0(r3)\n" " addi r6,r6,-2\n" " addi r3,r3,2\n" /* Copy words */ "6: bge r7,r6,1b\n" " ldw r2,0(r5)\n" " addi r5,r5,4\n" "11:stw r2,0(r3)\n" " addi r6,r6,-4\n" " addi r3,r3,4\n" " br 6b\n" /* Copy remaining bytes */ "7: ldbu r2,0(r5)\n" " addi r5,r5,1\n" " addi r3,r4,1\n" "12: stb r2,0(r4)\n" " addi r6,r6,-1\n" " br 5b\n" ".section __ex_table,\"a\"\n" ".word 9b,3b\n" ".word 10b,13b\n" ".word 11b,13b\n" ".word 12b,13b\n" ".previous\n"); EXPORT_SYMBOL(raw_copy_to_user);
linux-master
arch/nios2/mm/uaccess.c
/* * Architecture-dependent parts of process handling. * * Copyright (C) 2013 Altera Corporation * Copyright (C) 2010 Tobias Klauser <[email protected]> * Copyright (C) 2009 Wind River Systems Inc * Implemented by [email protected] and [email protected] * Copyright (C) 2004 Microtronix Datacom Ltd * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/export.h> #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/mm_types.h> #include <linux/tick.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <asm/traps.h> #include <asm/cpuinfo.h> asmlinkage void ret_from_fork(void); asmlinkage void ret_from_kernel_thread(void); void (*pm_power_off)(void) = NULL; EXPORT_SYMBOL(pm_power_off); void arch_cpu_idle(void) { } /* * The development boards have no way to pull a board reset. Just jump to the * cpu reset address and let the boot loader or the code in head.S take care of * resetting peripherals. */ void machine_restart(char *__unused) { pr_notice("Machine restart (%08x)...\n", cpuinfo.reset_addr); local_irq_disable(); __asm__ __volatile__ ( "jmp %0\n\t" : : "r" (cpuinfo.reset_addr) : "r4"); } void machine_halt(void) { pr_notice("Machine halt...\n"); local_irq_disable(); for (;;) ; } /* * There is no way to power off the development boards. So just spin for now. If * we ever have a way of resetting a board using a GPIO we should add that here. */ void machine_power_off(void) { pr_notice("Machine power off...\n"); local_irq_disable(); for (;;) ; } void show_regs(struct pt_regs *regs) { pr_notice("\n"); show_regs_print_info(KERN_DEFAULT); pr_notice("r1: %08lx r2: %08lx r3: %08lx r4: %08lx\n", regs->r1, regs->r2, regs->r3, regs->r4); pr_notice("r5: %08lx r6: %08lx r7: %08lx r8: %08lx\n", regs->r5, regs->r6, regs->r7, regs->r8); pr_notice("r9: %08lx r10: %08lx r11: %08lx r12: %08lx\n", regs->r9, regs->r10, regs->r11, regs->r12); pr_notice("r13: %08lx r14: %08lx r15: %08lx\n", regs->r13, regs->r14, regs->r15); pr_notice("ra: %08lx fp: %08lx sp: %08lx gp: %08lx\n", regs->ra, regs->fp, regs->sp, regs->gp); pr_notice("ea: %08lx estatus: %08lx\n", regs->ea, regs->estatus); } void flush_thread(void) { } int copy_thread(struct task_struct *p, const struct kernel_clone_args *args) { unsigned long clone_flags = args->flags; unsigned long usp = args->stack; unsigned long tls = args->tls; struct pt_regs *childregs = task_pt_regs(p); struct pt_regs *regs; struct switch_stack *stack; struct switch_stack *childstack = ((struct switch_stack *)childregs) - 1; if (unlikely(args->fn)) { memset(childstack, 0, sizeof(struct switch_stack) + sizeof(struct pt_regs)); childstack->r16 = (unsigned long) args->fn; childstack->r17 = (unsigned long) args->fn_arg; childstack->ra = (unsigned long) ret_from_kernel_thread; childregs->estatus = STATUS_PIE; childregs->sp = (unsigned long) childstack; p->thread.ksp = (unsigned long) childstack; p->thread.kregs = childregs; return 0; } regs = current_pt_regs(); *childregs = *regs; childregs->r2 = 0; /* Set the return value for the child. */ childregs->r7 = 0; stack = ((struct switch_stack *) regs) - 1; *childstack = *stack; childstack->ra = (unsigned long)ret_from_fork; p->thread.kregs = childregs; p->thread.ksp = (unsigned long) childstack; if (usp) childregs->sp = usp; /* Initialize tls register. */ if (clone_flags & CLONE_SETTLS) childstack->r23 = tls; return 0; } /* * Generic dumping code. Used for panic and debug. */ void dump(struct pt_regs *fp) { unsigned long *sp; unsigned char *tp; int i; pr_emerg("\nCURRENT PROCESS:\n\n"); pr_emerg("COMM=%s PID=%d\n", current->comm, current->pid); if (current->mm) { pr_emerg("TEXT=%08x-%08x DATA=%08x-%08x BSS=%08x-%08x\n", (int) current->mm->start_code, (int) current->mm->end_code, (int) current->mm->start_data, (int) current->mm->end_data, (int) current->mm->end_data, (int) current->mm->brk); pr_emerg("USER-STACK=%08x KERNEL-STACK=%08x\n\n", (int) current->mm->start_stack, (int)(((unsigned long) current) + THREAD_SIZE)); } pr_emerg("PC: %08lx\n", fp->ea); pr_emerg("SR: %08lx SP: %08lx\n", (long) fp->estatus, (long) fp); pr_emerg("r1: %08lx r2: %08lx r3: %08lx\n", fp->r1, fp->r2, fp->r3); pr_emerg("r4: %08lx r5: %08lx r6: %08lx r7: %08lx\n", fp->r4, fp->r5, fp->r6, fp->r7); pr_emerg("r8: %08lx r9: %08lx r10: %08lx r11: %08lx\n", fp->r8, fp->r9, fp->r10, fp->r11); pr_emerg("r12: %08lx r13: %08lx r14: %08lx r15: %08lx\n", fp->r12, fp->r13, fp->r14, fp->r15); pr_emerg("or2: %08lx ra: %08lx fp: %08lx sp: %08lx\n", fp->orig_r2, fp->ra, fp->fp, fp->sp); pr_emerg("\nUSP: %08x TRAPFRAME: %08x\n", (unsigned int) fp->sp, (unsigned int) fp); pr_emerg("\nCODE:"); tp = ((unsigned char *) fp->ea) - 0x20; for (sp = (unsigned long *) tp, i = 0; (i < 0x40); i += 4) { if ((i % 0x10) == 0) pr_emerg("\n%08x: ", (int) (tp + i)); pr_emerg("%08x ", (int) *sp++); } pr_emerg("\n"); pr_emerg("\nKERNEL STACK:"); tp = ((unsigned char *) fp) - 0x40; for (sp = (unsigned long *) tp, i = 0; (i < 0xc0); i += 4) { if ((i % 0x10) == 0) pr_emerg("\n%08x: ", (int) (tp + i)); pr_emerg("%08x ", (int) *sp++); } pr_emerg("\n"); pr_emerg("\n"); pr_emerg("\nUSER STACK:"); tp = (unsigned char *) (fp->sp - 0x10); for (sp = (unsigned long *) tp, i = 0; (i < 0x80); i += 4) { if ((i % 0x10) == 0) pr_emerg("\n%08x: ", (int) (tp + i)); pr_emerg("%08x ", (int) *sp++); } pr_emerg("\n\n"); } unsigned long __get_wchan(struct task_struct *p) { unsigned long fp, pc; unsigned long stack_page; int count = 0; stack_page = (unsigned long)p; fp = ((struct switch_stack *)p->thread.ksp)->fp; /* ;dgt2 */ do { if (fp < stack_page+sizeof(struct task_struct) || fp >= 8184+stack_page) /* ;dgt2;tmp */ return 0; pc = ((unsigned long *)fp)[1]; if (!in_sched_functions(pc)) return pc; fp = *(unsigned long *) fp; } while (count++ < 16); /* ;dgt2;tmp */ return 0; } /* * Do necessary setup to start up a newly executed thread. * Will startup in user mode (status_extension = 0). */ void start_thread(struct pt_regs *regs, unsigned long pc, unsigned long sp) { memset((void *) regs, 0, sizeof(struct pt_regs)); regs->estatus = ESTATUS_EPIE | ESTATUS_EU; regs->ea = pc; regs->sp = sp; } asmlinkage int nios2_clone(unsigned long clone_flags, unsigned long newsp, int __user *parent_tidptr, int __user *child_tidptr, unsigned long tls) { struct kernel_clone_args args = { .flags = (lower_32_bits(clone_flags) & ~CSIGNAL), .pidfd = parent_tidptr, .child_tid = child_tidptr, .parent_tid = parent_tidptr, .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL), .stack = newsp, .tls = tls, }; return kernel_clone(&args); }
linux-master
arch/nios2/kernel/process.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2013 Altera Corporation * Copyright (C) 2011 Tobias Klauser <[email protected]> * Copyright (C) 2008 Thomas Chou <[email protected]> * * based on irq.c from m68k which is: * * Copyright (C) 2007 Greg Ungerer <[email protected]> */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/irqdomain.h> #include <linux/of.h> static u32 ienable; asmlinkage void do_IRQ(int hwirq, struct pt_regs *regs) { struct pt_regs *oldregs = set_irq_regs(regs); irq_enter(); generic_handle_domain_irq(NULL, hwirq); irq_exit(); set_irq_regs(oldregs); } static void chip_unmask(struct irq_data *d) { ienable |= (1 << d->hwirq); WRCTL(CTL_IENABLE, ienable); } static void chip_mask(struct irq_data *d) { ienable &= ~(1 << d->hwirq); WRCTL(CTL_IENABLE, ienable); } static struct irq_chip m_irq_chip = { .name = "NIOS2-INTC", .irq_unmask = chip_unmask, .irq_mask = chip_mask, }; static int irq_map(struct irq_domain *h, unsigned int virq, irq_hw_number_t hw_irq_num) { irq_set_chip_and_handler(virq, &m_irq_chip, handle_level_irq); return 0; } static const struct irq_domain_ops irq_ops = { .map = irq_map, .xlate = irq_domain_xlate_onecell, }; void __init init_IRQ(void) { struct irq_domain *domain; struct device_node *node; node = of_find_compatible_node(NULL, NULL, "altr,nios2-1.0"); if (!node) node = of_find_compatible_node(NULL, NULL, "altr,nios2-1.1"); BUG_ON(!node); domain = irq_domain_add_linear(node, NIOS2_CPU_NR_IRQS, &irq_ops, NULL); BUG_ON(!domain); irq_set_default_host(domain); of_node_put(node); /* Load the initial ienable value */ ienable = RDCTL(CTL_IENABLE); }
linux-master
arch/nios2/kernel/irq.c
/* * Copyright (C) 2014 Altera Corporation * Copyright (C) 2010 Tobias Klauser <[email protected]> * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of this * archive for more details. */ #include <linux/elf.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/ptrace.h> #include <linux/regset.h> #include <linux/sched.h> #include <linux/sched/task_stack.h> #include <linux/uaccess.h> #include <linux/user.h> static int genregs_get(struct task_struct *target, const struct user_regset *regset, struct membuf to) { const struct pt_regs *regs = task_pt_regs(target); const struct switch_stack *sw = (struct switch_stack *)regs - 1; membuf_zero(&to, 4); // R0 membuf_write(&to, &regs->r1, 7 * 4); // R1..R7 membuf_write(&to, &regs->r8, 8 * 4); // R8..R15 membuf_write(&to, sw, 8 * 4); // R16..R23 membuf_zero(&to, 2 * 4); /* et and bt */ membuf_store(&to, regs->gp); membuf_store(&to, regs->sp); membuf_store(&to, regs->fp); membuf_store(&to, regs->ea); membuf_zero(&to, 4); // PTR_BA membuf_store(&to, regs->ra); membuf_store(&to, regs->ea); /* use ea for PC */ return membuf_zero(&to, (NUM_PTRACE_REG - PTR_PC) * 4); } /* * Set the thread state from a regset passed in via ptrace */ static int genregs_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct pt_regs *regs = task_pt_regs(target); const struct switch_stack *sw = (struct switch_stack *)regs - 1; int ret = 0; #define REG_IGNORE_RANGE(START, END) \ if (!ret) \ user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf, \ START * 4, (END * 4) + 4); #define REG_IN_ONE(PTR, LOC) \ if (!ret) \ ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, \ (void *)(PTR), LOC * 4, (LOC * 4) + 4); #define REG_IN_RANGE(PTR, START, END) \ if (!ret) \ ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, \ (void *)(PTR), START * 4, (END * 4) + 4); REG_IGNORE_RANGE(PTR_R0, PTR_R0); REG_IN_RANGE(&regs->r1, PTR_R1, PTR_R7); REG_IN_RANGE(&regs->r8, PTR_R8, PTR_R15); REG_IN_RANGE(sw, PTR_R16, PTR_R23); REG_IGNORE_RANGE(PTR_R24, PTR_R25); /* et and bt */ REG_IN_ONE(&regs->gp, PTR_GP); REG_IN_ONE(&regs->sp, PTR_SP); REG_IN_ONE(&regs->fp, PTR_FP); REG_IN_ONE(&regs->ea, PTR_EA); REG_IGNORE_RANGE(PTR_BA, PTR_BA); REG_IN_ONE(&regs->ra, PTR_RA); REG_IN_ONE(&regs->ea, PTR_PC); /* use ea for PC */ if (!ret) user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf, PTR_STATUS * 4, -1); return ret; } /* * Define the register sets available on Nios2 under Linux */ enum nios2_regset { REGSET_GENERAL, }; static const struct user_regset nios2_regsets[] = { [REGSET_GENERAL] = { .core_note_type = NT_PRSTATUS, .n = NUM_PTRACE_REG, .size = sizeof(unsigned long), .align = sizeof(unsigned long), .regset_get = genregs_get, .set = genregs_set, } }; static const struct user_regset_view nios2_user_view = { .name = "nios2", .e_machine = ELF_ARCH, .ei_osabi = ELF_OSABI, .regsets = nios2_regsets, .n = ARRAY_SIZE(nios2_regsets) }; const struct user_regset_view *task_user_regset_view(struct task_struct *task) { return &nios2_user_view; } void ptrace_disable(struct task_struct *child) { } long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { return ptrace_request(child, request, addr, data); } asmlinkage int do_syscall_trace_enter(void) { int ret = 0; if (test_thread_flag(TIF_SYSCALL_TRACE)) ret = ptrace_report_syscall_entry(task_pt_regs(current)); return ret; } asmlinkage void do_syscall_trace_exit(void) { if (test_thread_flag(TIF_SYSCALL_TRACE)) ptrace_report_syscall_exit(task_pt_regs(current), 0); }
linux-master
arch/nios2/kernel/ptrace.c
/* * Hardware exception handling * * Copyright (C) 2010 Tobias Klauser <[email protected]> * Copyright (C) 2004 Microtronix Datacom Ltd. * Copyright (C) 2001 Vic Phillips * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of this * archive for more details. */ #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/export.h> #include <linux/mm.h> #include <linux/ptrace.h> #include <asm/traps.h> #include <asm/sections.h> #include <linux/uaccess.h> static DEFINE_SPINLOCK(die_lock); static void _send_sig(int signo, int code, unsigned long addr) { force_sig_fault(signo, code, (void __user *) addr); } void die(const char *str, struct pt_regs *regs, long err) { console_verbose(); spin_lock_irq(&die_lock); pr_warn("Oops: %s, sig: %ld\n", str, err); show_regs(regs); spin_unlock_irq(&die_lock); /* * make_task_dead() should take care of panic'ing from an interrupt * context so we don't handle it here */ make_task_dead(err); } void _exception(int signo, struct pt_regs *regs, int code, unsigned long addr) { if (!user_mode(regs)) die("Exception in kernel mode", regs, signo); _send_sig(signo, code, addr); } /* * The show_stack() is external API which we do not use ourselves. */ int kstack_depth_to_print = 48; void show_stack(struct task_struct *task, unsigned long *stack, const char *loglvl) { unsigned long *endstack, addr; int i; if (!stack) { if (task) stack = (unsigned long *)task->thread.ksp; else stack = (unsigned long *)&stack; } addr = (unsigned long) stack; endstack = (unsigned long *) PAGE_ALIGN(addr); printk("%sStack from %08lx:", loglvl, (unsigned long)stack); for (i = 0; i < kstack_depth_to_print; i++) { if (stack + 1 > endstack) break; if (i % 8 == 0) printk("%s\n ", loglvl); printk("%s %08lx", loglvl, *stack++); } printk("%s\nCall Trace:", loglvl); i = 0; while (stack + 1 <= endstack) { addr = *stack++; /* * If the address is either in the text segment of the * kernel, or in the region which contains vmalloc'ed * memory, it *may* be the address of a calling * routine; if so, print it so that someone tracing * down the cause of the crash will be able to figure * out the call path that was taken. */ if (((addr >= (unsigned long) _stext) && (addr <= (unsigned long) _etext))) { if (i % 4 == 0) pr_emerg("\n "); printk("%s [<%08lx>]", loglvl, addr); i++; } } printk("%s\n", loglvl); } /* Breakpoint handler */ asmlinkage void breakpoint_c(struct pt_regs *fp) { /* * The breakpoint entry code has moved the PC on by 4 bytes, so we must * move it back. This could be done on the host but we do it here * because monitor.S of JTAG gdbserver does it too. */ fp->ea -= 4; _exception(SIGTRAP, fp, TRAP_BRKPT, fp->ea); } #ifndef CONFIG_NIOS2_ALIGNMENT_TRAP /* Alignment exception handler */ asmlinkage void handle_unaligned_c(struct pt_regs *fp, int cause) { unsigned long addr = RDCTL(CTL_BADADDR); cause >>= 2; fp->ea -= 4; if (fixup_exception(fp)) return; if (!user_mode(fp)) { pr_alert("Unaligned access from kernel mode, this might be a hardware\n"); pr_alert("problem, dump registers and restart the instruction\n"); pr_alert(" BADADDR 0x%08lx\n", addr); pr_alert(" cause %d\n", cause); pr_alert(" op-code 0x%08lx\n", *(unsigned long *)(fp->ea)); show_regs(fp); return; } _exception(SIGBUS, fp, BUS_ADRALN, addr); } #endif /* CONFIG_NIOS2_ALIGNMENT_TRAP */ /* Illegal instruction handler */ asmlinkage void handle_illegal_c(struct pt_regs *fp) { fp->ea -= 4; _exception(SIGILL, fp, ILL_ILLOPC, fp->ea); } /* Supervisor instruction handler */ asmlinkage void handle_supervisor_instr(struct pt_regs *fp) { fp->ea -= 4; _exception(SIGILL, fp, ILL_PRVOPC, fp->ea); } /* Division error handler */ asmlinkage void handle_diverror_c(struct pt_regs *fp) { fp->ea -= 4; _exception(SIGFPE, fp, FPE_INTDIV, fp->ea); } /* Unhandled exception handler */ asmlinkage void unhandled_exception(struct pt_regs *regs, int cause) { unsigned long addr = RDCTL(CTL_BADADDR); cause /= 4; pr_emerg("Unhandled exception #%d in %s mode (badaddr=0x%08lx)\n", cause, user_mode(regs) ? "user" : "kernel", addr); regs->ea -= 4; show_regs(regs); pr_emerg("opcode: 0x%08lx\n", *(unsigned long *)(regs->ea)); } asmlinkage void handle_trap_1_c(struct pt_regs *fp) { _send_sig(SIGUSR1, 0, fp->ea); } asmlinkage void handle_trap_2_c(struct pt_regs *fp) { _send_sig(SIGUSR2, 0, fp->ea); } asmlinkage void handle_trap_3_c(struct pt_regs *fp) { _send_sig(SIGILL, ILL_ILLTRP, fp->ea); }
linux-master
arch/nios2/kernel/traps.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2011 Tobias Klauser <[email protected]> */ #include <linux/stddef.h> #include <linux/sched.h> #include <linux/kernel_stat.h> #include <linux/ptrace.h> #include <linux/hardirq.h> #include <linux/thread_info.h> #include <linux/kbuild.h> int main(void) { /* struct task_struct */ OFFSET(TASK_THREAD, task_struct, thread); BLANK(); /* struct thread_struct */ OFFSET(THREAD_KSP, thread_struct, ksp); OFFSET(THREAD_KPSR, thread_struct, kpsr); BLANK(); /* struct pt_regs */ OFFSET(PT_ORIG_R2, pt_regs, orig_r2); OFFSET(PT_ORIG_R7, pt_regs, orig_r7); OFFSET(PT_R1, pt_regs, r1); OFFSET(PT_R2, pt_regs, r2); OFFSET(PT_R3, pt_regs, r3); OFFSET(PT_R4, pt_regs, r4); OFFSET(PT_R5, pt_regs, r5); OFFSET(PT_R6, pt_regs, r6); OFFSET(PT_R7, pt_regs, r7); OFFSET(PT_R8, pt_regs, r8); OFFSET(PT_R9, pt_regs, r9); OFFSET(PT_R10, pt_regs, r10); OFFSET(PT_R11, pt_regs, r11); OFFSET(PT_R12, pt_regs, r12); OFFSET(PT_R13, pt_regs, r13); OFFSET(PT_R14, pt_regs, r14); OFFSET(PT_R15, pt_regs, r15); OFFSET(PT_EA, pt_regs, ea); OFFSET(PT_RA, pt_regs, ra); OFFSET(PT_FP, pt_regs, fp); OFFSET(PT_SP, pt_regs, sp); OFFSET(PT_GP, pt_regs, gp); OFFSET(PT_ESTATUS, pt_regs, estatus); DEFINE(PT_REGS_SIZE, sizeof(struct pt_regs)); BLANK(); /* struct switch_stack */ OFFSET(SW_R16, switch_stack, r16); OFFSET(SW_R17, switch_stack, r17); OFFSET(SW_R18, switch_stack, r18); OFFSET(SW_R19, switch_stack, r19); OFFSET(SW_R20, switch_stack, r20); OFFSET(SW_R21, switch_stack, r21); OFFSET(SW_R22, switch_stack, r22); OFFSET(SW_R23, switch_stack, r23); OFFSET(SW_FP, switch_stack, fp); OFFSET(SW_GP, switch_stack, gp); OFFSET(SW_RA, switch_stack, ra); DEFINE(SWITCH_STACK_SIZE, sizeof(struct switch_stack)); BLANK(); /* struct thread_info */ OFFSET(TI_FLAGS, thread_info, flags); OFFSET(TI_PREEMPT_COUNT, thread_info, preempt_count); BLANK(); return 0; }
linux-master
arch/nios2/kernel/asm-offsets.c
/* * Copyright (C) 2013 Altera Corporation * Copyright (C) 2011-2012 Tobias Klauser <[email protected]> * Copyright (C) 2004 Microtronix Datacom Ltd. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/export.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/syscalls.h> #include <asm/cacheflush.h> #include <asm/traps.h> /* sys_cacheflush -- flush the processor cache. */ asmlinkage int sys_cacheflush(unsigned long addr, unsigned long len, unsigned int op) { struct vm_area_struct *vma; struct mm_struct *mm = current->mm; if (len == 0) return 0; /* We only support op 0 now, return error if op is non-zero.*/ if (op) return -EINVAL; /* Check for overflow */ if (addr + len < addr) return -EFAULT; if (mmap_read_lock_killable(mm)) return -EINTR; /* * Verify that the specified address region actually belongs * to this process. */ vma = find_vma(mm, addr); if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end) { mmap_read_unlock(mm); return -EFAULT; } flush_cache_range(vma, addr, addr + len); mmap_read_unlock(mm); return 0; } asmlinkage int sys_getpagesize(void) { return PAGE_SIZE; }
linux-master
arch/nios2/kernel/sys_nios2.c
/* * Kernel module support for Nios II. * * Copyright (C) 2004 Microtronix Datacom Ltd. * Written by Wentao Xu <[email protected]> * Copyright (C) 2001, 2003 Rusty Russell * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of this * archive for more details. */ #include <linux/moduleloader.h> #include <linux/elf.h> #include <linux/mm.h> #include <linux/vmalloc.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/string.h> #include <linux/kernel.h> #include <asm/cacheflush.h> /* * Modules should NOT be allocated with kmalloc for (obvious) reasons. * But we do it for now to avoid relocation issues. CALL26/PCREL26 cannot reach * from 0x80000000 (vmalloc area) to 0xc00000000 (kernel) (kmalloc returns * addresses in 0xc0000000) */ void *module_alloc(unsigned long size) { if (size == 0) return NULL; return kmalloc(size, GFP_KERNEL); } /* Free memory returned from module_alloc */ void module_memfree(void *module_region) { kfree(module_region); } int apply_relocate_add(Elf32_Shdr *sechdrs, const char *strtab, unsigned int symindex, unsigned int relsec, struct module *mod) { unsigned int i; Elf32_Rela *rela = (void *)sechdrs[relsec].sh_addr; pr_debug("Applying relocate section %u to %u\n", relsec, sechdrs[relsec].sh_info); for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rela); i++) { /* This is where to make the change */ uint32_t word; uint32_t *loc = ((void *)sechdrs[sechdrs[relsec].sh_info].sh_addr + rela[i].r_offset); /* This is the symbol it is referring to. Note that all undefined symbols have been resolved. */ Elf32_Sym *sym = ((Elf32_Sym *)sechdrs[symindex].sh_addr + ELF32_R_SYM(rela[i].r_info)); uint32_t v = sym->st_value + rela[i].r_addend; pr_debug("reltype %d 0x%x name:<%s>\n", ELF32_R_TYPE(rela[i].r_info), rela[i].r_offset, strtab + sym->st_name); switch (ELF32_R_TYPE(rela[i].r_info)) { case R_NIOS2_NONE: break; case R_NIOS2_BFD_RELOC_32: *loc += v; break; case R_NIOS2_PCREL16: v -= (uint32_t)loc + 4; if ((int32_t)v > 0x7fff || (int32_t)v < -(int32_t)0x8000) { pr_err("module %s: relocation overflow\n", mod->name); return -ENOEXEC; } word = *loc; *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) | (word & 0x3f); break; case R_NIOS2_CALL26: if (v & 3) { pr_err("module %s: dangerous relocation\n", mod->name); return -ENOEXEC; } if ((v >> 28) != ((uint32_t)loc >> 28)) { pr_err("module %s: relocation overflow\n", mod->name); return -ENOEXEC; } *loc = (*loc & 0x3f) | ((v >> 2) << 6); break; case R_NIOS2_HI16: word = *loc; *loc = ((((word >> 22) << 16) | ((v >> 16) & 0xffff)) << 6) | (word & 0x3f); break; case R_NIOS2_LO16: word = *loc; *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) | (word & 0x3f); break; case R_NIOS2_HIADJ16: { Elf32_Addr word2; word = *loc; word2 = ((v >> 16) + ((v >> 15) & 1)) & 0xffff; *loc = ((((word >> 22) << 16) | word2) << 6) | (word & 0x3f); } break; default: pr_err("module %s: Unknown reloc: %u\n", mod->name, ELF32_R_TYPE(rela[i].r_info)); return -ENOEXEC; } } return 0; } int module_finalize(const Elf_Ehdr *hdr, const Elf_Shdr *sechdrs, struct module *me) { flush_cache_all(); return 0; }
linux-master
arch/nios2/kernel/module.c
/* * linux/arch/nios2/kernel/misaligned.c * * basic emulation for mis-aligned accesses on the NIOS II cpu * modelled after the version for arm in arm/alignment.c * * Brad Parker <[email protected]> * Copyright (C) 2010 Ambient Corporation * Copyright (c) 2010 Altera Corporation, San Jose, California, USA. * Copyright (c) 2010 Arrow Electronics, Inc. * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of * this archive for more details. */ #include <linux/errno.h> #include <linux/string.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/uaccess.h> #include <linux/seq_file.h> #include <asm/traps.h> #include <asm/unaligned.h> /* instructions we emulate */ #define INST_LDHU 0x0b #define INST_STH 0x0d #define INST_LDH 0x0f #define INST_STW 0x15 #define INST_LDW 0x17 static unsigned int ma_usermode; #define UM_WARN 0x01 #define UM_FIXUP 0x02 #define UM_SIGNAL 0x04 #define KM_WARN 0x08 /* see arch/nios2/include/asm/ptrace.h */ static u8 sys_stack_frame_reg_offset[] = { /* struct pt_regs */ 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 0, /* struct switch_stack */ 16, 17, 18, 19, 20, 21, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0 }; static int reg_offsets[32]; static inline u32 get_reg_val(struct pt_regs *fp, int reg) { u8 *p = ((u8 *)fp) + reg_offsets[reg]; return *(u32 *)p; } static inline void put_reg_val(struct pt_regs *fp, int reg, u32 val) { u8 *p = ((u8 *)fp) + reg_offsets[reg]; *(u32 *)p = val; } /* * (mis)alignment handler */ asmlinkage void handle_unaligned_c(struct pt_regs *fp, int cause) { u32 isn, addr, val; int in_kernel; u8 a, b, d0, d1, d2, d3; s16 imm16; unsigned int fault; /* back up one instruction */ fp->ea -= 4; if (fixup_exception(fp)) { return; } in_kernel = !user_mode(fp); isn = *(unsigned long *)(fp->ea); fault = 0; /* do fixup if in kernel or mode turned on */ if (in_kernel || (ma_usermode & UM_FIXUP)) { /* decompose instruction */ a = (isn >> 27) & 0x1f; b = (isn >> 22) & 0x1f; imm16 = (isn >> 6) & 0xffff; addr = get_reg_val(fp, a) + imm16; /* do fixup to saved registers */ switch (isn & 0x3f) { case INST_LDHU: fault |= __get_user(d0, (u8 *)(addr+0)); fault |= __get_user(d1, (u8 *)(addr+1)); val = (d1 << 8) | d0; put_reg_val(fp, b, val); break; case INST_STH: val = get_reg_val(fp, b); d1 = val >> 8; d0 = val >> 0; if (in_kernel) { *(u8 *)(addr+0) = d0; *(u8 *)(addr+1) = d1; } else { fault |= __put_user(d0, (u8 *)(addr+0)); fault |= __put_user(d1, (u8 *)(addr+1)); } break; case INST_LDH: fault |= __get_user(d0, (u8 *)(addr+0)); fault |= __get_user(d1, (u8 *)(addr+1)); val = (short)((d1 << 8) | d0); put_reg_val(fp, b, val); break; case INST_STW: val = get_reg_val(fp, b); d3 = val >> 24; d2 = val >> 16; d1 = val >> 8; d0 = val >> 0; if (in_kernel) { *(u8 *)(addr+0) = d0; *(u8 *)(addr+1) = d1; *(u8 *)(addr+2) = d2; *(u8 *)(addr+3) = d3; } else { fault |= __put_user(d0, (u8 *)(addr+0)); fault |= __put_user(d1, (u8 *)(addr+1)); fault |= __put_user(d2, (u8 *)(addr+2)); fault |= __put_user(d3, (u8 *)(addr+3)); } break; case INST_LDW: fault |= __get_user(d0, (u8 *)(addr+0)); fault |= __get_user(d1, (u8 *)(addr+1)); fault |= __get_user(d2, (u8 *)(addr+2)); fault |= __get_user(d3, (u8 *)(addr+3)); val = (d3 << 24) | (d2 << 16) | (d1 << 8) | d0; put_reg_val(fp, b, val); break; } } addr = RDCTL(CTL_BADADDR); cause >>= 2; if (fault) { if (in_kernel) { pr_err("fault during kernel misaligned fixup @ %#lx; addr 0x%08x; isn=0x%08x\n", fp->ea, (unsigned int)addr, (unsigned int)isn); } else { pr_err("fault during user misaligned fixup @ %#lx; isn=%08x addr=0x%08x sp=0x%08lx pid=%d\n", fp->ea, (unsigned int)isn, addr, fp->sp, current->pid); _exception(SIGSEGV, fp, SEGV_MAPERR, fp->ea); return; } } /* * kernel mode - * note exception and skip bad instruction (return) */ if (in_kernel) { fp->ea += 4; if (ma_usermode & KM_WARN) { pr_err("kernel unaligned access @ %#lx; BADADDR 0x%08x; cause=%d, isn=0x%08x\n", fp->ea, (unsigned int)addr, cause, (unsigned int)isn); /* show_regs(fp); */ } return; } /* * user mode - * possibly warn, * possibly send SIGBUS signal to process */ if (ma_usermode & UM_WARN) { pr_err("user unaligned access @ %#lx; isn=0x%08lx ea=0x%08lx ra=0x%08lx sp=0x%08lx\n", (unsigned long)addr, (unsigned long)isn, fp->ea, fp->ra, fp->sp); } if (ma_usermode & UM_SIGNAL) _exception(SIGBUS, fp, BUS_ADRALN, fp->ea); else fp->ea += 4; /* else advance */ } static void __init misaligned_calc_reg_offsets(void) { int i, r, offset; /* pre-calc offsets of registers on sys call stack frame */ offset = 0; /* struct pt_regs */ for (i = 0; i < 16; i++) { r = sys_stack_frame_reg_offset[i]; reg_offsets[r] = offset; offset += 4; } /* struct switch_stack */ offset = -sizeof(struct switch_stack); for (i = 16; i < 32; i++) { r = sys_stack_frame_reg_offset[i]; reg_offsets[r] = offset; offset += 4; } } static int __init misaligned_init(void) { /* default mode - silent fix */ ma_usermode = UM_FIXUP | KM_WARN; misaligned_calc_reg_offsets(); return 0; } fs_initcall(misaligned_init);
linux-master
arch/nios2/kernel/misaligned.c
/* * Copyright (C) 2004 Microtronix Datacom Ltd * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of this * archive for more details. */ #include <linux/export.h> #include <linux/string.h> #include <linux/pgtable.h> #include <asm/cacheflush.h> /* string functions */ EXPORT_SYMBOL(memcpy); EXPORT_SYMBOL(memset); EXPORT_SYMBOL(memmove); /* memory management */ EXPORT_SYMBOL(empty_zero_page); EXPORT_SYMBOL(flush_icache_range); /* * libgcc functions - functions that are used internally by the * compiler... (prototypes are not correct though, but that * doesn't really matter since they're not versioned). */ #define DECLARE_EXPORT(name) extern void name(void); EXPORT_SYMBOL(name) DECLARE_EXPORT(__gcc_bcmp); DECLARE_EXPORT(__divsi3); DECLARE_EXPORT(__moddi3); DECLARE_EXPORT(__modsi3); DECLARE_EXPORT(__udivmoddi4); DECLARE_EXPORT(__udivsi3); DECLARE_EXPORT(__umoddi3); DECLARE_EXPORT(__umodsi3); DECLARE_EXPORT(__muldi3); DECLARE_EXPORT(__ucmpdi2); DECLARE_EXPORT(__lshrdi3); DECLARE_EXPORT(__ashldi3); DECLARE_EXPORT(__ashrdi3);
linux-master
arch/nios2/kernel/nios2_ksyms.c
/* * Nios2-specific parts of system setup * * Copyright (C) 2010 Tobias Klauser <[email protected]> * Copyright (C) 2004 Microtronix Datacom Ltd. * Copyright (C) 2001 Vic Phillips <[email protected]> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/export.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/sched/task.h> #include <linux/console.h> #include <linux/memblock.h> #include <linux/initrd.h> #include <linux/of_fdt.h> #include <linux/screen_info.h> #include <asm/mmu_context.h> #include <asm/sections.h> #include <asm/setup.h> #include <asm/cpuinfo.h> unsigned long memory_start; EXPORT_SYMBOL(memory_start); unsigned long memory_end; EXPORT_SYMBOL(memory_end); static struct pt_regs fake_regs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; #ifdef CONFIG_VT struct screen_info screen_info; #endif /* Copy a short hook instruction sequence to the exception address */ static inline void copy_exception_handler(unsigned int addr) { unsigned int start = (unsigned int) exception_handler_hook; volatile unsigned int tmp = 0; if (start == addr) { /* The CPU exception address already points to the handler. */ return; } __asm__ __volatile__ ( "ldw %2,0(%0)\n" "stw %2,0(%1)\n" "ldw %2,4(%0)\n" "stw %2,4(%1)\n" "ldw %2,8(%0)\n" "stw %2,8(%1)\n" "flushd 0(%1)\n" "flushd 4(%1)\n" "flushd 8(%1)\n" "flushi %1\n" "addi %1,%1,4\n" "flushi %1\n" "addi %1,%1,4\n" "flushi %1\n" "flushp\n" : /* no output registers */ : "r" (start), "r" (addr), "r" (tmp) : "memory" ); } /* Copy the fast TLB miss handler */ static inline void copy_fast_tlb_miss_handler(unsigned int addr) { unsigned int start = (unsigned int) fast_handler; unsigned int end = (unsigned int) fast_handler_end; volatile unsigned int tmp = 0; __asm__ __volatile__ ( "1:\n" " ldw %3,0(%0)\n" " stw %3,0(%1)\n" " flushd 0(%1)\n" " flushi %1\n" " flushp\n" " addi %0,%0,4\n" " addi %1,%1,4\n" " bne %0,%2,1b\n" : /* no output registers */ : "r" (start), "r" (addr), "r" (end), "r" (tmp) : "memory" ); } /* * save args passed from u-boot, called from head.S * * @r4: NIOS magic * @r5: initrd start * @r6: initrd end or fdt * @r7: kernel command line */ asmlinkage void __init nios2_boot_init(unsigned r4, unsigned r5, unsigned r6, unsigned r7) { unsigned dtb_passed = 0; char cmdline_passed[COMMAND_LINE_SIZE] __maybe_unused = { 0, }; #if defined(CONFIG_NIOS2_PASS_CMDLINE) if (r4 == 0x534f494e) { /* r4 is magic NIOS */ #if defined(CONFIG_BLK_DEV_INITRD) if (r5) { /* initramfs */ initrd_start = r5; initrd_end = r6; } #endif /* CONFIG_BLK_DEV_INITRD */ dtb_passed = r6; if (r7) strscpy(cmdline_passed, (char *)r7, COMMAND_LINE_SIZE); } #endif early_init_devtree((void *)dtb_passed); #ifndef CONFIG_CMDLINE_FORCE if (cmdline_passed[0]) strscpy(boot_command_line, cmdline_passed, COMMAND_LINE_SIZE); #ifdef CONFIG_NIOS2_CMDLINE_IGNORE_DTB else strscpy(boot_command_line, CONFIG_CMDLINE, COMMAND_LINE_SIZE); #endif #endif parse_early_param(); } static void __init find_limits(unsigned long *min, unsigned long *max_low, unsigned long *max_high) { *max_low = PFN_DOWN(memblock_get_current_limit()); *min = PFN_UP(memblock_start_of_DRAM()); *max_high = PFN_DOWN(memblock_end_of_DRAM()); } void __init setup_arch(char **cmdline_p) { console_verbose(); memory_start = memblock_start_of_DRAM(); memory_end = memblock_end_of_DRAM(); setup_initial_init_mm(_stext, _etext, _edata, _end); init_task.thread.kregs = &fake_regs; /* Keep a copy of command line */ *cmdline_p = boot_command_line; find_limits(&min_low_pfn, &max_low_pfn, &max_pfn); max_mapnr = max_low_pfn; memblock_reserve(__pa_symbol(_stext), _end - _stext); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start) { memblock_reserve(virt_to_phys((void *)initrd_start), initrd_end - initrd_start); } #endif /* CONFIG_BLK_DEV_INITRD */ early_init_fdt_reserve_self(); early_init_fdt_scan_reserved_mem(); unflatten_and_copy_device_tree(); setup_cpuinfo(); copy_exception_handler(cpuinfo.exception_addr); mmu_init(); copy_fast_tlb_miss_handler(cpuinfo.fast_tlb_miss_exc_addr); /* * Initialize MMU context handling here because data from cpuinfo is * needed for this. */ mmu_context_init(); /* * get kmalloc into gear */ paging_init(); }
linux-master
arch/nios2/kernel/setup.c
/* * Copyright (C) 2013-2014 Altera Corporation * Copyright (C) 2010 Tobias Klauser <[email protected]> * Copyright (C) 2004 Microtronix Datacom Ltd. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/export.h> #include <linux/interrupt.h> #include <linux/clockchips.h> #include <linux/clocksource.h> #include <linux/delay.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/io.h> #include <linux/slab.h> #define ALTR_TIMER_COMPATIBLE "altr,timer-1.0" #define ALTERA_TIMER_STATUS_REG 0 #define ALTERA_TIMER_CONTROL_REG 4 #define ALTERA_TIMER_PERIODL_REG 8 #define ALTERA_TIMER_PERIODH_REG 12 #define ALTERA_TIMER_SNAPL_REG 16 #define ALTERA_TIMER_SNAPH_REG 20 #define ALTERA_TIMER_CONTROL_ITO_MSK (0x1) #define ALTERA_TIMER_CONTROL_CONT_MSK (0x2) #define ALTERA_TIMER_CONTROL_START_MSK (0x4) #define ALTERA_TIMER_CONTROL_STOP_MSK (0x8) struct nios2_timer { void __iomem *base; unsigned long freq; }; struct nios2_clockevent_dev { struct nios2_timer timer; struct clock_event_device ced; }; struct nios2_clocksource { struct nios2_timer timer; struct clocksource cs; }; static inline struct nios2_clockevent_dev * to_nios2_clkevent(struct clock_event_device *evt) { return container_of(evt, struct nios2_clockevent_dev, ced); } static inline struct nios2_clocksource * to_nios2_clksource(struct clocksource *cs) { return container_of(cs, struct nios2_clocksource, cs); } static u16 timer_readw(struct nios2_timer *timer, u32 offs) { return readw(timer->base + offs); } static void timer_writew(struct nios2_timer *timer, u16 val, u32 offs) { writew(val, timer->base + offs); } static inline unsigned long read_timersnapshot(struct nios2_timer *timer) { unsigned long count; timer_writew(timer, 0, ALTERA_TIMER_SNAPL_REG); count = timer_readw(timer, ALTERA_TIMER_SNAPH_REG) << 16 | timer_readw(timer, ALTERA_TIMER_SNAPL_REG); return count; } static u64 nios2_timer_read(struct clocksource *cs) { struct nios2_clocksource *nios2_cs = to_nios2_clksource(cs); unsigned long flags; u32 count; local_irq_save(flags); count = read_timersnapshot(&nios2_cs->timer); local_irq_restore(flags); /* Counter is counting down */ return ~count; } static struct nios2_clocksource nios2_cs = { .cs = { .name = "nios2-clksrc", .rating = 250, .read = nios2_timer_read, .mask = CLOCKSOURCE_MASK(32), .flags = CLOCK_SOURCE_IS_CONTINUOUS, }, }; cycles_t get_cycles(void) { /* Only read timer if it has been initialized */ if (nios2_cs.timer.base) return nios2_timer_read(&nios2_cs.cs); return 0; } EXPORT_SYMBOL(get_cycles); static void nios2_timer_start(struct nios2_timer *timer) { u16 ctrl; ctrl = timer_readw(timer, ALTERA_TIMER_CONTROL_REG); ctrl |= ALTERA_TIMER_CONTROL_START_MSK; timer_writew(timer, ctrl, ALTERA_TIMER_CONTROL_REG); } static void nios2_timer_stop(struct nios2_timer *timer) { u16 ctrl; ctrl = timer_readw(timer, ALTERA_TIMER_CONTROL_REG); ctrl |= ALTERA_TIMER_CONTROL_STOP_MSK; timer_writew(timer, ctrl, ALTERA_TIMER_CONTROL_REG); } static void nios2_timer_config(struct nios2_timer *timer, unsigned long period, bool periodic) { u16 ctrl; /* The timer's actual period is one cycle greater than the value * stored in the period register. */ period--; ctrl = timer_readw(timer, ALTERA_TIMER_CONTROL_REG); /* stop counter */ timer_writew(timer, ctrl | ALTERA_TIMER_CONTROL_STOP_MSK, ALTERA_TIMER_CONTROL_REG); /* write new count */ timer_writew(timer, period, ALTERA_TIMER_PERIODL_REG); timer_writew(timer, period >> 16, ALTERA_TIMER_PERIODH_REG); ctrl |= ALTERA_TIMER_CONTROL_START_MSK | ALTERA_TIMER_CONTROL_ITO_MSK; if (periodic) ctrl |= ALTERA_TIMER_CONTROL_CONT_MSK; else ctrl &= ~ALTERA_TIMER_CONTROL_CONT_MSK; timer_writew(timer, ctrl, ALTERA_TIMER_CONTROL_REG); } static int nios2_timer_set_next_event(unsigned long delta, struct clock_event_device *evt) { struct nios2_clockevent_dev *nios2_ced = to_nios2_clkevent(evt); nios2_timer_config(&nios2_ced->timer, delta, false); return 0; } static int nios2_timer_shutdown(struct clock_event_device *evt) { struct nios2_clockevent_dev *nios2_ced = to_nios2_clkevent(evt); struct nios2_timer *timer = &nios2_ced->timer; nios2_timer_stop(timer); return 0; } static int nios2_timer_set_periodic(struct clock_event_device *evt) { unsigned long period; struct nios2_clockevent_dev *nios2_ced = to_nios2_clkevent(evt); struct nios2_timer *timer = &nios2_ced->timer; period = DIV_ROUND_UP(timer->freq, HZ); nios2_timer_config(timer, period, true); return 0; } static int nios2_timer_resume(struct clock_event_device *evt) { struct nios2_clockevent_dev *nios2_ced = to_nios2_clkevent(evt); struct nios2_timer *timer = &nios2_ced->timer; nios2_timer_start(timer); return 0; } irqreturn_t timer_interrupt(int irq, void *dev_id) { struct clock_event_device *evt = (struct clock_event_device *) dev_id; struct nios2_clockevent_dev *nios2_ced = to_nios2_clkevent(evt); /* Clear the interrupt condition */ timer_writew(&nios2_ced->timer, 0, ALTERA_TIMER_STATUS_REG); evt->event_handler(evt); return IRQ_HANDLED; } static int __init nios2_timer_get_base_and_freq(struct device_node *np, void __iomem **base, u32 *freq) { *base = of_iomap(np, 0); if (!*base) { pr_crit("Unable to map reg for %pOFn\n", np); return -ENXIO; } if (of_property_read_u32(np, "clock-frequency", freq)) { pr_crit("Unable to get %pOFn clock frequency\n", np); return -EINVAL; } return 0; } static struct nios2_clockevent_dev nios2_ce = { .ced = { .name = "nios2-clkevent", .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT, .rating = 250, .shift = 32, .set_next_event = nios2_timer_set_next_event, .set_state_shutdown = nios2_timer_shutdown, .set_state_periodic = nios2_timer_set_periodic, .set_state_oneshot = nios2_timer_shutdown, .tick_resume = nios2_timer_resume, }, }; static __init int nios2_clockevent_init(struct device_node *timer) { void __iomem *iobase; u32 freq; int irq, ret; ret = nios2_timer_get_base_and_freq(timer, &iobase, &freq); if (ret) return ret; irq = irq_of_parse_and_map(timer, 0); if (!irq) { pr_crit("Unable to parse timer irq\n"); return -EINVAL; } nios2_ce.timer.base = iobase; nios2_ce.timer.freq = freq; nios2_ce.ced.cpumask = cpumask_of(0); nios2_ce.ced.irq = irq; nios2_timer_stop(&nios2_ce.timer); /* clear pending interrupt */ timer_writew(&nios2_ce.timer, 0, ALTERA_TIMER_STATUS_REG); ret = request_irq(irq, timer_interrupt, IRQF_TIMER, timer->name, &nios2_ce.ced); if (ret) { pr_crit("Unable to setup timer irq\n"); return ret; } clockevents_config_and_register(&nios2_ce.ced, freq, 1, ULONG_MAX); return 0; } static __init int nios2_clocksource_init(struct device_node *timer) { unsigned int ctrl; void __iomem *iobase; u32 freq; int ret; ret = nios2_timer_get_base_and_freq(timer, &iobase, &freq); if (ret) return ret; nios2_cs.timer.base = iobase; nios2_cs.timer.freq = freq; ret = clocksource_register_hz(&nios2_cs.cs, freq); if (ret) return ret; timer_writew(&nios2_cs.timer, USHRT_MAX, ALTERA_TIMER_PERIODL_REG); timer_writew(&nios2_cs.timer, USHRT_MAX, ALTERA_TIMER_PERIODH_REG); /* interrupt disable + continuous + start */ ctrl = ALTERA_TIMER_CONTROL_CONT_MSK | ALTERA_TIMER_CONTROL_START_MSK; timer_writew(&nios2_cs.timer, ctrl, ALTERA_TIMER_CONTROL_REG); /* Calibrate the delay loop directly */ lpj_fine = freq / HZ; return 0; } /* * The first timer instance will use as a clockevent. If there are two or * more instances, the second one gets used as clocksource and all * others are unused. */ static int __init nios2_time_init(struct device_node *timer) { static int num_called; int ret; switch (num_called) { case 0: ret = nios2_clockevent_init(timer); break; case 1: ret = nios2_clocksource_init(timer); break; default: ret = 0; break; } num_called++; return ret; } void read_persistent_clock64(struct timespec64 *ts) { ts->tv_sec = mktime64(2007, 1, 1, 0, 0, 0); ts->tv_nsec = 0; } void __init time_init(void) { struct device_node *np; int count = 0; for_each_compatible_node(np, NULL, ALTR_TIMER_COMPATIBLE) count++; if (count < 2) panic("%d timer is found, it needs 2 timers in system\n", count); timer_probe(); } TIMER_OF_DECLARE(nios2_timer, ALTR_TIMER_COMPATIBLE, nios2_time_init);
linux-master
arch/nios2/kernel/time.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright Altera Corporation (C) 2013. All rights reserved */ #include <linux/syscalls.h> #include <linux/signal.h> #include <linux/unistd.h> #include <asm/syscalls.h> #undef __SYSCALL #define __SYSCALL(nr, call) [nr] = (call), void *sys_call_table[__NR_syscalls] = { [0 ... __NR_syscalls-1] = sys_ni_syscall, #include <asm/unistd.h> };
linux-master
arch/nios2/kernel/syscall_table.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Device tree support * * Copyright (C) 2013, 2015 Altera Corporation * Copyright (C) 2010 Thomas Chou <[email protected]> * * Based on MIPS support for CONFIG_OF device tree support * * Copyright (C) 2010 Cisco Systems Inc. <[email protected]> */ #include <linux/init.h> #include <linux/types.h> #include <linux/memblock.h> #include <linux/of.h> #include <linux/of_fdt.h> #include <linux/io.h> #include <asm/sections.h> void __init early_init_devtree(void *params) { __be32 *dtb = (u32 *)__dtb_start; #if defined(CONFIG_NIOS2_DTB_AT_PHYS_ADDR) if (be32_to_cpup((__be32 *)CONFIG_NIOS2_DTB_PHYS_ADDR) == OF_DT_HEADER) { params = (void *)CONFIG_NIOS2_DTB_PHYS_ADDR; early_init_dt_scan(params); return; } #endif if (be32_to_cpu((__be32) *dtb) == OF_DT_HEADER) params = (void *)__dtb_start; early_init_dt_scan(params); }
linux-master
arch/nios2/kernel/prom.c
/* * Copyright (C) 2013-2014 Altera Corporation * Copyright (C) 2011-2012 Tobias Klauser <[email protected]> * Copyright (C) 2004 Microtronix Datacom Ltd * Copyright (C) 1991, 1992 Linus Torvalds * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. */ #include <linux/signal.h> #include <linux/errno.h> #include <linux/ptrace.h> #include <linux/uaccess.h> #include <linux/unistd.h> #include <linux/personality.h> #include <linux/resume_user_mode.h> #include <asm/ucontext.h> #include <asm/cacheflush.h> #define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP))) /* * Do a signal return; undo the signal stack. * * Keep the return code on the stack quadword aligned! * That makes the cache flush below easier. */ struct rt_sigframe { struct siginfo info; struct ucontext uc; }; static inline int rt_restore_ucontext(struct pt_regs *regs, struct switch_stack *sw, struct ucontext __user *uc, int *pr2) { int temp; unsigned long __user *gregs = uc->uc_mcontext.gregs; int err; /* Always make any pending restarted system calls return -EINTR */ current->restart_block.fn = do_no_restart_syscall; err = __get_user(temp, &uc->uc_mcontext.version); if (temp != MCONTEXT_VERSION) goto badframe; /* restore passed registers */ err |= __get_user(regs->r1, &gregs[0]); err |= __get_user(regs->r2, &gregs[1]); err |= __get_user(regs->r3, &gregs[2]); err |= __get_user(regs->r4, &gregs[3]); err |= __get_user(regs->r5, &gregs[4]); err |= __get_user(regs->r6, &gregs[5]); err |= __get_user(regs->r7, &gregs[6]); err |= __get_user(regs->r8, &gregs[7]); err |= __get_user(regs->r9, &gregs[8]); err |= __get_user(regs->r10, &gregs[9]); err |= __get_user(regs->r11, &gregs[10]); err |= __get_user(regs->r12, &gregs[11]); err |= __get_user(regs->r13, &gregs[12]); err |= __get_user(regs->r14, &gregs[13]); err |= __get_user(regs->r15, &gregs[14]); err |= __get_user(sw->r16, &gregs[15]); err |= __get_user(sw->r17, &gregs[16]); err |= __get_user(sw->r18, &gregs[17]); err |= __get_user(sw->r19, &gregs[18]); err |= __get_user(sw->r20, &gregs[19]); err |= __get_user(sw->r21, &gregs[20]); err |= __get_user(sw->r22, &gregs[21]); err |= __get_user(sw->r23, &gregs[22]); /* gregs[23] is handled below */ err |= __get_user(sw->fp, &gregs[24]); /* Verify, should this be settable */ err |= __get_user(sw->gp, &gregs[25]); /* Verify, should this be settable */ err |= __get_user(temp, &gregs[26]); /* Not really necessary no user settable bits */ err |= __get_user(regs->ea, &gregs[27]); err |= __get_user(regs->ra, &gregs[23]); err |= __get_user(regs->sp, &gregs[28]); regs->orig_r2 = -1; /* disable syscall checks */ err |= restore_altstack(&uc->uc_stack); if (err) goto badframe; *pr2 = regs->r2; return err; badframe: return 1; } asmlinkage int do_rt_sigreturn(struct switch_stack *sw) { struct pt_regs *regs = (struct pt_regs *)(sw + 1); /* Verify, can we follow the stack back */ struct rt_sigframe __user *frame; sigset_t set; int rval; frame = (struct rt_sigframe __user *) regs->sp; if (!access_ok(frame, sizeof(*frame))) goto badframe; if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set))) goto badframe; set_current_blocked(&set); if (rt_restore_ucontext(regs, sw, &frame->uc, &rval)) goto badframe; return rval; badframe: force_sig(SIGSEGV); return 0; } static inline int rt_setup_ucontext(struct ucontext __user *uc, struct pt_regs *regs) { struct switch_stack *sw = (struct switch_stack *)regs - 1; unsigned long __user *gregs = uc->uc_mcontext.gregs; int err = 0; err |= __put_user(MCONTEXT_VERSION, &uc->uc_mcontext.version); err |= __put_user(regs->r1, &gregs[0]); err |= __put_user(regs->r2, &gregs[1]); err |= __put_user(regs->r3, &gregs[2]); err |= __put_user(regs->r4, &gregs[3]); err |= __put_user(regs->r5, &gregs[4]); err |= __put_user(regs->r6, &gregs[5]); err |= __put_user(regs->r7, &gregs[6]); err |= __put_user(regs->r8, &gregs[7]); err |= __put_user(regs->r9, &gregs[8]); err |= __put_user(regs->r10, &gregs[9]); err |= __put_user(regs->r11, &gregs[10]); err |= __put_user(regs->r12, &gregs[11]); err |= __put_user(regs->r13, &gregs[12]); err |= __put_user(regs->r14, &gregs[13]); err |= __put_user(regs->r15, &gregs[14]); err |= __put_user(sw->r16, &gregs[15]); err |= __put_user(sw->r17, &gregs[16]); err |= __put_user(sw->r18, &gregs[17]); err |= __put_user(sw->r19, &gregs[18]); err |= __put_user(sw->r20, &gregs[19]); err |= __put_user(sw->r21, &gregs[20]); err |= __put_user(sw->r22, &gregs[21]); err |= __put_user(sw->r23, &gregs[22]); err |= __put_user(regs->ra, &gregs[23]); err |= __put_user(sw->fp, &gregs[24]); err |= __put_user(sw->gp, &gregs[25]); err |= __put_user(regs->ea, &gregs[27]); err |= __put_user(regs->sp, &gregs[28]); return err; } static inline void __user *get_sigframe(struct ksignal *ksig, struct pt_regs *regs, size_t frame_size) { unsigned long usp; /* Default to using normal stack. */ usp = regs->sp; /* This is the X/Open sanctioned signal stack switching. */ usp = sigsp(usp, ksig); /* Verify, is it 32 or 64 bit aligned */ return (void __user *)((usp - frame_size) & -8UL); } static int setup_rt_frame(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs) { struct rt_sigframe __user *frame; int err = 0; frame = get_sigframe(ksig, regs, sizeof(*frame)); if (ksig->ka.sa.sa_flags & SA_SIGINFO) err |= copy_siginfo_to_user(&frame->info, &ksig->info); /* Create the ucontext. */ err |= __put_user(0, &frame->uc.uc_flags); err |= __put_user(0, &frame->uc.uc_link); err |= __save_altstack(&frame->uc.uc_stack, regs->sp); err |= rt_setup_ucontext(&frame->uc, regs); err |= copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)); if (err) goto give_sigsegv; /* Set up to return from userspace; jump to fixed address sigreturn trampoline on kuser page. */ regs->ra = (unsigned long) (0x1044); /* Set up registers for signal handler */ regs->sp = (unsigned long) frame; regs->r4 = (unsigned long) ksig->sig; regs->r5 = (unsigned long) &frame->info; regs->r6 = (unsigned long) &frame->uc; regs->ea = (unsigned long) ksig->ka.sa.sa_handler; return 0; give_sigsegv: force_sigsegv(ksig->sig); return -EFAULT; } /* * OK, we're invoking a handler */ static void handle_signal(struct ksignal *ksig, struct pt_regs *regs) { int ret; sigset_t *oldset = sigmask_to_save(); /* set up the stack frame */ ret = setup_rt_frame(ksig, oldset, regs); signal_setup_done(ret, ksig, 0); } static int do_signal(struct pt_regs *regs) { unsigned int retval = 0, continue_addr = 0, restart_addr = 0; int restart = 0; struct ksignal ksig; current->thread.kregs = regs; /* * If we were from a system call, check for system call restarting... */ if (regs->orig_r2 >= 0 && regs->r1) { continue_addr = regs->ea; restart_addr = continue_addr - 4; retval = regs->r2; /* * Prepare for system call restart. We do this here so that a * debugger will see the already changed PC. */ switch (retval) { case ERESTART_RESTARTBLOCK: restart = -2; fallthrough; case ERESTARTNOHAND: case ERESTARTSYS: case ERESTARTNOINTR: restart++; regs->r2 = regs->orig_r2; regs->r7 = regs->orig_r7; regs->ea = restart_addr; break; } regs->orig_r2 = -1; } if (get_signal(&ksig)) { /* handler */ if (unlikely(restart && regs->ea == restart_addr)) { if (retval == ERESTARTNOHAND || retval == ERESTART_RESTARTBLOCK || (retval == ERESTARTSYS && !(ksig.ka.sa.sa_flags & SA_RESTART))) { regs->r2 = EINTR; regs->r7 = 1; regs->ea = continue_addr; } } handle_signal(&ksig, regs); return 0; } /* * No handler present */ if (unlikely(restart) && regs->ea == restart_addr) { regs->ea = continue_addr; regs->r2 = __NR_restart_syscall; } /* * If there's no signal to deliver, we just put the saved sigmask back. */ restore_saved_sigmask(); return restart; } asmlinkage int do_notify_resume(struct pt_regs *regs) { /* * We want the common case to go fast, which is why we may in certain * cases get here from kernel mode. Just return without doing anything * if so. */ if (!user_mode(regs)) return 0; if (test_thread_flag(TIF_SIGPENDING) || test_thread_flag(TIF_NOTIFY_SIGNAL)) { int restart = do_signal(regs); if (unlikely(restart)) { /* * Restart without handlers. * Deal with it without leaving * the kernel space. */ return restart; } } else if (test_thread_flag(TIF_NOTIFY_RESUME)) resume_user_mode_work(regs); return 0; }
linux-master
arch/nios2/kernel/signal.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Nios2 KGDB support * * Copyright (C) 2015 Altera Corporation * Copyright (C) 2011 Tobias Klauser <[email protected]> * * Based on the code posted by Kazuyasu on the Altera Forum at: * http://www.alteraforum.com/forum/showpost.php?p=77003&postcount=20 */ #include <linux/ptrace.h> #include <linux/kgdb.h> #include <linux/kdebug.h> #include <linux/io.h> static int wait_for_remote_debugger; struct dbg_reg_def_t dbg_reg_def[DBG_MAX_REG_NUM] = { { "zero", GDB_SIZEOF_REG, -1 }, { "at", GDB_SIZEOF_REG, offsetof(struct pt_regs, r1) }, { "r2", GDB_SIZEOF_REG, offsetof(struct pt_regs, r2) }, { "r3", GDB_SIZEOF_REG, offsetof(struct pt_regs, r3) }, { "r4", GDB_SIZEOF_REG, offsetof(struct pt_regs, r4) }, { "r5", GDB_SIZEOF_REG, offsetof(struct pt_regs, r5) }, { "r6", GDB_SIZEOF_REG, offsetof(struct pt_regs, r6) }, { "r7", GDB_SIZEOF_REG, offsetof(struct pt_regs, r7) }, { "r8", GDB_SIZEOF_REG, offsetof(struct pt_regs, r8) }, { "r9", GDB_SIZEOF_REG, offsetof(struct pt_regs, r9) }, { "r10", GDB_SIZEOF_REG, offsetof(struct pt_regs, r10) }, { "r11", GDB_SIZEOF_REG, offsetof(struct pt_regs, r11) }, { "r12", GDB_SIZEOF_REG, offsetof(struct pt_regs, r12) }, { "r13", GDB_SIZEOF_REG, offsetof(struct pt_regs, r13) }, { "r14", GDB_SIZEOF_REG, offsetof(struct pt_regs, r14) }, { "r15", GDB_SIZEOF_REG, offsetof(struct pt_regs, r15) }, { "r16", GDB_SIZEOF_REG, -1 }, { "r17", GDB_SIZEOF_REG, -1 }, { "r18", GDB_SIZEOF_REG, -1 }, { "r19", GDB_SIZEOF_REG, -1 }, { "r20", GDB_SIZEOF_REG, -1 }, { "r21", GDB_SIZEOF_REG, -1 }, { "r22", GDB_SIZEOF_REG, -1 }, { "r23", GDB_SIZEOF_REG, -1 }, { "et", GDB_SIZEOF_REG, -1 }, { "bt", GDB_SIZEOF_REG, -1 }, { "gp", GDB_SIZEOF_REG, offsetof(struct pt_regs, gp) }, { "sp", GDB_SIZEOF_REG, offsetof(struct pt_regs, sp) }, { "fp", GDB_SIZEOF_REG, offsetof(struct pt_regs, fp) }, { "ea", GDB_SIZEOF_REG, -1 }, { "ba", GDB_SIZEOF_REG, -1 }, { "ra", GDB_SIZEOF_REG, offsetof(struct pt_regs, ra) }, { "pc", GDB_SIZEOF_REG, offsetof(struct pt_regs, ea) }, { "status", GDB_SIZEOF_REG, -1 }, { "estatus", GDB_SIZEOF_REG, offsetof(struct pt_regs, estatus) }, { "bstatus", GDB_SIZEOF_REG, -1 }, { "ienable", GDB_SIZEOF_REG, -1 }, { "ipending", GDB_SIZEOF_REG, -1}, { "cpuid", GDB_SIZEOF_REG, -1 }, { "ctl6", GDB_SIZEOF_REG, -1 }, { "exception", GDB_SIZEOF_REG, -1 }, { "pteaddr", GDB_SIZEOF_REG, -1 }, { "tlbacc", GDB_SIZEOF_REG, -1 }, { "tlbmisc", GDB_SIZEOF_REG, -1 }, { "eccinj", GDB_SIZEOF_REG, -1 }, { "badaddr", GDB_SIZEOF_REG, -1 }, { "config", GDB_SIZEOF_REG, -1 }, { "mpubase", GDB_SIZEOF_REG, -1 }, { "mpuacc", GDB_SIZEOF_REG, -1 }, }; char *dbg_get_reg(int regno, void *mem, struct pt_regs *regs) { if (regno >= DBG_MAX_REG_NUM || regno < 0) return NULL; if (dbg_reg_def[regno].offset != -1) memcpy(mem, (void *)regs + dbg_reg_def[regno].offset, dbg_reg_def[regno].size); else memset(mem, 0, dbg_reg_def[regno].size); return dbg_reg_def[regno].name; } int dbg_set_reg(int regno, void *mem, struct pt_regs *regs) { if (regno >= DBG_MAX_REG_NUM || regno < 0) return -EINVAL; if (dbg_reg_def[regno].offset != -1) memcpy((void *)regs + dbg_reg_def[regno].offset, mem, dbg_reg_def[regno].size); return 0; } void sleeping_thread_to_gdb_regs(unsigned long *gdb_regs, struct task_struct *p) { memset((char *)gdb_regs, 0, NUMREGBYTES); gdb_regs[GDB_SP] = p->thread.kregs->sp; gdb_regs[GDB_PC] = p->thread.kregs->ea; } void kgdb_arch_set_pc(struct pt_regs *regs, unsigned long pc) { regs->ea = pc; } int kgdb_arch_handle_exception(int vector, int signo, int err_code, char *remcom_in_buffer, char *remcom_out_buffer, struct pt_regs *regs) { char *ptr; unsigned long addr; switch (remcom_in_buffer[0]) { case 's': case 'c': /* handle the optional parameters */ ptr = &remcom_in_buffer[1]; if (kgdb_hex2long(&ptr, &addr)) regs->ea = addr; return 0; } return -1; /* this means that we do not want to exit from the handler */ } asmlinkage void kgdb_breakpoint_c(struct pt_regs *regs) { /* * The breakpoint entry code has moved the PC on by 4 bytes, so we must * move it back. This could be done on the host but we do it here */ if (!wait_for_remote_debugger) regs->ea -= 4; else /* pass the first trap 30 code */ wait_for_remote_debugger = 0; kgdb_handle_exception(30, SIGTRAP, 0, regs); } int kgdb_arch_init(void) { wait_for_remote_debugger = 1; return 0; } void kgdb_arch_exit(void) { /* Nothing to do */ } const struct kgdb_arch arch_kgdb_ops = { /* Breakpoint instruction: trap 30 */ .gdb_bpt_instr = { 0xba, 0x6f, 0x3b, 0x00 }, };
linux-master
arch/nios2/kernel/kgdb.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2013 Altera Corporation * Copyright (C) 2011 Tobias Klauser <[email protected]> * * Based on cpuinfo.c from microblaze */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/seq_file.h> #include <linux/string.h> #include <linux/of.h> #include <asm/cpuinfo.h> struct cpuinfo cpuinfo; #define err_cpu(x) \ pr_err("ERROR: Nios II " x " different for kernel and DTS\n") static inline u32 fcpu(struct device_node *cpu, const char *n) { u32 val = 0; of_property_read_u32(cpu, n, &val); return val; } void __init setup_cpuinfo(void) { struct device_node *cpu; const char *str; int len; cpu = of_get_cpu_node(0, NULL); if (!cpu) panic("%s: No CPU found in devicetree!\n", __func__); if (!of_property_read_bool(cpu, "altr,has-initda")) panic("initda instruction is unimplemented. Please update your " "hardware system to have more than 4-byte line data " "cache\n"); cpuinfo.cpu_clock_freq = fcpu(cpu, "clock-frequency"); str = of_get_property(cpu, "altr,implementation", &len); if (str) strscpy(cpuinfo.cpu_impl, str, sizeof(cpuinfo.cpu_impl)); else strcpy(cpuinfo.cpu_impl, "<unknown>"); cpuinfo.has_div = of_property_read_bool(cpu, "altr,has-div"); cpuinfo.has_mul = of_property_read_bool(cpu, "altr,has-mul"); cpuinfo.has_mulx = of_property_read_bool(cpu, "altr,has-mulx"); cpuinfo.has_bmx = of_property_read_bool(cpu, "altr,has-bmx"); cpuinfo.has_cdx = of_property_read_bool(cpu, "altr,has-cdx"); cpuinfo.mmu = of_property_read_bool(cpu, "altr,has-mmu"); if (IS_ENABLED(CONFIG_NIOS2_HW_DIV_SUPPORT) && !cpuinfo.has_div) err_cpu("DIV"); if (IS_ENABLED(CONFIG_NIOS2_HW_MUL_SUPPORT) && !cpuinfo.has_mul) err_cpu("MUL"); if (IS_ENABLED(CONFIG_NIOS2_HW_MULX_SUPPORT) && !cpuinfo.has_mulx) err_cpu("MULX"); if (IS_ENABLED(CONFIG_NIOS2_BMX_SUPPORT) && !cpuinfo.has_bmx) err_cpu("BMX"); if (IS_ENABLED(CONFIG_NIOS2_CDX_SUPPORT) && !cpuinfo.has_cdx) err_cpu("CDX"); cpuinfo.tlb_num_ways = fcpu(cpu, "altr,tlb-num-ways"); if (!cpuinfo.tlb_num_ways) panic("altr,tlb-num-ways can't be 0. Please check your hardware " "system\n"); cpuinfo.icache_line_size = fcpu(cpu, "icache-line-size"); cpuinfo.icache_size = fcpu(cpu, "icache-size"); if (CONFIG_NIOS2_ICACHE_SIZE != cpuinfo.icache_size) pr_warn("Warning: icache size configuration mismatch " "(0x%x vs 0x%x) of CONFIG_NIOS2_ICACHE_SIZE vs " "device tree icache-size\n", CONFIG_NIOS2_ICACHE_SIZE, cpuinfo.icache_size); cpuinfo.dcache_line_size = fcpu(cpu, "dcache-line-size"); if (CONFIG_NIOS2_DCACHE_LINE_SIZE != cpuinfo.dcache_line_size) pr_warn("Warning: dcache line size configuration mismatch " "(0x%x vs 0x%x) of CONFIG_NIOS2_DCACHE_LINE_SIZE vs " "device tree dcache-line-size\n", CONFIG_NIOS2_DCACHE_LINE_SIZE, cpuinfo.dcache_line_size); cpuinfo.dcache_size = fcpu(cpu, "dcache-size"); if (CONFIG_NIOS2_DCACHE_SIZE != cpuinfo.dcache_size) pr_warn("Warning: dcache size configuration mismatch " "(0x%x vs 0x%x) of CONFIG_NIOS2_DCACHE_SIZE vs " "device tree dcache-size\n", CONFIG_NIOS2_DCACHE_SIZE, cpuinfo.dcache_size); cpuinfo.tlb_pid_num_bits = fcpu(cpu, "altr,pid-num-bits"); cpuinfo.tlb_num_ways_log2 = ilog2(cpuinfo.tlb_num_ways); cpuinfo.tlb_num_entries = fcpu(cpu, "altr,tlb-num-entries"); cpuinfo.tlb_num_lines = cpuinfo.tlb_num_entries / cpuinfo.tlb_num_ways; cpuinfo.tlb_ptr_sz = fcpu(cpu, "altr,tlb-ptr-sz"); cpuinfo.reset_addr = fcpu(cpu, "altr,reset-addr"); cpuinfo.exception_addr = fcpu(cpu, "altr,exception-addr"); cpuinfo.fast_tlb_miss_exc_addr = fcpu(cpu, "altr,fast-tlb-miss-addr"); of_node_put(cpu); } #ifdef CONFIG_PROC_FS /* * Get CPU information for use by the procfs. */ static int show_cpuinfo(struct seq_file *m, void *v) { const u32 clockfreq = cpuinfo.cpu_clock_freq; seq_printf(m, "CPU:\t\tNios II/%s\n" "REV:\t\t%i\n" "MMU:\t\t%s\n" "FPU:\t\tnone\n" "Clocking:\t%u.%02u MHz\n" "BogoMips:\t%lu.%02lu\n" "Calibration:\t%lu loops\n", cpuinfo.cpu_impl, CONFIG_NIOS2_ARCH_REVISION, cpuinfo.mmu ? "present" : "none", clockfreq / 1000000, (clockfreq / 100000) % 10, (loops_per_jiffy * HZ) / 500000, ((loops_per_jiffy * HZ) / 5000) % 100, (loops_per_jiffy * HZ)); seq_printf(m, "HW:\n" " MUL:\t\t%s\n" " MULX:\t\t%s\n" " DIV:\t\t%s\n" " BMX:\t\t%s\n" " CDX:\t\t%s\n", cpuinfo.has_mul ? "yes" : "no", cpuinfo.has_mulx ? "yes" : "no", cpuinfo.has_div ? "yes" : "no", cpuinfo.has_bmx ? "yes" : "no", cpuinfo.has_cdx ? "yes" : "no"); seq_printf(m, "Icache:\t\t%ukB, line length: %u\n", cpuinfo.icache_size >> 10, cpuinfo.icache_line_size); seq_printf(m, "Dcache:\t\t%ukB, line length: %u\n", cpuinfo.dcache_size >> 10, cpuinfo.dcache_line_size); seq_printf(m, "TLB:\t\t%u ways, %u entries, %u PID bits\n", cpuinfo.tlb_num_ways, cpuinfo.tlb_num_entries, cpuinfo.tlb_pid_num_bits); return 0; } static void *cpuinfo_start(struct seq_file *m, loff_t *pos) { unsigned long i = *pos; return i < num_possible_cpus() ? (void *) (i + 1) : NULL; } static void *cpuinfo_next(struct seq_file *m, void *v, loff_t *pos) { ++*pos; return cpuinfo_start(m, pos); } static void cpuinfo_stop(struct seq_file *m, void *v) { } const struct seq_operations cpuinfo_op = { .start = cpuinfo_start, .next = cpuinfo_next, .stop = cpuinfo_stop, .show = show_cpuinfo }; #endif /* CONFIG_PROC_FS */
linux-master
arch/nios2/kernel/cpuinfo.c
/* * Copyright (c) 2002 - 2011 Tony Finch <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * unifdef - remove ifdef'ed lines * * This code was derived from software contributed to Berkeley by Dave Yost. * It was rewritten to support ANSI C by Tony Finch. The original version * of unifdef carried the 4-clause BSD copyright licence. None of its code * remains in this version (though some of the names remain) so it now * carries a more liberal licence. * * Wishlist: * provide an option which will append the name of the * appropriate symbol after #else's and #endif's * provide an option which will check symbols after * #else's and #endif's to see that they match their * corresponding #ifdef or #ifndef * * These require better buffer handling, which would also make * it possible to handle all "dodgy" directives correctly. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> const char copyright[] = "@(#) $Version: unifdef-2.5 $\n" "@(#) $Author: Tony Finch ([email protected]) $\n" "@(#) $URL: http://dotat.at/prog/unifdef $\n" ; /* types of input lines: */ typedef enum { LT_TRUEI, /* a true #if with ignore flag */ LT_FALSEI, /* a false #if with ignore flag */ LT_IF, /* an unknown #if */ LT_TRUE, /* a true #if */ LT_FALSE, /* a false #if */ LT_ELIF, /* an unknown #elif */ LT_ELTRUE, /* a true #elif */ LT_ELFALSE, /* a false #elif */ LT_ELSE, /* #else */ LT_ENDIF, /* #endif */ LT_DODGY, /* flag: directive is not on one line */ LT_DODGY_LAST = LT_DODGY + LT_ENDIF, LT_PLAIN, /* ordinary line */ LT_EOF, /* end of file */ LT_ERROR, /* unevaluable #if */ LT_COUNT } Linetype; static char const * const linetype_name[] = { "TRUEI", "FALSEI", "IF", "TRUE", "FALSE", "ELIF", "ELTRUE", "ELFALSE", "ELSE", "ENDIF", "DODGY TRUEI", "DODGY FALSEI", "DODGY IF", "DODGY TRUE", "DODGY FALSE", "DODGY ELIF", "DODGY ELTRUE", "DODGY ELFALSE", "DODGY ELSE", "DODGY ENDIF", "PLAIN", "EOF", "ERROR" }; /* state of #if processing */ typedef enum { IS_OUTSIDE, IS_FALSE_PREFIX, /* false #if followed by false #elifs */ IS_TRUE_PREFIX, /* first non-false #(el)if is true */ IS_PASS_MIDDLE, /* first non-false #(el)if is unknown */ IS_FALSE_MIDDLE, /* a false #elif after a pass state */ IS_TRUE_MIDDLE, /* a true #elif after a pass state */ IS_PASS_ELSE, /* an else after a pass state */ IS_FALSE_ELSE, /* an else after a true state */ IS_TRUE_ELSE, /* an else after only false states */ IS_FALSE_TRAILER, /* #elifs after a true are false */ IS_COUNT } Ifstate; static char const * const ifstate_name[] = { "OUTSIDE", "FALSE_PREFIX", "TRUE_PREFIX", "PASS_MIDDLE", "FALSE_MIDDLE", "TRUE_MIDDLE", "PASS_ELSE", "FALSE_ELSE", "TRUE_ELSE", "FALSE_TRAILER" }; /* state of comment parser */ typedef enum { NO_COMMENT = false, /* outside a comment */ C_COMMENT, /* in a comment like this one */ CXX_COMMENT, /* between // and end of line */ STARTING_COMMENT, /* just after slash-backslash-newline */ FINISHING_COMMENT, /* star-backslash-newline in a C comment */ CHAR_LITERAL, /* inside '' */ STRING_LITERAL /* inside "" */ } Comment_state; static char const * const comment_name[] = { "NO", "C", "CXX", "STARTING", "FINISHING", "CHAR", "STRING" }; /* state of preprocessor line parser */ typedef enum { LS_START, /* only space and comments on this line */ LS_HASH, /* only space, comments, and a hash */ LS_DIRTY /* this line can't be a preprocessor line */ } Line_state; static char const * const linestate_name[] = { "START", "HASH", "DIRTY" }; /* * Minimum translation limits from ISO/IEC 9899:1999 5.2.4.1 */ #define MAXDEPTH 64 /* maximum #if nesting */ #define MAXLINE 4096 /* maximum length of line */ #define MAXSYMS 4096 /* maximum number of symbols */ /* * Sometimes when editing a keyword the replacement text is longer, so * we leave some space at the end of the tline buffer to accommodate this. */ #define EDITSLOP 10 /* * For temporary filenames */ #define TEMPLATE "unifdef.XXXXXX" /* * Globals. */ static bool compblank; /* -B: compress blank lines */ static bool lnblank; /* -b: blank deleted lines */ static bool complement; /* -c: do the complement */ static bool debugging; /* -d: debugging reports */ static bool iocccok; /* -e: fewer IOCCC errors */ static bool strictlogic; /* -K: keep ambiguous #ifs */ static bool killconsts; /* -k: eval constant #ifs */ static bool lnnum; /* -n: add #line directives */ static bool symlist; /* -s: output symbol list */ static bool symdepth; /* -S: output symbol depth */ static bool text; /* -t: this is a text file */ static const char *symname[MAXSYMS]; /* symbol name */ static const char *value[MAXSYMS]; /* -Dsym=value */ static bool ignore[MAXSYMS]; /* -iDsym or -iUsym */ static int nsyms; /* number of symbols */ static FILE *input; /* input file pointer */ static const char *filename; /* input file name */ static int linenum; /* current line number */ static FILE *output; /* output file pointer */ static const char *ofilename; /* output file name */ static bool overwriting; /* output overwrites input */ static char tempname[FILENAME_MAX]; /* used when overwriting */ static char tline[MAXLINE+EDITSLOP];/* input buffer plus space */ static char *keyword; /* used for editing #elif's */ static const char *newline; /* input file format */ static const char newline_unix[] = "\n"; static const char newline_crlf[] = "\r\n"; static Comment_state incomment; /* comment parser state */ static Line_state linestate; /* #if line parser state */ static Ifstate ifstate[MAXDEPTH]; /* #if processor state */ static bool ignoring[MAXDEPTH]; /* ignore comments state */ static int stifline[MAXDEPTH]; /* start of current #if */ static int depth; /* current #if nesting */ static int delcount; /* count of deleted lines */ static unsigned blankcount; /* count of blank lines */ static unsigned blankmax; /* maximum recent blankcount */ static bool constexpr; /* constant #if expression */ static bool zerosyms = true; /* to format symdepth output */ static bool firstsym; /* ditto */ static int exitstat; /* program exit status */ static void addsym(bool, bool, char *); static void closeout(void); static void debug(const char *, ...); static void done(void); static void error(const char *); static int findsym(const char *); static void flushline(bool); static Linetype parseline(void); static Linetype ifeval(const char **); static void ignoreoff(void); static void ignoreon(void); static void keywordedit(const char *); static void nest(void); static void process(void); static const char *skipargs(const char *); static const char *skipcomment(const char *); static const char *skipsym(const char *); static void state(Ifstate); static int strlcmp(const char *, const char *, size_t); static void unnest(void); static void usage(void); static void version(void); #define endsym(c) (!isalnum((unsigned char)c) && c != '_') /* * The main program. */ int main(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "i:D:U:I:o:bBcdeKklnsStV")) != -1) switch (opt) { case 'i': /* treat stuff controlled by these symbols as text */ /* * For strict backwards-compatibility the U or D * should be immediately after the -i but it doesn't * matter much if we relax that requirement. */ opt = *optarg++; if (opt == 'D') addsym(true, true, optarg); else if (opt == 'U') addsym(true, false, optarg); else usage(); break; case 'D': /* define a symbol */ addsym(false, true, optarg); break; case 'U': /* undef a symbol */ addsym(false, false, optarg); break; case 'I': /* no-op for compatibility with cpp */ break; case 'b': /* blank deleted lines instead of omitting them */ case 'l': /* backwards compatibility */ lnblank = true; break; case 'B': /* compress blank lines around removed section */ compblank = true; break; case 'c': /* treat -D as -U and vice versa */ complement = true; break; case 'd': debugging = true; break; case 'e': /* fewer errors from dodgy lines */ iocccok = true; break; case 'K': /* keep ambiguous #ifs */ strictlogic = true; break; case 'k': /* process constant #ifs */ killconsts = true; break; case 'n': /* add #line directive after deleted lines */ lnnum = true; break; case 'o': /* output to a file */ ofilename = optarg; break; case 's': /* only output list of symbols that control #ifs */ symlist = true; break; case 'S': /* list symbols with their nesting depth */ symlist = symdepth = true; break; case 't': /* don't parse C comments */ text = true; break; case 'V': /* print version */ version(); default: usage(); } argc -= optind; argv += optind; if (compblank && lnblank) errx(2, "-B and -b are mutually exclusive"); if (argc > 1) { errx(2, "can only do one file"); } else if (argc == 1 && strcmp(*argv, "-") != 0) { filename = *argv; input = fopen(filename, "rb"); if (input == NULL) err(2, "can't open %s", filename); } else { filename = "[stdin]"; input = stdin; } if (ofilename == NULL) { ofilename = "[stdout]"; output = stdout; } else { struct stat ist, ost; if (stat(ofilename, &ost) == 0 && fstat(fileno(input), &ist) == 0) overwriting = (ist.st_dev == ost.st_dev && ist.st_ino == ost.st_ino); if (overwriting) { const char *dirsep; int ofd; dirsep = strrchr(ofilename, '/'); if (dirsep != NULL) snprintf(tempname, sizeof(tempname), "%.*s/" TEMPLATE, (int)(dirsep - ofilename), ofilename); else snprintf(tempname, sizeof(tempname), TEMPLATE); ofd = mkstemp(tempname); if (ofd != -1) output = fdopen(ofd, "wb+"); if (output == NULL) err(2, "can't create temporary file"); fchmod(ofd, ist.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO)); } else { output = fopen(ofilename, "wb"); if (output == NULL) err(2, "can't open %s", ofilename); } } process(); abort(); /* bug */ } static void version(void) { const char *c = copyright; for (;;) { while (*++c != '$') if (*c == '\0') exit(0); while (*++c != '$') putc(*c, stderr); putc('\n', stderr); } } static void usage(void) { fprintf(stderr, "usage: unifdef [-bBcdeKknsStV] [-Ipath]" " [-Dsym[=val]] [-Usym] [-iDsym[=val]] [-iUsym] ... [file]\n"); exit(2); } /* * A state transition function alters the global #if processing state * in a particular way. The table below is indexed by the current * processing state and the type of the current line. * * Nesting is handled by keeping a stack of states; some transition * functions increase or decrease the depth. They also maintain the * ignore state on a stack. In some complicated cases they have to * alter the preprocessor directive, as follows. * * When we have processed a group that starts off with a known-false * #if/#elif sequence (which has therefore been deleted) followed by a * #elif that we don't understand and therefore must keep, we edit the * latter into a #if to keep the nesting correct. We use memcpy() to * overwrite the 4 byte token "elif" with "if " without a '\0' byte. * * When we find a true #elif in a group, the following block will * always be kept and the rest of the sequence after the next #elif or * #else will be discarded. We edit the #elif into a #else and the * following directive to #endif since this has the desired behaviour. * * "Dodgy" directives are split across multiple lines, the most common * example being a multi-line comment hanging off the right of the * directive. We can handle them correctly only if there is no change * from printing to dropping (or vice versa) caused by that directive. * If the directive is the first of a group we have a choice between * failing with an error, or passing it through unchanged instead of * evaluating it. The latter is not the default to avoid questions from * users about unifdef unexpectedly leaving behind preprocessor directives. */ typedef void state_fn(void); /* report an error */ static void Eelif (void) { error("Inappropriate #elif"); } static void Eelse (void) { error("Inappropriate #else"); } static void Eendif(void) { error("Inappropriate #endif"); } static void Eeof (void) { error("Premature EOF"); } static void Eioccc(void) { error("Obfuscated preprocessor control line"); } /* plain line handling */ static void print (void) { flushline(true); } static void drop (void) { flushline(false); } /* output lacks group's start line */ static void Strue (void) { drop(); ignoreoff(); state(IS_TRUE_PREFIX); } static void Sfalse(void) { drop(); ignoreoff(); state(IS_FALSE_PREFIX); } static void Selse (void) { drop(); state(IS_TRUE_ELSE); } /* print/pass this block */ static void Pelif (void) { print(); ignoreoff(); state(IS_PASS_MIDDLE); } static void Pelse (void) { print(); state(IS_PASS_ELSE); } static void Pendif(void) { print(); unnest(); } /* discard this block */ static void Dfalse(void) { drop(); ignoreoff(); state(IS_FALSE_TRAILER); } static void Delif (void) { drop(); ignoreoff(); state(IS_FALSE_MIDDLE); } static void Delse (void) { drop(); state(IS_FALSE_ELSE); } static void Dendif(void) { drop(); unnest(); } /* first line of group */ static void Fdrop (void) { nest(); Dfalse(); } static void Fpass (void) { nest(); Pelif(); } static void Ftrue (void) { nest(); Strue(); } static void Ffalse(void) { nest(); Sfalse(); } /* variable pedantry for obfuscated lines */ static void Oiffy (void) { if (!iocccok) Eioccc(); Fpass(); ignoreon(); } static void Oif (void) { if (!iocccok) Eioccc(); Fpass(); } static void Oelif (void) { if (!iocccok) Eioccc(); Pelif(); } /* ignore comments in this block */ static void Idrop (void) { Fdrop(); ignoreon(); } static void Itrue (void) { Ftrue(); ignoreon(); } static void Ifalse(void) { Ffalse(); ignoreon(); } /* modify this line */ static void Mpass (void) { memcpy(keyword, "if ", 4); Pelif(); } static void Mtrue (void) { keywordedit("else"); state(IS_TRUE_MIDDLE); } static void Melif (void) { keywordedit("endif"); state(IS_FALSE_TRAILER); } static void Melse (void) { keywordedit("endif"); state(IS_FALSE_ELSE); } static state_fn * const trans_table[IS_COUNT][LT_COUNT] = { /* IS_OUTSIDE */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Eendif, Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eendif, print, done, abort }, /* IS_FALSE_PREFIX */ { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Strue, Sfalse,Selse, Dendif, Idrop, Idrop, Fdrop, Fdrop, Fdrop, Mpass, Eioccc,Eioccc,Eioccc,Eioccc, drop, Eeof, abort }, /* IS_TRUE_PREFIX */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Dfalse,Dfalse,Dfalse,Delse, Dendif, Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc, print, Eeof, abort }, /* IS_PASS_MIDDLE */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Pelif, Mtrue, Delif, Pelse, Pendif, Oiffy, Oiffy, Fpass, Oif, Oif, Pelif, Oelif, Oelif, Pelse, Pendif, print, Eeof, abort }, /* IS_FALSE_MIDDLE */ { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Pelif, Mtrue, Delif, Pelse, Pendif, Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eioccc,Eioccc,Eioccc,Eioccc,Eioccc, drop, Eeof, abort }, /* IS_TRUE_MIDDLE */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Melif, Melif, Melif, Melse, Pendif, Oiffy, Oiffy, Fpass, Oif, Oif, Eioccc,Eioccc,Eioccc,Eioccc,Pendif, print, Eeof, abort }, /* IS_PASS_ELSE */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Pendif, Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Pendif, print, Eeof, abort }, /* IS_FALSE_ELSE */ { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Dendif, Idrop, Idrop, Fdrop, Fdrop, Fdrop, Eelif, Eelif, Eelif, Eelse, Eioccc, drop, Eeof, abort }, /* IS_TRUE_ELSE */ { Itrue, Ifalse,Fpass, Ftrue, Ffalse,Eelif, Eelif, Eelif, Eelse, Dendif, Oiffy, Oiffy, Fpass, Oif, Oif, Eelif, Eelif, Eelif, Eelse, Eioccc, print, Eeof, abort }, /* IS_FALSE_TRAILER */ { Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Dendif, Idrop, Idrop, Fdrop, Fdrop, Fdrop, Dfalse,Dfalse,Dfalse,Delse, Eioccc, drop, Eeof, abort } /*TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF TRUEI FALSEI IF TRUE FALSE ELIF ELTRUE ELFALSE ELSE ENDIF (DODGY) PLAIN EOF ERROR */ }; /* * State machine utility functions */ static void ignoreoff(void) { if (depth == 0) abort(); /* bug */ ignoring[depth] = ignoring[depth-1]; } static void ignoreon(void) { ignoring[depth] = true; } static void keywordedit(const char *replacement) { snprintf(keyword, tline + sizeof(tline) - keyword, "%s%s", replacement, newline); print(); } static void nest(void) { if (depth > MAXDEPTH-1) abort(); /* bug */ if (depth == MAXDEPTH-1) error("Too many levels of nesting"); depth += 1; stifline[depth] = linenum; } static void unnest(void) { if (depth == 0) abort(); /* bug */ depth -= 1; } static void state(Ifstate is) { ifstate[depth] = is; } /* * Write a line to the output or not, according to command line options. */ static void flushline(bool keep) { if (symlist) return; if (keep ^ complement) { bool blankline = tline[strspn(tline, " \t\r\n")] == '\0'; if (blankline && compblank && blankcount != blankmax) { delcount += 1; blankcount += 1; } else { if (lnnum && delcount > 0) printf("#line %d%s", linenum, newline); fputs(tline, output); delcount = 0; blankmax = blankcount = blankline ? blankcount + 1 : 0; } } else { if (lnblank) fputs(newline, output); exitstat = 1; delcount += 1; blankcount = 0; } if (debugging) fflush(output); } /* * The driver for the state machine. */ static void process(void) { /* When compressing blank lines, act as if the file is preceded by a large number of blank lines. */ blankmax = blankcount = 1000; for (;;) { Linetype lineval = parseline(); trans_table[ifstate[depth]][lineval](); debug("process line %d %s -> %s depth %d", linenum, linetype_name[lineval], ifstate_name[ifstate[depth]], depth); } } /* * Flush the output and handle errors. */ static void closeout(void) { if (symdepth && !zerosyms) printf("\n"); if (fclose(output) == EOF) { warn("couldn't write to %s", ofilename); if (overwriting) { unlink(tempname); errx(2, "%s unchanged", filename); } else { exit(2); } } } /* * Clean up and exit. */ static void done(void) { if (incomment) error("EOF in comment"); closeout(); if (overwriting && rename(tempname, ofilename) == -1) { warn("couldn't rename temporary file"); unlink(tempname); errx(2, "%s unchanged", ofilename); } exit(exitstat); } /* * Parse a line and determine its type. We keep the preprocessor line * parser state between calls in the global variable linestate, with * help from skipcomment(). */ static Linetype parseline(void) { const char *cp; int cursym; int kwlen; Linetype retval; Comment_state wascomment; linenum++; if (fgets(tline, MAXLINE, input) == NULL) return (LT_EOF); if (newline == NULL) { if (strrchr(tline, '\n') == strrchr(tline, '\r') + 1) newline = newline_crlf; else newline = newline_unix; } retval = LT_PLAIN; wascomment = incomment; cp = skipcomment(tline); if (linestate == LS_START) { if (*cp == '#') { linestate = LS_HASH; firstsym = true; cp = skipcomment(cp + 1); } else if (*cp != '\0') linestate = LS_DIRTY; } if (!incomment && linestate == LS_HASH) { keyword = tline + (cp - tline); cp = skipsym(cp); kwlen = cp - keyword; /* no way can we deal with a continuation inside a keyword */ if (strncmp(cp, "\\\r\n", 3) == 0 || strncmp(cp, "\\\n", 2) == 0) Eioccc(); if (strlcmp("ifdef", keyword, kwlen) == 0 || strlcmp("ifndef", keyword, kwlen) == 0) { cp = skipcomment(cp); if ((cursym = findsym(cp)) < 0) retval = LT_IF; else { retval = (keyword[2] == 'n') ? LT_FALSE : LT_TRUE; if (value[cursym] == NULL) retval = (retval == LT_TRUE) ? LT_FALSE : LT_TRUE; if (ignore[cursym]) retval = (retval == LT_TRUE) ? LT_TRUEI : LT_FALSEI; } cp = skipsym(cp); } else if (strlcmp("if", keyword, kwlen) == 0) retval = ifeval(&cp); else if (strlcmp("elif", keyword, kwlen) == 0) retval = ifeval(&cp) - LT_IF + LT_ELIF; else if (strlcmp("else", keyword, kwlen) == 0) retval = LT_ELSE; else if (strlcmp("endif", keyword, kwlen) == 0) retval = LT_ENDIF; else { linestate = LS_DIRTY; retval = LT_PLAIN; } cp = skipcomment(cp); if (*cp != '\0') { linestate = LS_DIRTY; if (retval == LT_TRUE || retval == LT_FALSE || retval == LT_TRUEI || retval == LT_FALSEI) retval = LT_IF; if (retval == LT_ELTRUE || retval == LT_ELFALSE) retval = LT_ELIF; } if (retval != LT_PLAIN && (wascomment || incomment)) { retval += LT_DODGY; if (incomment) linestate = LS_DIRTY; } /* skipcomment normally changes the state, except if the last line of the file lacks a newline, or if there is too much whitespace in a directive */ if (linestate == LS_HASH) { size_t len = cp - tline; if (fgets(tline + len, MAXLINE - len, input) == NULL) { /* append the missing newline */ strcpy(tline + len, newline); cp += strlen(newline); linestate = LS_START; } else { linestate = LS_DIRTY; } } } if (linestate == LS_DIRTY) { while (*cp != '\0') cp = skipcomment(cp + 1); } debug("parser line %d state %s comment %s line", linenum, comment_name[incomment], linestate_name[linestate]); return (retval); } /* * These are the binary operators that are supported by the expression * evaluator. */ static Linetype op_strict(int *p, int v, Linetype at, Linetype bt) { if(at == LT_IF || bt == LT_IF) return (LT_IF); return (*p = v, v ? LT_TRUE : LT_FALSE); } static Linetype op_lt(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a < b, at, bt); } static Linetype op_gt(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a > b, at, bt); } static Linetype op_le(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a <= b, at, bt); } static Linetype op_ge(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a >= b, at, bt); } static Linetype op_eq(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a == b, at, bt); } static Linetype op_ne(int *p, Linetype at, int a, Linetype bt, int b) { return op_strict(p, a != b, at, bt); } static Linetype op_or(int *p, Linetype at, int a, Linetype bt, int b) { if (!strictlogic && (at == LT_TRUE || bt == LT_TRUE)) return (*p = 1, LT_TRUE); return op_strict(p, a || b, at, bt); } static Linetype op_and(int *p, Linetype at, int a, Linetype bt, int b) { if (!strictlogic && (at == LT_FALSE || bt == LT_FALSE)) return (*p = 0, LT_FALSE); return op_strict(p, a && b, at, bt); } /* * An evaluation function takes three arguments, as follows: (1) a pointer to * an element of the precedence table which lists the operators at the current * level of precedence; (2) a pointer to an integer which will receive the * value of the expression; and (3) a pointer to a char* that points to the * expression to be evaluated and that is updated to the end of the expression * when evaluation is complete. The function returns LT_FALSE if the value of * the expression is zero, LT_TRUE if it is non-zero, LT_IF if the expression * depends on an unknown symbol, or LT_ERROR if there is a parse failure. */ struct ops; typedef Linetype eval_fn(const struct ops *, int *, const char **); static eval_fn eval_table, eval_unary; /* * The precedence table. Expressions involving binary operators are evaluated * in a table-driven way by eval_table. When it evaluates a subexpression it * calls the inner function with its first argument pointing to the next * element of the table. Innermost expressions have special non-table-driven * handling. */ static const struct ops { eval_fn *inner; struct op { const char *str; Linetype (*fn)(int *, Linetype, int, Linetype, int); } op[5]; } eval_ops[] = { { eval_table, { { "||", op_or } } }, { eval_table, { { "&&", op_and } } }, { eval_table, { { "==", op_eq }, { "!=", op_ne } } }, { eval_unary, { { "<=", op_le }, { ">=", op_ge }, { "<", op_lt }, { ">", op_gt } } } }; /* * Function for evaluating the innermost parts of expressions, * viz. !expr (expr) number defined(symbol) symbol * We reset the constexpr flag in the last two cases. */ static Linetype eval_unary(const struct ops *ops, int *valp, const char **cpp) { const char *cp; char *ep; int sym; bool defparen; Linetype lt; cp = skipcomment(*cpp); if (*cp == '!') { debug("eval%d !", ops - eval_ops); cp++; lt = eval_unary(ops, valp, &cp); if (lt == LT_ERROR) return (LT_ERROR); if (lt != LT_IF) { *valp = !*valp; lt = *valp ? LT_TRUE : LT_FALSE; } } else if (*cp == '(') { cp++; debug("eval%d (", ops - eval_ops); lt = eval_table(eval_ops, valp, &cp); if (lt == LT_ERROR) return (LT_ERROR); cp = skipcomment(cp); if (*cp++ != ')') return (LT_ERROR); } else if (isdigit((unsigned char)*cp)) { debug("eval%d number", ops - eval_ops); *valp = strtol(cp, &ep, 0); if (ep == cp) return (LT_ERROR); lt = *valp ? LT_TRUE : LT_FALSE; cp = skipsym(cp); } else if (strncmp(cp, "defined", 7) == 0 && endsym(cp[7])) { cp = skipcomment(cp+7); debug("eval%d defined", ops - eval_ops); if (*cp == '(') { cp = skipcomment(cp+1); defparen = true; } else { defparen = false; } sym = findsym(cp); if (sym < 0) { lt = LT_IF; } else { *valp = (value[sym] != NULL); lt = *valp ? LT_TRUE : LT_FALSE; } cp = skipsym(cp); cp = skipcomment(cp); if (defparen && *cp++ != ')') return (LT_ERROR); constexpr = false; } else if (!endsym(*cp)) { debug("eval%d symbol", ops - eval_ops); sym = findsym(cp); cp = skipsym(cp); if (sym < 0) { lt = LT_IF; cp = skipargs(cp); } else if (value[sym] == NULL) { *valp = 0; lt = LT_FALSE; } else { *valp = strtol(value[sym], &ep, 0); if (*ep != '\0' || ep == value[sym]) return (LT_ERROR); lt = *valp ? LT_TRUE : LT_FALSE; cp = skipargs(cp); } constexpr = false; } else { debug("eval%d bad expr", ops - eval_ops); return (LT_ERROR); } *cpp = cp; debug("eval%d = %d", ops - eval_ops, *valp); return (lt); } /* * Table-driven evaluation of binary operators. */ static Linetype eval_table(const struct ops *ops, int *valp, const char **cpp) { const struct op *op; const char *cp; int val; Linetype lt, rt; debug("eval%d", ops - eval_ops); cp = *cpp; lt = ops->inner(ops+1, valp, &cp); if (lt == LT_ERROR) return (LT_ERROR); for (;;) { cp = skipcomment(cp); for (op = ops->op; op->str != NULL; op++) if (strncmp(cp, op->str, strlen(op->str)) == 0) break; if (op->str == NULL) break; cp += strlen(op->str); debug("eval%d %s", ops - eval_ops, op->str); rt = ops->inner(ops+1, &val, &cp); if (rt == LT_ERROR) return (LT_ERROR); lt = op->fn(valp, lt, *valp, rt, val); } *cpp = cp; debug("eval%d = %d", ops - eval_ops, *valp); debug("eval%d lt = %s", ops - eval_ops, linetype_name[lt]); return (lt); } /* * Evaluate the expression on a #if or #elif line. If we can work out * the result we return LT_TRUE or LT_FALSE accordingly, otherwise we * return just a generic LT_IF. */ static Linetype ifeval(const char **cpp) { int ret; int val = 0; debug("eval %s", *cpp); constexpr = killconsts ? false : true; ret = eval_table(eval_ops, &val, cpp); debug("eval = %d", val); return (constexpr ? LT_IF : ret == LT_ERROR ? LT_IF : ret); } /* * Skip over comments, strings, and character literals and stop at the * next character position that is not whitespace. Between calls we keep * the comment state in the global variable incomment, and we also adjust * the global variable linestate when we see a newline. * XXX: doesn't cope with the buffer splitting inside a state transition. */ static const char * skipcomment(const char *cp) { if (text || ignoring[depth]) { for (; isspace((unsigned char)*cp); cp++) if (*cp == '\n') linestate = LS_START; return (cp); } while (*cp != '\0') /* don't reset to LS_START after a line continuation */ if (strncmp(cp, "\\\r\n", 3) == 0) cp += 3; else if (strncmp(cp, "\\\n", 2) == 0) cp += 2; else switch (incomment) { case NO_COMMENT: if (strncmp(cp, "/\\\r\n", 4) == 0) { incomment = STARTING_COMMENT; cp += 4; } else if (strncmp(cp, "/\\\n", 3) == 0) { incomment = STARTING_COMMENT; cp += 3; } else if (strncmp(cp, "/*", 2) == 0) { incomment = C_COMMENT; cp += 2; } else if (strncmp(cp, "//", 2) == 0) { incomment = CXX_COMMENT; cp += 2; } else if (strncmp(cp, "\'", 1) == 0) { incomment = CHAR_LITERAL; linestate = LS_DIRTY; cp += 1; } else if (strncmp(cp, "\"", 1) == 0) { incomment = STRING_LITERAL; linestate = LS_DIRTY; cp += 1; } else if (strncmp(cp, "\n", 1) == 0) { linestate = LS_START; cp += 1; } else if (strchr(" \r\t", *cp) != NULL) { cp += 1; } else return (cp); continue; case CXX_COMMENT: if (strncmp(cp, "\n", 1) == 0) { incomment = NO_COMMENT; linestate = LS_START; } cp += 1; continue; case CHAR_LITERAL: case STRING_LITERAL: if ((incomment == CHAR_LITERAL && cp[0] == '\'') || (incomment == STRING_LITERAL && cp[0] == '\"')) { incomment = NO_COMMENT; cp += 1; } else if (cp[0] == '\\') { if (cp[1] == '\0') cp += 1; else cp += 2; } else if (strncmp(cp, "\n", 1) == 0) { if (incomment == CHAR_LITERAL) error("unterminated char literal"); else error("unterminated string literal"); } else cp += 1; continue; case C_COMMENT: if (strncmp(cp, "*\\\r\n", 4) == 0) { incomment = FINISHING_COMMENT; cp += 4; } else if (strncmp(cp, "*\\\n", 3) == 0) { incomment = FINISHING_COMMENT; cp += 3; } else if (strncmp(cp, "*/", 2) == 0) { incomment = NO_COMMENT; cp += 2; } else cp += 1; continue; case STARTING_COMMENT: if (*cp == '*') { incomment = C_COMMENT; cp += 1; } else if (*cp == '/') { incomment = CXX_COMMENT; cp += 1; } else { incomment = NO_COMMENT; linestate = LS_DIRTY; } continue; case FINISHING_COMMENT: if (*cp == '/') { incomment = NO_COMMENT; cp += 1; } else incomment = C_COMMENT; continue; default: abort(); /* bug */ } return (cp); } /* * Skip macro arguments. */ static const char * skipargs(const char *cp) { const char *ocp = cp; int level = 0; cp = skipcomment(cp); if (*cp != '(') return (cp); do { if (*cp == '(') level++; if (*cp == ')') level--; cp = skipcomment(cp+1); } while (level != 0 && *cp != '\0'); if (level == 0) return (cp); else /* Rewind and re-detect the syntax error later. */ return (ocp); } /* * Skip over an identifier. */ static const char * skipsym(const char *cp) { while (!endsym(*cp)) ++cp; return (cp); } /* * Look for the symbol in the symbol table. If it is found, we return * the symbol table index, else we return -1. */ static int findsym(const char *str) { const char *cp; int symind; cp = skipsym(str); if (cp == str) return (-1); if (symlist) { if (symdepth && firstsym) printf("%s%3d", zerosyms ? "" : "\n", depth); firstsym = zerosyms = false; printf("%s%.*s%s", symdepth ? " " : "", (int)(cp-str), str, symdepth ? "" : "\n"); /* we don't care about the value of the symbol */ return (0); } for (symind = 0; symind < nsyms; ++symind) { if (strlcmp(symname[symind], str, cp-str) == 0) { debug("findsym %s %s", symname[symind], value[symind] ? value[symind] : ""); return (symind); } } return (-1); } /* * Add a symbol to the symbol table. */ static void addsym(bool ignorethis, bool definethis, char *sym) { int symind; char *val; symind = findsym(sym); if (symind < 0) { if (nsyms >= MAXSYMS) errx(2, "too many symbols"); symind = nsyms++; } symname[symind] = sym; ignore[symind] = ignorethis; val = sym + (skipsym(sym) - sym); if (definethis) { if (*val == '=') { value[symind] = val+1; *val = '\0'; } else if (*val == '\0') value[symind] = "1"; else usage(); } else { if (*val != '\0') usage(); value[symind] = NULL; } debug("addsym %s=%s", symname[symind], value[symind] ? value[symind] : "undef"); } /* * Compare s with n characters of t. * The same as strncmp() except that it checks that s[n] == '\0'. */ static int strlcmp(const char *s, const char *t, size_t n) { while (n-- && *t != '\0') if (*s != *t) return ((unsigned char)*s - (unsigned char)*t); else ++s, ++t; return ((unsigned char)*s); } /* * Diagnostics. */ static void debug(const char *msg, ...) { va_list ap; if (debugging) { va_start(ap, msg); vwarnx(msg, ap); va_end(ap); } } static void error(const char *msg) { if (depth == 0) warnx("%s: %d: %s", filename, linenum, msg); else warnx("%s: %d: %s (#if line %d depth %d)", filename, linenum, msg, stifline[depth], depth); closeout(); errx(2, "output may be truncated"); }
linux-master
scripts/unifdef.c
/* Sign a module file using the given key. * * Copyright © 2014-2016 Red Hat, Inc. All Rights Reserved. * Copyright © 2015 Intel Corporation. * Copyright © 2016 Hewlett Packard Enterprise Development LP * * Authors: David Howells <[email protected]> * David Woodhouse <[email protected]> * Juerg Haefliger <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the licence, or (at your option) any later version. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <getopt.h> #include <err.h> #include <arpa/inet.h> #include <openssl/opensslv.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/engine.h> /* * OpenSSL 3.0 deprecates the OpenSSL's ENGINE API. * * Remove this if/when that API is no longer used */ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /* * Use CMS if we have openssl-1.0.0 or newer available - otherwise we have to * assume that it's not available and its header file is missing and that we * should use PKCS#7 instead. Switching to the older PKCS#7 format restricts * the options we have on specifying the X.509 certificate we want. * * Further, older versions of OpenSSL don't support manually adding signers to * the PKCS#7 message so have to accept that we get a certificate included in * the signature message. Nor do such older versions of OpenSSL support * signing with anything other than SHA1 - so we're stuck with that if such is * the case. */ #if defined(LIBRESSL_VERSION_NUMBER) || \ OPENSSL_VERSION_NUMBER < 0x10000000L || \ defined(OPENSSL_NO_CMS) #define USE_PKCS7 #endif #ifndef USE_PKCS7 #include <openssl/cms.h> #else #include <openssl/pkcs7.h> #endif struct module_signature { uint8_t algo; /* Public-key crypto algorithm [0] */ uint8_t hash; /* Digest algorithm [0] */ uint8_t id_type; /* Key identifier type [PKEY_ID_PKCS7] */ uint8_t signer_len; /* Length of signer's name [0] */ uint8_t key_id_len; /* Length of key identifier [0] */ uint8_t __pad[3]; uint32_t sig_len; /* Length of signature data */ }; #define PKEY_ID_PKCS7 2 static char magic_number[] = "~Module signature appended~\n"; static __attribute__((noreturn)) void format(void) { fprintf(stderr, "Usage: scripts/sign-file [-dp] <hash algo> <key> <x509> <module> [<dest>]\n"); fprintf(stderr, " scripts/sign-file -s <raw sig> <hash algo> <x509> <module> [<dest>]\n"); exit(2); } static void display_openssl_errors(int l) { const char *file; char buf[120]; int e, line; if (ERR_peek_error() == 0) return; fprintf(stderr, "At main.c:%d:\n", l); while ((e = ERR_get_error_line(&file, &line))) { ERR_error_string(e, buf); fprintf(stderr, "- SSL %s: %s:%d\n", buf, file, line); } } static void drain_openssl_errors(void) { const char *file; int line; if (ERR_peek_error() == 0) return; while (ERR_get_error_line(&file, &line)) {} } #define ERR(cond, fmt, ...) \ do { \ bool __cond = (cond); \ display_openssl_errors(__LINE__); \ if (__cond) { \ errx(1, fmt, ## __VA_ARGS__); \ } \ } while(0) static const char *key_pass; static int pem_pw_cb(char *buf, int len, int w, void *v) { int pwlen; if (!key_pass) return -1; pwlen = strlen(key_pass); if (pwlen >= len) return -1; strcpy(buf, key_pass); /* If it's wrong, don't keep trying it. */ key_pass = NULL; return pwlen; } static EVP_PKEY *read_private_key(const char *private_key_name) { EVP_PKEY *private_key; if (!strncmp(private_key_name, "pkcs11:", 7)) { ENGINE *e; ENGINE_load_builtin_engines(); drain_openssl_errors(); e = ENGINE_by_id("pkcs11"); ERR(!e, "Load PKCS#11 ENGINE"); if (ENGINE_init(e)) drain_openssl_errors(); else ERR(1, "ENGINE_init"); if (key_pass) ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN"); private_key = ENGINE_load_private_key(e, private_key_name, NULL, NULL); ERR(!private_key, "%s", private_key_name); } else { BIO *b; b = BIO_new_file(private_key_name, "rb"); ERR(!b, "%s", private_key_name); private_key = PEM_read_bio_PrivateKey(b, NULL, pem_pw_cb, NULL); ERR(!private_key, "%s", private_key_name); BIO_free(b); } return private_key; } static X509 *read_x509(const char *x509_name) { unsigned char buf[2]; X509 *x509; BIO *b; int n; b = BIO_new_file(x509_name, "rb"); ERR(!b, "%s", x509_name); /* Look at the first two bytes of the file to determine the encoding */ n = BIO_read(b, buf, 2); if (n != 2) { if (BIO_should_retry(b)) { fprintf(stderr, "%s: Read wanted retry\n", x509_name); exit(1); } if (n >= 0) { fprintf(stderr, "%s: Short read\n", x509_name); exit(1); } ERR(1, "%s", x509_name); } ERR(BIO_reset(b) != 0, "%s", x509_name); if (buf[0] == 0x30 && buf[1] >= 0x81 && buf[1] <= 0x84) /* Assume raw DER encoded X.509 */ x509 = d2i_X509_bio(b, NULL); else /* Assume PEM encoded X.509 */ x509 = PEM_read_bio_X509(b, NULL, NULL, NULL); BIO_free(b); ERR(!x509, "%s", x509_name); return x509; } int main(int argc, char **argv) { struct module_signature sig_info = { .id_type = PKEY_ID_PKCS7 }; char *hash_algo = NULL; char *private_key_name = NULL, *raw_sig_name = NULL; char *x509_name, *module_name, *dest_name; bool save_sig = false, replace_orig; bool sign_only = false; bool raw_sig = false; unsigned char buf[4096]; unsigned long module_size, sig_size; unsigned int use_signed_attrs; const EVP_MD *digest_algo; EVP_PKEY *private_key; #ifndef USE_PKCS7 CMS_ContentInfo *cms = NULL; unsigned int use_keyid = 0; #else PKCS7 *pkcs7 = NULL; #endif X509 *x509; BIO *bd, *bm; int opt, n; OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); ERR_clear_error(); key_pass = getenv("KBUILD_SIGN_PIN"); #ifndef USE_PKCS7 use_signed_attrs = CMS_NOATTR; #else use_signed_attrs = PKCS7_NOATTR; #endif do { opt = getopt(argc, argv, "sdpk"); switch (opt) { case 's': raw_sig = true; break; case 'p': save_sig = true; break; case 'd': sign_only = true; save_sig = true; break; #ifndef USE_PKCS7 case 'k': use_keyid = CMS_USE_KEYID; break; #endif case -1: break; default: format(); } } while (opt != -1); argc -= optind; argv += optind; if (argc < 4 || argc > 5) format(); if (raw_sig) { raw_sig_name = argv[0]; hash_algo = argv[1]; } else { hash_algo = argv[0]; private_key_name = argv[1]; } x509_name = argv[2]; module_name = argv[3]; if (argc == 5 && strcmp(argv[3], argv[4]) != 0) { dest_name = argv[4]; replace_orig = false; } else { ERR(asprintf(&dest_name, "%s.~signed~", module_name) < 0, "asprintf"); replace_orig = true; } #ifdef USE_PKCS7 if (strcmp(hash_algo, "sha1") != 0) { fprintf(stderr, "sign-file: %s only supports SHA1 signing\n", OPENSSL_VERSION_TEXT); exit(3); } #endif /* Open the module file */ bm = BIO_new_file(module_name, "rb"); ERR(!bm, "%s", module_name); if (!raw_sig) { /* Read the private key and the X.509 cert the PKCS#7 message * will point to. */ private_key = read_private_key(private_key_name); x509 = read_x509(x509_name); /* Digest the module data. */ OpenSSL_add_all_digests(); display_openssl_errors(__LINE__); digest_algo = EVP_get_digestbyname(hash_algo); ERR(!digest_algo, "EVP_get_digestbyname"); #ifndef USE_PKCS7 /* Load the signature message from the digest buffer. */ cms = CMS_sign(NULL, NULL, NULL, NULL, CMS_NOCERTS | CMS_PARTIAL | CMS_BINARY | CMS_DETACHED | CMS_STREAM); ERR(!cms, "CMS_sign"); ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, CMS_NOCERTS | CMS_BINARY | CMS_NOSMIMECAP | use_keyid | use_signed_attrs), "CMS_add1_signer"); ERR(CMS_final(cms, bm, NULL, CMS_NOCERTS | CMS_BINARY) < 0, "CMS_final"); #else pkcs7 = PKCS7_sign(x509, private_key, NULL, bm, PKCS7_NOCERTS | PKCS7_BINARY | PKCS7_DETACHED | use_signed_attrs); ERR(!pkcs7, "PKCS7_sign"); #endif if (save_sig) { char *sig_file_name; BIO *b; ERR(asprintf(&sig_file_name, "%s.p7s", module_name) < 0, "asprintf"); b = BIO_new_file(sig_file_name, "wb"); ERR(!b, "%s", sig_file_name); #ifndef USE_PKCS7 ERR(i2d_CMS_bio_stream(b, cms, NULL, 0) < 0, "%s", sig_file_name); #else ERR(i2d_PKCS7_bio(b, pkcs7) < 0, "%s", sig_file_name); #endif BIO_free(b); } if (sign_only) { BIO_free(bm); return 0; } } /* Open the destination file now so that we can shovel the module data * across as we read it. */ bd = BIO_new_file(dest_name, "wb"); ERR(!bd, "%s", dest_name); /* Append the marker and the PKCS#7 message to the destination file */ ERR(BIO_reset(bm) < 0, "%s", module_name); while ((n = BIO_read(bm, buf, sizeof(buf))), n > 0) { ERR(BIO_write(bd, buf, n) < 0, "%s", dest_name); } BIO_free(bm); ERR(n < 0, "%s", module_name); module_size = BIO_number_written(bd); if (!raw_sig) { #ifndef USE_PKCS7 ERR(i2d_CMS_bio_stream(bd, cms, NULL, 0) < 0, "%s", dest_name); #else ERR(i2d_PKCS7_bio(bd, pkcs7) < 0, "%s", dest_name); #endif } else { BIO *b; /* Read the raw signature file and write the data to the * destination file */ b = BIO_new_file(raw_sig_name, "rb"); ERR(!b, "%s", raw_sig_name); while ((n = BIO_read(b, buf, sizeof(buf))), n > 0) ERR(BIO_write(bd, buf, n) < 0, "%s", dest_name); BIO_free(b); } sig_size = BIO_number_written(bd) - module_size; sig_info.sig_len = htonl(sig_size); ERR(BIO_write(bd, &sig_info, sizeof(sig_info)) < 0, "%s", dest_name); ERR(BIO_write(bd, magic_number, sizeof(magic_number) - 1) < 0, "%s", dest_name); ERR(BIO_free(bd) < 0, "%s", dest_name); /* Finally, if we're signing in place, replace the original. */ if (replace_orig) ERR(rename(dest_name, module_name) < 0, "%s", dest_name); return 0; }
linux-master
scripts/sign-file.c
// SPDX-License-Identifier: GPL-2.0-only /* * recordmcount.c: construct a table of the locations of calls to 'mcount' * so that ftrace can find them quickly. * Copyright 2009 John F. Reiser <[email protected]>. All rights reserved. * * Restructured to fit Linux format, as well as other updates: * Copyright 2010 Steven Rostedt <[email protected]>, Red Hat Inc. */ /* * Strategy: alter the .o file in-place. * * Append a new STRTAB that has the new section names, followed by a new array * ElfXX_Shdr[] that has the new section headers, followed by the section * contents for __mcount_loc and its relocations. The old shstrtab strings, * and the old ElfXX_Shdr[] array, remain as "garbage" (commonly, a couple * kilobytes.) Subsequent processing by /bin/ld (or the kernel module loader) * will ignore the garbage regions, because they are not designated by the * new .e_shoff nor the new ElfXX_Shdr[]. [In order to remove the garbage, * then use "ld -r" to create a new file that omits the garbage.] */ #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <getopt.h> #include <elf.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifndef EM_AARCH64 #define EM_AARCH64 183 #define R_AARCH64_NONE 0 #define R_AARCH64_ABS64 257 #endif #ifndef EM_LOONGARCH #define EM_LOONGARCH 258 #define R_LARCH_32 1 #define R_LARCH_64 2 #define R_LARCH_MARK_LA 20 #define R_LARCH_SOP_PUSH_PLT_PCREL 29 #endif #define R_ARM_PC24 1 #define R_ARM_THM_CALL 10 #define R_ARM_CALL 28 #define R_AARCH64_CALL26 283 static int fd_map; /* File descriptor for file being modified. */ static int mmap_failed; /* Boolean flag. */ static char gpfx; /* prefix for global symbol name (sometimes '_') */ static struct stat sb; /* Remember .st_size, etc. */ static const char *altmcount; /* alternate mcount symbol name */ static int warn_on_notrace_sect; /* warn when section has mcount not being recorded */ static void *file_map; /* pointer of the mapped file */ static void *file_end; /* pointer to the end of the mapped file */ static int file_updated; /* flag to state file was changed */ static void *file_ptr; /* current file pointer location */ static void *file_append; /* added to the end of the file */ static size_t file_append_size; /* how much is added to end of file */ /* Per-file resource cleanup when multiple files. */ static void file_append_cleanup(void) { free(file_append); file_append = NULL; file_append_size = 0; file_updated = 0; } static void mmap_cleanup(void) { if (!mmap_failed) munmap(file_map, sb.st_size); else free(file_map); file_map = NULL; } /* ulseek, uwrite, ...: Check return value for errors. */ static off_t ulseek(off_t const offset, int const whence) { switch (whence) { case SEEK_SET: file_ptr = file_map + offset; break; case SEEK_CUR: file_ptr += offset; break; case SEEK_END: file_ptr = file_map + (sb.st_size - offset); break; } if (file_ptr < file_map) { fprintf(stderr, "lseek: seek before file\n"); return -1; } return file_ptr - file_map; } static ssize_t uwrite(void const *const buf, size_t const count) { size_t cnt = count; off_t idx = 0; void *p = NULL; file_updated = 1; if (file_ptr + count >= file_end) { off_t aoffset = (file_ptr + count) - file_end; if (aoffset > file_append_size) { p = realloc(file_append, aoffset); if (!p) free(file_append); file_append = p; file_append_size = aoffset; } if (!file_append) { perror("write"); file_append_cleanup(); mmap_cleanup(); return -1; } if (file_ptr < file_end) { cnt = file_end - file_ptr; } else { cnt = 0; idx = aoffset - count; } } if (cnt) memcpy(file_ptr, buf, cnt); if (cnt < count) memcpy(file_append + idx, buf + cnt, count - cnt); file_ptr += count; return count; } static void * umalloc(size_t size) { void *const addr = malloc(size); if (addr == 0) { fprintf(stderr, "malloc failed: %zu bytes\n", size); file_append_cleanup(); mmap_cleanup(); return NULL; } return addr; } /* * Get the whole file as a programming convenience in order to avoid * malloc+lseek+read+free of many pieces. If successful, then mmap * avoids copying unused pieces; else just read the whole file. * Open for both read and write; new info will be appended to the file. * Use MAP_PRIVATE so that a few changes to the in-memory ElfXX_Ehdr * do not propagate to the file until an explicit overwrite at the last. * This preserves most aspects of consistency (all except .st_size) * for simultaneous readers of the file while we are appending to it. * However, multiple writers still are bad. We choose not to use * locking because it is expensive and the use case of kernel build * makes multiple writers unlikely. */ static void *mmap_file(char const *fname) { /* Avoid problems if early cleanup() */ fd_map = -1; mmap_failed = 1; file_map = NULL; file_ptr = NULL; file_updated = 0; sb.st_size = 0; fd_map = open(fname, O_RDONLY); if (fd_map < 0) { perror(fname); return NULL; } if (fstat(fd_map, &sb) < 0) { perror(fname); goto out; } if (!S_ISREG(sb.st_mode)) { fprintf(stderr, "not a regular file: %s\n", fname); goto out; } file_map = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd_map, 0); if (file_map == MAP_FAILED) { mmap_failed = 1; file_map = umalloc(sb.st_size); if (!file_map) { perror(fname); goto out; } if (read(fd_map, file_map, sb.st_size) != sb.st_size) { perror(fname); free(file_map); file_map = NULL; goto out; } } else mmap_failed = 0; out: close(fd_map); fd_map = -1; file_end = file_map + sb.st_size; return file_map; } static unsigned char ideal_nop5_x86_64[5] = { 0x0f, 0x1f, 0x44, 0x00, 0x00 }; static unsigned char ideal_nop5_x86_32[5] = { 0x3e, 0x8d, 0x74, 0x26, 0x00 }; static unsigned char *ideal_nop; static char rel_type_nop; static int (*make_nop)(void *map, size_t const offset); static int make_nop_x86(void *map, size_t const offset) { uint32_t *ptr; unsigned char *op; /* Confirm we have 0xe8 0x0 0x0 0x0 0x0 */ ptr = map + offset; if (*ptr != 0) return -1; op = map + offset - 1; if (*op != 0xe8) return -1; /* convert to nop */ if (ulseek(offset - 1, SEEK_SET) < 0) return -1; if (uwrite(ideal_nop, 5) < 0) return -1; return 0; } static unsigned char ideal_nop4_arm_le[4] = { 0x00, 0x00, 0xa0, 0xe1 }; /* mov r0, r0 */ static unsigned char ideal_nop4_arm_be[4] = { 0xe1, 0xa0, 0x00, 0x00 }; /* mov r0, r0 */ static unsigned char *ideal_nop4_arm; static unsigned char bl_mcount_arm_le[4] = { 0xfe, 0xff, 0xff, 0xeb }; /* bl */ static unsigned char bl_mcount_arm_be[4] = { 0xeb, 0xff, 0xff, 0xfe }; /* bl */ static unsigned char *bl_mcount_arm; static unsigned char push_arm_le[4] = { 0x04, 0xe0, 0x2d, 0xe5 }; /* push {lr} */ static unsigned char push_arm_be[4] = { 0xe5, 0x2d, 0xe0, 0x04 }; /* push {lr} */ static unsigned char *push_arm; static unsigned char ideal_nop2_thumb_le[2] = { 0x00, 0xbf }; /* nop */ static unsigned char ideal_nop2_thumb_be[2] = { 0xbf, 0x00 }; /* nop */ static unsigned char *ideal_nop2_thumb; static unsigned char push_bl_mcount_thumb_le[6] = { 0x00, 0xb5, 0xff, 0xf7, 0xfe, 0xff }; /* push {lr}, bl */ static unsigned char push_bl_mcount_thumb_be[6] = { 0xb5, 0x00, 0xf7, 0xff, 0xff, 0xfe }; /* push {lr}, bl */ static unsigned char *push_bl_mcount_thumb; static int make_nop_arm(void *map, size_t const offset) { char *ptr; int cnt = 1; int nop_size; size_t off = offset; ptr = map + offset; if (memcmp(ptr, bl_mcount_arm, 4) == 0) { if (memcmp(ptr - 4, push_arm, 4) == 0) { off -= 4; cnt = 2; } ideal_nop = ideal_nop4_arm; nop_size = 4; } else if (memcmp(ptr - 2, push_bl_mcount_thumb, 6) == 0) { cnt = 3; nop_size = 2; off -= 2; ideal_nop = ideal_nop2_thumb; } else return -1; /* Convert to nop */ if (ulseek(off, SEEK_SET) < 0) return -1; do { if (uwrite(ideal_nop, nop_size) < 0) return -1; } while (--cnt > 0); return 0; } static unsigned char ideal_nop4_arm64[4] = {0x1f, 0x20, 0x03, 0xd5}; static int make_nop_arm64(void *map, size_t const offset) { uint32_t *ptr; ptr = map + offset; /* bl <_mcount> is 0x94000000 before relocation */ if (*ptr != 0x94000000) return -1; /* Convert to nop */ if (ulseek(offset, SEEK_SET) < 0) return -1; if (uwrite(ideal_nop, 4) < 0) return -1; return 0; } static int write_file(const char *fname) { char tmp_file[strlen(fname) + 4]; size_t n; if (!file_updated) return 0; sprintf(tmp_file, "%s.rc", fname); /* * After reading the entire file into memory, delete it * and write it back, to prevent weird side effects of modifying * an object file in place. */ fd_map = open(tmp_file, O_WRONLY | O_TRUNC | O_CREAT, sb.st_mode); if (fd_map < 0) { perror(fname); return -1; } n = write(fd_map, file_map, sb.st_size); if (n != sb.st_size) { perror("write"); close(fd_map); return -1; } if (file_append_size) { n = write(fd_map, file_append, file_append_size); if (n != file_append_size) { perror("write"); close(fd_map); return -1; } } close(fd_map); if (rename(tmp_file, fname) < 0) { perror(fname); return -1; } return 0; } /* w8rev, w8nat, ...: Handle endianness. */ static uint64_t w8rev(uint64_t const x) { return ((0xff & (x >> (0 * 8))) << (7 * 8)) | ((0xff & (x >> (1 * 8))) << (6 * 8)) | ((0xff & (x >> (2 * 8))) << (5 * 8)) | ((0xff & (x >> (3 * 8))) << (4 * 8)) | ((0xff & (x >> (4 * 8))) << (3 * 8)) | ((0xff & (x >> (5 * 8))) << (2 * 8)) | ((0xff & (x >> (6 * 8))) << (1 * 8)) | ((0xff & (x >> (7 * 8))) << (0 * 8)); } static uint32_t w4rev(uint32_t const x) { return ((0xff & (x >> (0 * 8))) << (3 * 8)) | ((0xff & (x >> (1 * 8))) << (2 * 8)) | ((0xff & (x >> (2 * 8))) << (1 * 8)) | ((0xff & (x >> (3 * 8))) << (0 * 8)); } static uint32_t w2rev(uint16_t const x) { return ((0xff & (x >> (0 * 8))) << (1 * 8)) | ((0xff & (x >> (1 * 8))) << (0 * 8)); } static uint64_t w8nat(uint64_t const x) { return x; } static uint32_t w4nat(uint32_t const x) { return x; } static uint32_t w2nat(uint16_t const x) { return x; } static uint64_t (*w8)(uint64_t); static uint32_t (*w)(uint32_t); static uint32_t (*w2)(uint16_t); /* Names of the sections that could contain calls to mcount. */ static int is_mcounted_section_name(char const *const txtname) { return strncmp(".text", txtname, 5) == 0 || strcmp(".init.text", txtname) == 0 || strcmp(".ref.text", txtname) == 0 || strcmp(".sched.text", txtname) == 0 || strcmp(".spinlock.text", txtname) == 0 || strcmp(".irqentry.text", txtname) == 0 || strcmp(".softirqentry.text", txtname) == 0 || strcmp(".kprobes.text", txtname) == 0 || strcmp(".cpuidle.text", txtname) == 0; } static char const *already_has_rel_mcount = "success"; /* our work here is done! */ /* 32 bit and 64 bit are very similar */ #include "recordmcount.h" #define RECORD_MCOUNT_64 #include "recordmcount.h" static int arm_is_fake_mcount(Elf32_Rel const *rp) { switch (ELF32_R_TYPE(w(rp->r_info))) { case R_ARM_THM_CALL: case R_ARM_CALL: case R_ARM_PC24: return 0; } return 1; } static int arm64_is_fake_mcount(Elf64_Rel const *rp) { return ELF64_R_TYPE(w8(rp->r_info)) != R_AARCH64_CALL26; } static int LARCH32_is_fake_mcount(Elf32_Rel const *rp) { switch (ELF64_R_TYPE(w(rp->r_info))) { case R_LARCH_MARK_LA: case R_LARCH_SOP_PUSH_PLT_PCREL: return 0; } return 1; } static int LARCH64_is_fake_mcount(Elf64_Rel const *rp) { switch (ELF64_R_TYPE(w(rp->r_info))) { case R_LARCH_MARK_LA: case R_LARCH_SOP_PUSH_PLT_PCREL: return 0; } return 1; } /* 64-bit EM_MIPS has weird ELF64_Rela.r_info. * http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf * We interpret Table 29 Relocation Operation (Elf64_Rel, Elf64_Rela) [p.40] * to imply the order of the members; the spec does not say so. * typedef unsigned char Elf64_Byte; * fails on MIPS64 because their <elf.h> already has it! */ typedef uint8_t myElf64_Byte; /* Type for a 8-bit quantity. */ union mips_r_info { Elf64_Xword r_info; struct { Elf64_Word r_sym; /* Symbol index. */ myElf64_Byte r_ssym; /* Special symbol. */ myElf64_Byte r_type3; /* Third relocation. */ myElf64_Byte r_type2; /* Second relocation. */ myElf64_Byte r_type; /* First relocation. */ } r_mips; }; static uint64_t MIPS64_r_sym(Elf64_Rel const *rp) { return w(((union mips_r_info){ .r_info = rp->r_info }).r_mips.r_sym); } static void MIPS64_r_info(Elf64_Rel *const rp, unsigned sym, unsigned type) { rp->r_info = ((union mips_r_info){ .r_mips = { .r_sym = w(sym), .r_type = type } }).r_info; } static int do_file(char const *const fname) { unsigned int reltype = 0; Elf32_Ehdr *ehdr; int rc = -1; ehdr = mmap_file(fname); if (!ehdr) goto out; w = w4nat; w2 = w2nat; w8 = w8nat; switch (ehdr->e_ident[EI_DATA]) { static unsigned int const endian = 1; default: fprintf(stderr, "unrecognized ELF data encoding %d: %s\n", ehdr->e_ident[EI_DATA], fname); goto out; case ELFDATA2LSB: if (*(unsigned char const *)&endian != 1) { /* main() is big endian, file.o is little endian. */ w = w4rev; w2 = w2rev; w8 = w8rev; } ideal_nop4_arm = ideal_nop4_arm_le; bl_mcount_arm = bl_mcount_arm_le; push_arm = push_arm_le; ideal_nop2_thumb = ideal_nop2_thumb_le; push_bl_mcount_thumb = push_bl_mcount_thumb_le; break; case ELFDATA2MSB: if (*(unsigned char const *)&endian != 0) { /* main() is little endian, file.o is big endian. */ w = w4rev; w2 = w2rev; w8 = w8rev; } ideal_nop4_arm = ideal_nop4_arm_be; bl_mcount_arm = bl_mcount_arm_be; push_arm = push_arm_be; ideal_nop2_thumb = ideal_nop2_thumb_be; push_bl_mcount_thumb = push_bl_mcount_thumb_be; break; } /* end switch */ if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0 || w2(ehdr->e_type) != ET_REL || ehdr->e_ident[EI_VERSION] != EV_CURRENT) { fprintf(stderr, "unrecognized ET_REL file %s\n", fname); goto out; } gpfx = '_'; switch (w2(ehdr->e_machine)) { default: fprintf(stderr, "unrecognized e_machine %u %s\n", w2(ehdr->e_machine), fname); goto out; case EM_386: reltype = R_386_32; rel_type_nop = R_386_NONE; make_nop = make_nop_x86; ideal_nop = ideal_nop5_x86_32; mcount_adjust_32 = -1; gpfx = 0; break; case EM_ARM: reltype = R_ARM_ABS32; altmcount = "__gnu_mcount_nc"; make_nop = make_nop_arm; rel_type_nop = R_ARM_NONE; is_fake_mcount32 = arm_is_fake_mcount; gpfx = 0; break; case EM_AARCH64: reltype = R_AARCH64_ABS64; make_nop = make_nop_arm64; rel_type_nop = R_AARCH64_NONE; ideal_nop = ideal_nop4_arm64; is_fake_mcount64 = arm64_is_fake_mcount; break; case EM_IA_64: reltype = R_IA64_IMM64; break; case EM_MIPS: /* reltype: e_class */ break; case EM_LOONGARCH: /* reltype: e_class */ break; case EM_PPC: reltype = R_PPC_ADDR32; break; case EM_PPC64: reltype = R_PPC64_ADDR64; break; case EM_S390: /* reltype: e_class */ break; case EM_SH: reltype = R_SH_DIR32; gpfx = 0; break; case EM_SPARCV9: reltype = R_SPARC_64; break; case EM_X86_64: make_nop = make_nop_x86; ideal_nop = ideal_nop5_x86_64; reltype = R_X86_64_64; rel_type_nop = R_X86_64_NONE; mcount_adjust_64 = -1; gpfx = 0; break; } /* end switch */ switch (ehdr->e_ident[EI_CLASS]) { default: fprintf(stderr, "unrecognized ELF class %d %s\n", ehdr->e_ident[EI_CLASS], fname); goto out; case ELFCLASS32: if (w2(ehdr->e_ehsize) != sizeof(Elf32_Ehdr) || w2(ehdr->e_shentsize) != sizeof(Elf32_Shdr)) { fprintf(stderr, "unrecognized ET_REL file: %s\n", fname); goto out; } if (w2(ehdr->e_machine) == EM_MIPS) { reltype = R_MIPS_32; is_fake_mcount32 = MIPS32_is_fake_mcount; } if (w2(ehdr->e_machine) == EM_LOONGARCH) { reltype = R_LARCH_32; is_fake_mcount32 = LARCH32_is_fake_mcount; } if (do32(ehdr, fname, reltype) < 0) goto out; break; case ELFCLASS64: { Elf64_Ehdr *const ghdr = (Elf64_Ehdr *)ehdr; if (w2(ghdr->e_ehsize) != sizeof(Elf64_Ehdr) || w2(ghdr->e_shentsize) != sizeof(Elf64_Shdr)) { fprintf(stderr, "unrecognized ET_REL file: %s\n", fname); goto out; } if (w2(ghdr->e_machine) == EM_S390) { reltype = R_390_64; mcount_adjust_64 = -14; } if (w2(ghdr->e_machine) == EM_MIPS) { reltype = R_MIPS_64; Elf64_r_sym = MIPS64_r_sym; Elf64_r_info = MIPS64_r_info; is_fake_mcount64 = MIPS64_is_fake_mcount; } if (w2(ghdr->e_machine) == EM_LOONGARCH) { reltype = R_LARCH_64; is_fake_mcount64 = LARCH64_is_fake_mcount; } if (do64(ghdr, fname, reltype) < 0) goto out; break; } } /* end switch */ rc = write_file(fname); out: file_append_cleanup(); mmap_cleanup(); return rc; } int main(int argc, char *argv[]) { const char ftrace[] = "/ftrace.o"; int ftrace_size = sizeof(ftrace) - 1; int n_error = 0; /* gcc-4.3.0 false positive complaint */ int c; int i; while ((c = getopt(argc, argv, "w")) >= 0) { switch (c) { case 'w': warn_on_notrace_sect = 1; break; default: fprintf(stderr, "usage: recordmcount [-w] file.o...\n"); return 0; } } if ((argc - optind) < 1) { fprintf(stderr, "usage: recordmcount [-w] file.o...\n"); return 0; } /* Process each file in turn, allowing deep failure. */ for (i = optind; i < argc; i++) { char *file = argv[i]; int len; /* * The file kernel/trace/ftrace.o references the mcount * function but does not call it. Since ftrace.o should * not be traced anyway, we just skip it. */ len = strlen(file); if (len >= ftrace_size && strcmp(file + (len - ftrace_size), ftrace) == 0) continue; if (do_file(file)) { fprintf(stderr, "%s: failed\n", file); ++n_error; } } return !!n_error; }
linux-master
scripts/recordmcount.c
/* Generate assembler source containing symbol information * * Copyright 2002 by Kai Germaschewski * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Usage: kallsyms [--all-symbols] [--absolute-percpu] * [--base-relative] [--lto-clang] in.map > out.S * * Table compression uses all the unused char codes on the symbols and * maps these to the most used substrings (tokens). For instance, it might * map char code 0xF7 to represent "write_" and then in every symbol where * "write_" appears it can be replaced by 0xF7, saving 5 bytes. * The used codes themselves are also placed in the table so that the * decompresion can work without "special cases". * Applied to kernel symbols, this usually produces a compression ratio * of about 50%. * */ #include <errno.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) #define KSYM_NAME_LEN 512 struct sym_entry { unsigned long long addr; unsigned int len; unsigned int seq; unsigned int start_pos; unsigned int percpu_absolute; unsigned char sym[]; }; struct addr_range { const char *start_sym, *end_sym; unsigned long long start, end; }; static unsigned long long _text; static unsigned long long relative_base; static struct addr_range text_ranges[] = { { "_stext", "_etext" }, { "_sinittext", "_einittext" }, }; #define text_range_text (&text_ranges[0]) #define text_range_inittext (&text_ranges[1]) static struct addr_range percpu_range = { "__per_cpu_start", "__per_cpu_end", -1ULL, 0 }; static struct sym_entry **table; static unsigned int table_size, table_cnt; static int all_symbols; static int absolute_percpu; static int base_relative; static int lto_clang; static int token_profit[0x10000]; /* the table that holds the result of the compression */ static unsigned char best_table[256][2]; static unsigned char best_table_len[256]; static void usage(void) { fprintf(stderr, "Usage: kallsyms [--all-symbols] [--absolute-percpu] " "[--base-relative] [--lto-clang] in.map > out.S\n"); exit(1); } static char *sym_name(const struct sym_entry *s) { return (char *)s->sym + 1; } static bool is_ignored_symbol(const char *name, char type) { if (type == 'u' || type == 'n') return true; if (toupper(type) == 'A') { /* Keep these useful absolute symbols */ if (strcmp(name, "__kernel_syscall_via_break") && strcmp(name, "__kernel_syscall_via_epc") && strcmp(name, "__kernel_sigtramp") && strcmp(name, "__gp")) return true; } return false; } static void check_symbol_range(const char *sym, unsigned long long addr, struct addr_range *ranges, int entries) { size_t i; struct addr_range *ar; for (i = 0; i < entries; ++i) { ar = &ranges[i]; if (strcmp(sym, ar->start_sym) == 0) { ar->start = addr; return; } else if (strcmp(sym, ar->end_sym) == 0) { ar->end = addr; return; } } } static struct sym_entry *read_symbol(FILE *in, char **buf, size_t *buf_len) { char *name, type, *p; unsigned long long addr; size_t len; ssize_t readlen; struct sym_entry *sym; errno = 0; readlen = getline(buf, buf_len, in); if (readlen < 0) { if (errno) { perror("read_symbol"); exit(EXIT_FAILURE); } return NULL; } if ((*buf)[readlen - 1] == '\n') (*buf)[readlen - 1] = 0; addr = strtoull(*buf, &p, 16); if (*buf == p || *p++ != ' ' || !isascii((type = *p++)) || *p++ != ' ') { fprintf(stderr, "line format error\n"); exit(EXIT_FAILURE); } name = p; len = strlen(name); if (len >= KSYM_NAME_LEN) { fprintf(stderr, "Symbol %s too long for kallsyms (%zu >= %d).\n" "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n", name, len, KSYM_NAME_LEN); return NULL; } if (strcmp(name, "_text") == 0) _text = addr; /* Ignore most absolute/undefined (?) symbols. */ if (is_ignored_symbol(name, type)) return NULL; check_symbol_range(name, addr, text_ranges, ARRAY_SIZE(text_ranges)); check_symbol_range(name, addr, &percpu_range, 1); /* include the type field in the symbol name, so that it gets * compressed together */ len++; sym = malloc(sizeof(*sym) + len + 1); if (!sym) { fprintf(stderr, "kallsyms failure: " "unable to allocate required amount of memory\n"); exit(EXIT_FAILURE); } sym->addr = addr; sym->len = len; sym->sym[0] = type; strcpy(sym_name(sym), name); sym->percpu_absolute = 0; return sym; } static int symbol_in_range(const struct sym_entry *s, const struct addr_range *ranges, int entries) { size_t i; const struct addr_range *ar; for (i = 0; i < entries; ++i) { ar = &ranges[i]; if (s->addr >= ar->start && s->addr <= ar->end) return 1; } return 0; } static int symbol_valid(const struct sym_entry *s) { const char *name = sym_name(s); /* if --all-symbols is not specified, then symbols outside the text * and inittext sections are discarded */ if (!all_symbols) { if (symbol_in_range(s, text_ranges, ARRAY_SIZE(text_ranges)) == 0) return 0; /* Corner case. Discard any symbols with the same value as * _etext _einittext; they can move between pass 1 and 2 when * the kallsyms data are added. If these symbols move then * they may get dropped in pass 2, which breaks the kallsyms * rules. */ if ((s->addr == text_range_text->end && strcmp(name, text_range_text->end_sym)) || (s->addr == text_range_inittext->end && strcmp(name, text_range_inittext->end_sym))) return 0; } return 1; } /* remove all the invalid symbols from the table */ static void shrink_table(void) { unsigned int i, pos; pos = 0; for (i = 0; i < table_cnt; i++) { if (symbol_valid(table[i])) { if (pos != i) table[pos] = table[i]; pos++; } else { free(table[i]); } } table_cnt = pos; /* When valid symbol is not registered, exit to error */ if (!table_cnt) { fprintf(stderr, "No valid symbol.\n"); exit(1); } } static void read_map(const char *in) { FILE *fp; struct sym_entry *sym; char *buf = NULL; size_t buflen = 0; fp = fopen(in, "r"); if (!fp) { perror(in); exit(1); } while (!feof(fp)) { sym = read_symbol(fp, &buf, &buflen); if (!sym) continue; sym->start_pos = table_cnt; if (table_cnt >= table_size) { table_size += 10000; table = realloc(table, sizeof(*table) * table_size); if (!table) { fprintf(stderr, "out of memory\n"); fclose(fp); exit (1); } } table[table_cnt++] = sym; } free(buf); fclose(fp); } static void output_label(const char *label) { printf(".globl %s\n", label); printf("\tALGN\n"); printf("%s:\n", label); } /* Provide proper symbols relocatability by their '_text' relativeness. */ static void output_address(unsigned long long addr) { if (_text <= addr) printf("\tPTR\t_text + %#llx\n", addr - _text); else printf("\tPTR\t_text - %#llx\n", _text - addr); } /* uncompress a compressed symbol. When this function is called, the best table * might still be compressed itself, so the function needs to be recursive */ static int expand_symbol(const unsigned char *data, int len, char *result) { int c, rlen, total=0; while (len) { c = *data; /* if the table holds a single char that is the same as the one * we are looking for, then end the search */ if (best_table[c][0]==c && best_table_len[c]==1) { *result++ = c; total++; } else { /* if not, recurse and expand */ rlen = expand_symbol(best_table[c], best_table_len[c], result); total += rlen; result += rlen; } data++; len--; } *result=0; return total; } static int symbol_absolute(const struct sym_entry *s) { return s->percpu_absolute; } static void cleanup_symbol_name(char *s) { char *p; /* * ASCII[.] = 2e * ASCII[0-9] = 30,39 * ASCII[A-Z] = 41,5a * ASCII[_] = 5f * ASCII[a-z] = 61,7a * * As above, replacing the first '.' in ".llvm." with '\0' does not * affect the main sorting, but it helps us with subsorting. */ p = strstr(s, ".llvm."); if (p) *p = '\0'; } static int compare_names(const void *a, const void *b) { int ret; const struct sym_entry *sa = *(const struct sym_entry **)a; const struct sym_entry *sb = *(const struct sym_entry **)b; ret = strcmp(sym_name(sa), sym_name(sb)); if (!ret) { if (sa->addr > sb->addr) return 1; else if (sa->addr < sb->addr) return -1; /* keep old order */ return (int)(sa->seq - sb->seq); } return ret; } static void sort_symbols_by_name(void) { qsort(table, table_cnt, sizeof(table[0]), compare_names); } static void write_src(void) { unsigned int i, k, off; unsigned int best_idx[256]; unsigned int *markers; char buf[KSYM_NAME_LEN]; printf("#include <asm/bitsperlong.h>\n"); printf("#if BITS_PER_LONG == 64\n"); printf("#define PTR .quad\n"); printf("#define ALGN .balign 8\n"); printf("#else\n"); printf("#define PTR .long\n"); printf("#define ALGN .balign 4\n"); printf("#endif\n"); printf("\t.section .rodata, \"a\"\n"); output_label("kallsyms_num_syms"); printf("\t.long\t%u\n", table_cnt); printf("\n"); /* table of offset markers, that give the offset in the compressed stream * every 256 symbols */ markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256)); if (!markers) { fprintf(stderr, "kallsyms failure: " "unable to allocate required memory\n"); exit(EXIT_FAILURE); } output_label("kallsyms_names"); off = 0; for (i = 0; i < table_cnt; i++) { if ((i & 0xFF) == 0) markers[i >> 8] = off; table[i]->seq = i; /* There cannot be any symbol of length zero. */ if (table[i]->len == 0) { fprintf(stderr, "kallsyms failure: " "unexpected zero symbol length\n"); exit(EXIT_FAILURE); } /* Only lengths that fit in up-to-two-byte ULEB128 are supported. */ if (table[i]->len > 0x3FFF) { fprintf(stderr, "kallsyms failure: " "unexpected huge symbol length\n"); exit(EXIT_FAILURE); } /* Encode length with ULEB128. */ if (table[i]->len <= 0x7F) { /* Most symbols use a single byte for the length. */ printf("\t.byte 0x%02x", table[i]->len); off += table[i]->len + 1; } else { /* "Big" symbols use two bytes. */ printf("\t.byte 0x%02x, 0x%02x", (table[i]->len & 0x7F) | 0x80, (table[i]->len >> 7) & 0x7F); off += table[i]->len + 2; } for (k = 0; k < table[i]->len; k++) printf(", 0x%02x", table[i]->sym[k]); printf("\n"); } printf("\n"); /* * Now that we wrote out the compressed symbol names, restore the * original names, which are needed in some of the later steps. */ for (i = 0; i < table_cnt; i++) { expand_symbol(table[i]->sym, table[i]->len, buf); strcpy((char *)table[i]->sym, buf); } output_label("kallsyms_markers"); for (i = 0; i < ((table_cnt + 255) >> 8); i++) printf("\t.long\t%u\n", markers[i]); printf("\n"); free(markers); output_label("kallsyms_token_table"); off = 0; for (i = 0; i < 256; i++) { best_idx[i] = off; expand_symbol(best_table[i], best_table_len[i], buf); printf("\t.asciz\t\"%s\"\n", buf); off += strlen(buf) + 1; } printf("\n"); output_label("kallsyms_token_index"); for (i = 0; i < 256; i++) printf("\t.short\t%d\n", best_idx[i]); printf("\n"); if (!base_relative) output_label("kallsyms_addresses"); else output_label("kallsyms_offsets"); for (i = 0; i < table_cnt; i++) { if (base_relative) { /* * Use the offset relative to the lowest value * encountered of all relative symbols, and emit * non-relocatable fixed offsets that will be fixed * up at runtime. */ long long offset; int overflow; if (!absolute_percpu) { offset = table[i]->addr - relative_base; overflow = (offset < 0 || offset > UINT_MAX); } else if (symbol_absolute(table[i])) { offset = table[i]->addr; overflow = (offset < 0 || offset > INT_MAX); } else { offset = relative_base - table[i]->addr - 1; overflow = (offset < INT_MIN || offset >= 0); } if (overflow) { fprintf(stderr, "kallsyms failure: " "%s symbol value %#llx out of range in relative mode\n", symbol_absolute(table[i]) ? "absolute" : "relative", table[i]->addr); exit(EXIT_FAILURE); } printf("\t.long\t%#x /* %s */\n", (int)offset, table[i]->sym); } else if (!symbol_absolute(table[i])) { output_address(table[i]->addr); } else { printf("\tPTR\t%#llx\n", table[i]->addr); } } printf("\n"); if (base_relative) { output_label("kallsyms_relative_base"); output_address(relative_base); printf("\n"); } if (lto_clang) for (i = 0; i < table_cnt; i++) cleanup_symbol_name((char *)table[i]->sym); sort_symbols_by_name(); output_label("kallsyms_seqs_of_names"); for (i = 0; i < table_cnt; i++) printf("\t.byte 0x%02x, 0x%02x, 0x%02x\n", (unsigned char)(table[i]->seq >> 16), (unsigned char)(table[i]->seq >> 8), (unsigned char)(table[i]->seq >> 0)); printf("\n"); } /* table lookup compression functions */ /* count all the possible tokens in a symbol */ static void learn_symbol(const unsigned char *symbol, int len) { int i; for (i = 0; i < len - 1; i++) token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++; } /* decrease the count for all the possible tokens in a symbol */ static void forget_symbol(const unsigned char *symbol, int len) { int i; for (i = 0; i < len - 1; i++) token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--; } /* do the initial token count */ static void build_initial_token_table(void) { unsigned int i; for (i = 0; i < table_cnt; i++) learn_symbol(table[i]->sym, table[i]->len); } static unsigned char *find_token(unsigned char *str, int len, const unsigned char *token) { int i; for (i = 0; i < len - 1; i++) { if (str[i] == token[0] && str[i+1] == token[1]) return &str[i]; } return NULL; } /* replace a given token in all the valid symbols. Use the sampled symbols * to update the counts */ static void compress_symbols(const unsigned char *str, int idx) { unsigned int i, len, size; unsigned char *p1, *p2; for (i = 0; i < table_cnt; i++) { len = table[i]->len; p1 = table[i]->sym; /* find the token on the symbol */ p2 = find_token(p1, len, str); if (!p2) continue; /* decrease the counts for this symbol's tokens */ forget_symbol(table[i]->sym, len); size = len; do { *p2 = idx; p2++; size -= (p2 - p1); memmove(p2, p2 + 1, size); p1 = p2; len--; if (size < 2) break; /* find the token on the symbol */ p2 = find_token(p1, size, str); } while (p2); table[i]->len = len; /* increase the counts for this symbol's new tokens */ learn_symbol(table[i]->sym, len); } } /* search the token with the maximum profit */ static int find_best_token(void) { int i, best, bestprofit; bestprofit=-10000; best = 0; for (i = 0; i < 0x10000; i++) { if (token_profit[i] > bestprofit) { best = i; bestprofit = token_profit[i]; } } return best; } /* this is the core of the algorithm: calculate the "best" table */ static void optimize_result(void) { int i, best; /* using the '\0' symbol last allows compress_symbols to use standard * fast string functions */ for (i = 255; i >= 0; i--) { /* if this table slot is empty (it is not used by an actual * original char code */ if (!best_table_len[i]) { /* find the token with the best profit value */ best = find_best_token(); if (token_profit[best] == 0) break; /* place it in the "best" table */ best_table_len[i] = 2; best_table[i][0] = best & 0xFF; best_table[i][1] = (best >> 8) & 0xFF; /* replace this token in all the valid symbols */ compress_symbols(best_table[i], i); } } } /* start by placing the symbols that are actually used on the table */ static void insert_real_symbols_in_table(void) { unsigned int i, j, c; for (i = 0; i < table_cnt; i++) { for (j = 0; j < table[i]->len; j++) { c = table[i]->sym[j]; best_table[c][0]=c; best_table_len[c]=1; } } } static void optimize_token_table(void) { build_initial_token_table(); insert_real_symbols_in_table(); optimize_result(); } /* guess for "linker script provide" symbol */ static int may_be_linker_script_provide_symbol(const struct sym_entry *se) { const char *symbol = sym_name(se); int len = se->len - 1; if (len < 8) return 0; if (symbol[0] != '_' || symbol[1] != '_') return 0; /* __start_XXXXX */ if (!memcmp(symbol + 2, "start_", 6)) return 1; /* __stop_XXXXX */ if (!memcmp(symbol + 2, "stop_", 5)) return 1; /* __end_XXXXX */ if (!memcmp(symbol + 2, "end_", 4)) return 1; /* __XXXXX_start */ if (!memcmp(symbol + len - 6, "_start", 6)) return 1; /* __XXXXX_end */ if (!memcmp(symbol + len - 4, "_end", 4)) return 1; return 0; } static int compare_symbols(const void *a, const void *b) { const struct sym_entry *sa = *(const struct sym_entry **)a; const struct sym_entry *sb = *(const struct sym_entry **)b; int wa, wb; /* sort by address first */ if (sa->addr > sb->addr) return 1; if (sa->addr < sb->addr) return -1; /* sort by "weakness" type */ wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W'); wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W'); if (wa != wb) return wa - wb; /* sort by "linker script provide" type */ wa = may_be_linker_script_provide_symbol(sa); wb = may_be_linker_script_provide_symbol(sb); if (wa != wb) return wa - wb; /* sort by the number of prefix underscores */ wa = strspn(sym_name(sa), "_"); wb = strspn(sym_name(sb), "_"); if (wa != wb) return wa - wb; /* sort by initial order, so that other symbols are left undisturbed */ return sa->start_pos - sb->start_pos; } static void sort_symbols(void) { qsort(table, table_cnt, sizeof(table[0]), compare_symbols); } static void make_percpus_absolute(void) { unsigned int i; for (i = 0; i < table_cnt; i++) if (symbol_in_range(table[i], &percpu_range, 1)) { /* * Keep the 'A' override for percpu symbols to * ensure consistent behavior compared to older * versions of this tool. */ table[i]->sym[0] = 'A'; table[i]->percpu_absolute = 1; } } /* find the minimum non-absolute symbol address */ static void record_relative_base(void) { unsigned int i; for (i = 0; i < table_cnt; i++) if (!symbol_absolute(table[i])) { /* * The table is sorted by address. * Take the first non-absolute symbol value. */ relative_base = table[i]->addr; return; } } int main(int argc, char **argv) { while (1) { static const struct option long_options[] = { {"all-symbols", no_argument, &all_symbols, 1}, {"absolute-percpu", no_argument, &absolute_percpu, 1}, {"base-relative", no_argument, &base_relative, 1}, {"lto-clang", no_argument, &lto_clang, 1}, {}, }; int c = getopt_long(argc, argv, "", long_options, NULL); if (c == -1) break; if (c != 0) usage(); } if (optind >= argc) usage(); read_map(argv[optind]); shrink_table(); if (absolute_percpu) make_percpus_absolute(); sort_symbols(); if (base_relative) record_relative_base(); optimize_token_table(); write_src(); return 0; }
linux-master
scripts/kallsyms.c
/* Write the contents of the <certfile> into kernel symbol system_extra_cert * * Copyright (C) IBM Corporation, 2015 * * Author: Mehmet Kayaalp <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Usage: insert-sys-cert [-s <System.map> -b <vmlinux> -c <certfile> */ #define _GNU_SOURCE #include <stdio.h> #include <ctype.h> #include <string.h> #include <limits.h> #include <stdbool.h> #include <errno.h> #include <stdlib.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <elf.h> #define CERT_SYM "system_extra_cert" #define USED_SYM "system_extra_cert_used" #define LSIZE_SYM "system_certificate_list_size" #define info(format, args...) fprintf(stderr, "INFO: " format, ## args) #define warn(format, args...) fprintf(stdout, "WARNING: " format, ## args) #define err(format, args...) fprintf(stderr, "ERROR: " format, ## args) #if UINTPTR_MAX == 0xffffffff #define CURRENT_ELFCLASS ELFCLASS32 #define Elf_Ehdr Elf32_Ehdr #define Elf_Shdr Elf32_Shdr #define Elf_Sym Elf32_Sym #else #define CURRENT_ELFCLASS ELFCLASS64 #define Elf_Ehdr Elf64_Ehdr #define Elf_Shdr Elf64_Shdr #define Elf_Sym Elf64_Sym #endif static unsigned char endianness(void) { uint16_t two_byte = 0x00FF; uint8_t low_address = *((uint8_t *)&two_byte); if (low_address == 0) return ELFDATA2MSB; else return ELFDATA2LSB; } struct sym { char *name; unsigned long address; unsigned long offset; void *content; int size; }; static unsigned long get_offset_from_address(Elf_Ehdr *hdr, unsigned long addr) { Elf_Shdr *x; unsigned int i, num_sections; x = (void *)hdr + hdr->e_shoff; if (hdr->e_shnum == SHN_UNDEF) num_sections = x[0].sh_size; else num_sections = hdr->e_shnum; for (i = 1; i < num_sections; i++) { unsigned long start = x[i].sh_addr; unsigned long end = start + x[i].sh_size; unsigned long offset = x[i].sh_offset; if (addr >= start && addr <= end) return addr - start + offset; } return 0; } #define LINE_SIZE 100 static void get_symbol_from_map(Elf_Ehdr *hdr, FILE *f, char *name, struct sym *s) { char l[LINE_SIZE]; char *w, *p, *n; s->size = 0; s->address = 0; s->offset = 0; if (fseek(f, 0, SEEK_SET) != 0) { perror("File seek failed"); exit(EXIT_FAILURE); } while (fgets(l, LINE_SIZE, f)) { p = strchr(l, '\n'); if (!p) { err("Missing line ending.\n"); return; } n = strstr(l, name); if (n) break; } if (!n) { err("Unable to find symbol: %s\n", name); return; } w = strchr(l, ' '); if (!w) return; *w = '\0'; s->address = strtoul(l, NULL, 16); if (s->address == 0) return; s->offset = get_offset_from_address(hdr, s->address); s->name = name; s->content = (void *)hdr + s->offset; } static Elf_Sym *find_elf_symbol(Elf_Ehdr *hdr, Elf_Shdr *symtab, char *name) { Elf_Sym *sym, *symtab_start; char *strtab, *symname; unsigned int link; Elf_Shdr *x; int i, n; x = (void *)hdr + hdr->e_shoff; link = symtab->sh_link; symtab_start = (void *)hdr + symtab->sh_offset; n = symtab->sh_size / symtab->sh_entsize; strtab = (void *)hdr + x[link].sh_offset; for (i = 0; i < n; i++) { sym = &symtab_start[i]; symname = strtab + sym->st_name; if (strcmp(symname, name) == 0) return sym; } err("Unable to find symbol: %s\n", name); return NULL; } static void get_symbol_from_table(Elf_Ehdr *hdr, Elf_Shdr *symtab, char *name, struct sym *s) { Elf_Shdr *sec; int secndx; Elf_Sym *elf_sym; Elf_Shdr *x; x = (void *)hdr + hdr->e_shoff; s->size = 0; s->address = 0; s->offset = 0; elf_sym = find_elf_symbol(hdr, symtab, name); if (!elf_sym) return; secndx = elf_sym->st_shndx; if (!secndx) return; sec = &x[secndx]; s->size = elf_sym->st_size; s->address = elf_sym->st_value; s->offset = s->address - sec->sh_addr + sec->sh_offset; s->name = name; s->content = (void *)hdr + s->offset; } static Elf_Shdr *get_symbol_table(Elf_Ehdr *hdr) { Elf_Shdr *x; unsigned int i, num_sections; x = (void *)hdr + hdr->e_shoff; if (hdr->e_shnum == SHN_UNDEF) num_sections = x[0].sh_size; else num_sections = hdr->e_shnum; for (i = 1; i < num_sections; i++) if (x[i].sh_type == SHT_SYMTAB) return &x[i]; return NULL; } static void *map_file(char *file_name, int *size) { struct stat st; void *map; int fd; fd = open(file_name, O_RDWR); if (fd < 0) { perror(file_name); return NULL; } if (fstat(fd, &st)) { perror("Could not determine file size"); close(fd); return NULL; } *size = st.st_size; map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { perror("Mapping to memory failed"); close(fd); return NULL; } close(fd); return map; } static char *read_file(char *file_name, int *size) { struct stat st; char *buf; int fd; fd = open(file_name, O_RDONLY); if (fd < 0) { perror(file_name); return NULL; } if (fstat(fd, &st)) { perror("Could not determine file size"); close(fd); return NULL; } *size = st.st_size; buf = malloc(*size); if (!buf) { perror("Allocating memory failed"); close(fd); return NULL; } if (read(fd, buf, *size) != *size) { perror("File read failed"); close(fd); return NULL; } close(fd); return buf; } static void print_sym(Elf_Ehdr *hdr, struct sym *s) { info("sym: %s\n", s->name); info("addr: 0x%lx\n", s->address); info("size: %d\n", s->size); info("offset: 0x%lx\n", (unsigned long)s->offset); } static void print_usage(char *e) { printf("Usage %s [-s <System.map>] -b <vmlinux> -c <certfile>\n", e); } int main(int argc, char **argv) { char *system_map_file = NULL; char *vmlinux_file = NULL; char *cert_file = NULL; int vmlinux_size; int cert_size; Elf_Ehdr *hdr; char *cert; FILE *system_map; unsigned long *lsize; int *used; int opt; Elf_Shdr *symtab = NULL; struct sym cert_sym, lsize_sym, used_sym; while ((opt = getopt(argc, argv, "b:c:s:")) != -1) { switch (opt) { case 's': system_map_file = optarg; break; case 'b': vmlinux_file = optarg; break; case 'c': cert_file = optarg; break; default: break; } } if (!vmlinux_file || !cert_file) { print_usage(argv[0]); exit(EXIT_FAILURE); } cert = read_file(cert_file, &cert_size); if (!cert) exit(EXIT_FAILURE); hdr = map_file(vmlinux_file, &vmlinux_size); if (!hdr) exit(EXIT_FAILURE); if (vmlinux_size < sizeof(*hdr)) { err("Invalid ELF file.\n"); exit(EXIT_FAILURE); } if ((hdr->e_ident[EI_MAG0] != ELFMAG0) || (hdr->e_ident[EI_MAG1] != ELFMAG1) || (hdr->e_ident[EI_MAG2] != ELFMAG2) || (hdr->e_ident[EI_MAG3] != ELFMAG3)) { err("Invalid ELF magic.\n"); exit(EXIT_FAILURE); } if (hdr->e_ident[EI_CLASS] != CURRENT_ELFCLASS) { err("ELF class mismatch.\n"); exit(EXIT_FAILURE); } if (hdr->e_ident[EI_DATA] != endianness()) { err("ELF endian mismatch.\n"); exit(EXIT_FAILURE); } if (hdr->e_shoff > vmlinux_size) { err("Could not find section header.\n"); exit(EXIT_FAILURE); } symtab = get_symbol_table(hdr); if (!symtab) { warn("Could not find the symbol table.\n"); if (!system_map_file) { err("Please provide a System.map file.\n"); print_usage(argv[0]); exit(EXIT_FAILURE); } system_map = fopen(system_map_file, "r"); if (!system_map) { perror(system_map_file); exit(EXIT_FAILURE); } get_symbol_from_map(hdr, system_map, CERT_SYM, &cert_sym); get_symbol_from_map(hdr, system_map, USED_SYM, &used_sym); get_symbol_from_map(hdr, system_map, LSIZE_SYM, &lsize_sym); cert_sym.size = used_sym.address - cert_sym.address; } else { info("Symbol table found.\n"); if (system_map_file) warn("System.map is ignored.\n"); get_symbol_from_table(hdr, symtab, CERT_SYM, &cert_sym); get_symbol_from_table(hdr, symtab, USED_SYM, &used_sym); get_symbol_from_table(hdr, symtab, LSIZE_SYM, &lsize_sym); } if (!cert_sym.offset || !lsize_sym.offset || !used_sym.offset) exit(EXIT_FAILURE); print_sym(hdr, &cert_sym); print_sym(hdr, &used_sym); print_sym(hdr, &lsize_sym); lsize = (unsigned long *)lsize_sym.content; used = (int *)used_sym.content; if (cert_sym.size < cert_size) { err("Certificate is larger than the reserved area!\n"); exit(EXIT_FAILURE); } /* If the existing cert is the same, don't overwrite */ if (cert_size == *used && strncmp(cert_sym.content, cert, cert_size) == 0) { warn("Certificate was already inserted.\n"); exit(EXIT_SUCCESS); } if (*used > 0) warn("Replacing previously inserted certificate.\n"); memcpy(cert_sym.content, cert, cert_size); if (cert_size < cert_sym.size) memset(cert_sym.content + cert_size, 0, cert_sym.size - cert_size); *lsize = *lsize + cert_size - *used; *used = cert_size; info("Inserted the contents of %s into %lx.\n", cert_file, cert_sym.address); info("Used %d bytes out of %d bytes reserved.\n", *used, cert_sym.size); exit(EXIT_SUCCESS); }
linux-master
scripts/insert-sys-cert.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Simplified ASN.1 notation parser * * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <linux/asn1_ber_bytecode.h> enum token_type { DIRECTIVE_ABSENT, DIRECTIVE_ALL, DIRECTIVE_ANY, DIRECTIVE_APPLICATION, DIRECTIVE_AUTOMATIC, DIRECTIVE_BEGIN, DIRECTIVE_BIT, DIRECTIVE_BMPString, DIRECTIVE_BOOLEAN, DIRECTIVE_BY, DIRECTIVE_CHARACTER, DIRECTIVE_CHOICE, DIRECTIVE_CLASS, DIRECTIVE_COMPONENT, DIRECTIVE_COMPONENTS, DIRECTIVE_CONSTRAINED, DIRECTIVE_CONTAINING, DIRECTIVE_DEFAULT, DIRECTIVE_DEFINED, DIRECTIVE_DEFINITIONS, DIRECTIVE_EMBEDDED, DIRECTIVE_ENCODED, DIRECTIVE_ENCODING_CONTROL, DIRECTIVE_END, DIRECTIVE_ENUMERATED, DIRECTIVE_EXCEPT, DIRECTIVE_EXPLICIT, DIRECTIVE_EXPORTS, DIRECTIVE_EXTENSIBILITY, DIRECTIVE_EXTERNAL, DIRECTIVE_FALSE, DIRECTIVE_FROM, DIRECTIVE_GeneralString, DIRECTIVE_GeneralizedTime, DIRECTIVE_GraphicString, DIRECTIVE_IA5String, DIRECTIVE_IDENTIFIER, DIRECTIVE_IMPLICIT, DIRECTIVE_IMPLIED, DIRECTIVE_IMPORTS, DIRECTIVE_INCLUDES, DIRECTIVE_INSTANCE, DIRECTIVE_INSTRUCTIONS, DIRECTIVE_INTEGER, DIRECTIVE_INTERSECTION, DIRECTIVE_ISO646String, DIRECTIVE_MAX, DIRECTIVE_MIN, DIRECTIVE_MINUS_INFINITY, DIRECTIVE_NULL, DIRECTIVE_NumericString, DIRECTIVE_OBJECT, DIRECTIVE_OCTET, DIRECTIVE_OF, DIRECTIVE_OPTIONAL, DIRECTIVE_ObjectDescriptor, DIRECTIVE_PATTERN, DIRECTIVE_PDV, DIRECTIVE_PLUS_INFINITY, DIRECTIVE_PRESENT, DIRECTIVE_PRIVATE, DIRECTIVE_PrintableString, DIRECTIVE_REAL, DIRECTIVE_RELATIVE_OID, DIRECTIVE_SEQUENCE, DIRECTIVE_SET, DIRECTIVE_SIZE, DIRECTIVE_STRING, DIRECTIVE_SYNTAX, DIRECTIVE_T61String, DIRECTIVE_TAGS, DIRECTIVE_TRUE, DIRECTIVE_TeletexString, DIRECTIVE_UNION, DIRECTIVE_UNIQUE, DIRECTIVE_UNIVERSAL, DIRECTIVE_UTCTime, DIRECTIVE_UTF8String, DIRECTIVE_UniversalString, DIRECTIVE_VideotexString, DIRECTIVE_VisibleString, DIRECTIVE_WITH, NR__DIRECTIVES, TOKEN_ASSIGNMENT = NR__DIRECTIVES, TOKEN_OPEN_CURLY, TOKEN_CLOSE_CURLY, TOKEN_OPEN_SQUARE, TOKEN_CLOSE_SQUARE, TOKEN_OPEN_ACTION, TOKEN_CLOSE_ACTION, TOKEN_COMMA, TOKEN_NUMBER, TOKEN_TYPE_NAME, TOKEN_ELEMENT_NAME, NR__TOKENS }; static const unsigned char token_to_tag[NR__TOKENS] = { /* EOC goes first */ [DIRECTIVE_BOOLEAN] = ASN1_BOOL, [DIRECTIVE_INTEGER] = ASN1_INT, [DIRECTIVE_BIT] = ASN1_BTS, [DIRECTIVE_OCTET] = ASN1_OTS, [DIRECTIVE_NULL] = ASN1_NULL, [DIRECTIVE_OBJECT] = ASN1_OID, [DIRECTIVE_ObjectDescriptor] = ASN1_ODE, [DIRECTIVE_EXTERNAL] = ASN1_EXT, [DIRECTIVE_REAL] = ASN1_REAL, [DIRECTIVE_ENUMERATED] = ASN1_ENUM, [DIRECTIVE_EMBEDDED] = 0, [DIRECTIVE_UTF8String] = ASN1_UTF8STR, [DIRECTIVE_RELATIVE_OID] = ASN1_RELOID, /* 14 */ /* 15 */ [DIRECTIVE_SEQUENCE] = ASN1_SEQ, [DIRECTIVE_SET] = ASN1_SET, [DIRECTIVE_NumericString] = ASN1_NUMSTR, [DIRECTIVE_PrintableString] = ASN1_PRNSTR, [DIRECTIVE_T61String] = ASN1_TEXSTR, [DIRECTIVE_TeletexString] = ASN1_TEXSTR, [DIRECTIVE_VideotexString] = ASN1_VIDSTR, [DIRECTIVE_IA5String] = ASN1_IA5STR, [DIRECTIVE_UTCTime] = ASN1_UNITIM, [DIRECTIVE_GeneralizedTime] = ASN1_GENTIM, [DIRECTIVE_GraphicString] = ASN1_GRASTR, [DIRECTIVE_VisibleString] = ASN1_VISSTR, [DIRECTIVE_GeneralString] = ASN1_GENSTR, [DIRECTIVE_UniversalString] = ASN1_UNITIM, [DIRECTIVE_CHARACTER] = ASN1_CHRSTR, [DIRECTIVE_BMPString] = ASN1_BMPSTR, }; static const char asn1_classes[4][5] = { [ASN1_UNIV] = "UNIV", [ASN1_APPL] = "APPL", [ASN1_CONT] = "CONT", [ASN1_PRIV] = "PRIV" }; static const char asn1_methods[2][5] = { [ASN1_UNIV] = "PRIM", [ASN1_APPL] = "CONS" }; static const char *const asn1_universal_tags[32] = { "EOC", "BOOL", "INT", "BTS", "OTS", "NULL", "OID", "ODE", "EXT", "REAL", "ENUM", "EPDV", "UTF8STR", "RELOID", NULL, /* 14 */ NULL, /* 15 */ "SEQ", "SET", "NUMSTR", "PRNSTR", "TEXSTR", "VIDSTR", "IA5STR", "UNITIM", "GENTIM", "GRASTR", "VISSTR", "GENSTR", "UNISTR", "CHRSTR", "BMPSTR", NULL /* 31 */ }; static const char *filename; static const char *grammar_name; static const char *outputname; static const char *headername; static const char *const directives[NR__DIRECTIVES] = { #define _(X) [DIRECTIVE_##X] = #X _(ABSENT), _(ALL), _(ANY), _(APPLICATION), _(AUTOMATIC), _(BEGIN), _(BIT), _(BMPString), _(BOOLEAN), _(BY), _(CHARACTER), _(CHOICE), _(CLASS), _(COMPONENT), _(COMPONENTS), _(CONSTRAINED), _(CONTAINING), _(DEFAULT), _(DEFINED), _(DEFINITIONS), _(EMBEDDED), _(ENCODED), [DIRECTIVE_ENCODING_CONTROL] = "ENCODING-CONTROL", _(END), _(ENUMERATED), _(EXCEPT), _(EXPLICIT), _(EXPORTS), _(EXTENSIBILITY), _(EXTERNAL), _(FALSE), _(FROM), _(GeneralString), _(GeneralizedTime), _(GraphicString), _(IA5String), _(IDENTIFIER), _(IMPLICIT), _(IMPLIED), _(IMPORTS), _(INCLUDES), _(INSTANCE), _(INSTRUCTIONS), _(INTEGER), _(INTERSECTION), _(ISO646String), _(MAX), _(MIN), [DIRECTIVE_MINUS_INFINITY] = "MINUS-INFINITY", [DIRECTIVE_NULL] = "NULL", _(NumericString), _(OBJECT), _(OCTET), _(OF), _(OPTIONAL), _(ObjectDescriptor), _(PATTERN), _(PDV), [DIRECTIVE_PLUS_INFINITY] = "PLUS-INFINITY", _(PRESENT), _(PRIVATE), _(PrintableString), _(REAL), [DIRECTIVE_RELATIVE_OID] = "RELATIVE-OID", _(SEQUENCE), _(SET), _(SIZE), _(STRING), _(SYNTAX), _(T61String), _(TAGS), _(TRUE), _(TeletexString), _(UNION), _(UNIQUE), _(UNIVERSAL), _(UTCTime), _(UTF8String), _(UniversalString), _(VideotexString), _(VisibleString), _(WITH) }; struct action { struct action *next; char *name; unsigned char index; }; static struct action *action_list; static unsigned nr_actions; struct token { unsigned short line; enum token_type token_type : 8; unsigned char size; struct action *action; char *content; struct type *type; }; static struct token *token_list; static unsigned nr_tokens; static bool verbose_opt; static bool debug_opt; #define verbose(fmt, ...) do { if (verbose_opt) printf(fmt, ## __VA_ARGS__); } while (0) #define debug(fmt, ...) do { if (debug_opt) printf(fmt, ## __VA_ARGS__); } while (0) static int directive_compare(const void *_key, const void *_pdir) { const struct token *token = _key; const char *const *pdir = _pdir, *dir = *pdir; size_t dlen, clen; int val; dlen = strlen(dir); clen = (dlen < token->size) ? dlen : token->size; //debug("cmp(%s,%s) = ", token->content, dir); val = memcmp(token->content, dir, clen); if (val != 0) { //debug("%d [cmp]\n", val); return val; } if (dlen == token->size) { //debug("0\n"); return 0; } //debug("%d\n", (int)dlen - (int)token->size); return dlen - token->size; /* shorter -> negative */ } /* * Tokenise an ASN.1 grammar */ static void tokenise(char *buffer, char *end) { struct token *tokens; char *line, *nl, *start, *p, *q; unsigned tix, lineno; /* Assume we're going to have half as many tokens as we have * characters */ token_list = tokens = calloc((end - buffer) / 2, sizeof(struct token)); if (!tokens) { perror(NULL); exit(1); } tix = 0; lineno = 0; while (buffer < end) { /* First of all, break out a line */ lineno++; line = buffer; nl = memchr(line, '\n', end - buffer); if (!nl) { buffer = nl = end; } else { buffer = nl + 1; *nl = '\0'; } /* Remove "--" comments */ p = line; next_comment: while ((p = memchr(p, '-', nl - p))) { if (p[1] == '-') { /* Found a comment; see if there's a terminator */ q = p + 2; while ((q = memchr(q, '-', nl - q))) { if (q[1] == '-') { /* There is - excise the comment */ q += 2; memmove(p, q, nl - q); goto next_comment; } q++; } *p = '\0'; nl = p; break; } else { p++; } } p = line; while (p < nl) { /* Skip white space */ while (p < nl && isspace(*p)) *(p++) = 0; if (p >= nl) break; tokens[tix].line = lineno; start = p; /* Handle string tokens */ if (isalpha(*p)) { const char **dir; /* Can be a directive, type name or element * name. Find the end of the name. */ q = p + 1; while (q < nl && (isalnum(*q) || *q == '-' || *q == '_')) q++; tokens[tix].size = q - p; p = q; tokens[tix].content = malloc(tokens[tix].size + 1); if (!tokens[tix].content) { perror(NULL); exit(1); } memcpy(tokens[tix].content, start, tokens[tix].size); tokens[tix].content[tokens[tix].size] = 0; /* If it begins with a lowercase letter then * it's an element name */ if (islower(tokens[tix].content[0])) { tokens[tix++].token_type = TOKEN_ELEMENT_NAME; continue; } /* Otherwise we need to search the directive * table */ dir = bsearch(&tokens[tix], directives, sizeof(directives) / sizeof(directives[1]), sizeof(directives[1]), directive_compare); if (dir) { tokens[tix++].token_type = dir - directives; continue; } tokens[tix++].token_type = TOKEN_TYPE_NAME; continue; } /* Handle numbers */ if (isdigit(*p)) { /* Find the end of the number */ q = p + 1; while (q < nl && (isdigit(*q))) q++; tokens[tix].size = q - p; p = q; tokens[tix].content = malloc(tokens[tix].size + 1); if (!tokens[tix].content) { perror(NULL); exit(1); } memcpy(tokens[tix].content, start, tokens[tix].size); tokens[tix].content[tokens[tix].size] = 0; tokens[tix++].token_type = TOKEN_NUMBER; continue; } if (nl - p >= 3) { if (memcmp(p, "::=", 3) == 0) { p += 3; tokens[tix].size = 3; tokens[tix].content = "::="; tokens[tix++].token_type = TOKEN_ASSIGNMENT; continue; } } if (nl - p >= 2) { if (memcmp(p, "({", 2) == 0) { p += 2; tokens[tix].size = 2; tokens[tix].content = "({"; tokens[tix++].token_type = TOKEN_OPEN_ACTION; continue; } if (memcmp(p, "})", 2) == 0) { p += 2; tokens[tix].size = 2; tokens[tix].content = "})"; tokens[tix++].token_type = TOKEN_CLOSE_ACTION; continue; } } if (nl - p >= 1) { tokens[tix].size = 1; switch (*p) { case '{': p += 1; tokens[tix].content = "{"; tokens[tix++].token_type = TOKEN_OPEN_CURLY; continue; case '}': p += 1; tokens[tix].content = "}"; tokens[tix++].token_type = TOKEN_CLOSE_CURLY; continue; case '[': p += 1; tokens[tix].content = "["; tokens[tix++].token_type = TOKEN_OPEN_SQUARE; continue; case ']': p += 1; tokens[tix].content = "]"; tokens[tix++].token_type = TOKEN_CLOSE_SQUARE; continue; case ',': p += 1; tokens[tix].content = ","; tokens[tix++].token_type = TOKEN_COMMA; continue; default: break; } } fprintf(stderr, "%s:%u: Unknown character in grammar: '%c'\n", filename, lineno, *p); exit(1); } } nr_tokens = tix; verbose("Extracted %u tokens\n", nr_tokens); #if 0 { int n; for (n = 0; n < nr_tokens; n++) debug("Token %3u: '%s'\n", n, token_list[n].content); } #endif } static void build_type_list(void); static void parse(void); static void dump_elements(void); static void render(FILE *out, FILE *hdr); /* * */ int main(int argc, char **argv) { struct stat st; ssize_t readlen; FILE *out, *hdr; char *buffer, *p; char *kbuild_verbose; int fd; kbuild_verbose = getenv("KBUILD_VERBOSE"); if (kbuild_verbose && strchr(kbuild_verbose, '1')) verbose_opt = true; while (argc > 4) { if (strcmp(argv[1], "-v") == 0) verbose_opt = true; else if (strcmp(argv[1], "-d") == 0) debug_opt = true; else break; memmove(&argv[1], &argv[2], (argc - 2) * sizeof(char *)); argc--; } if (argc != 4) { fprintf(stderr, "Format: %s [-v] [-d] <grammar-file> <c-file> <hdr-file>\n", argv[0]); exit(2); } filename = argv[1]; outputname = argv[2]; headername = argv[3]; fd = open(filename, O_RDONLY); if (fd < 0) { perror(filename); exit(1); } if (fstat(fd, &st) < 0) { perror(filename); exit(1); } if (!(buffer = malloc(st.st_size + 1))) { perror(NULL); exit(1); } if ((readlen = read(fd, buffer, st.st_size)) < 0) { perror(filename); exit(1); } if (close(fd) < 0) { perror(filename); exit(1); } if (readlen != st.st_size) { fprintf(stderr, "%s: Short read\n", filename); exit(1); } p = strrchr(argv[1], '/'); p = p ? p + 1 : argv[1]; grammar_name = strdup(p); if (!grammar_name) { perror(NULL); exit(1); } p = strchr(grammar_name, '.'); if (p) *p = '\0'; buffer[readlen] = 0; tokenise(buffer, buffer + readlen); build_type_list(); parse(); dump_elements(); out = fopen(outputname, "w"); if (!out) { perror(outputname); exit(1); } hdr = fopen(headername, "w"); if (!hdr) { perror(headername); exit(1); } render(out, hdr); if (fclose(out) < 0) { perror(outputname); exit(1); } if (fclose(hdr) < 0) { perror(headername); exit(1); } return 0; } enum compound { NOT_COMPOUND, SET, SET_OF, SEQUENCE, SEQUENCE_OF, CHOICE, ANY, TYPE_REF, TAG_OVERRIDE }; struct element { struct type *type_def; struct token *name; struct token *type; struct action *action; struct element *children; struct element *next; struct element *render_next; struct element *list_next; uint8_t n_elements; enum compound compound : 8; enum asn1_class class : 8; enum asn1_method method : 8; uint8_t tag; unsigned entry_index; unsigned flags; #define ELEMENT_IMPLICIT 0x0001 #define ELEMENT_EXPLICIT 0x0002 #define ELEMENT_TAG_SPECIFIED 0x0004 #define ELEMENT_RENDERED 0x0008 #define ELEMENT_SKIPPABLE 0x0010 #define ELEMENT_CONDITIONAL 0x0020 }; struct type { struct token *name; struct token *def; struct element *element; unsigned ref_count; unsigned flags; #define TYPE_STOP_MARKER 0x0001 #define TYPE_BEGIN 0x0002 }; static struct type *type_list; static struct type **type_index; static unsigned nr_types; static int type_index_compare(const void *_a, const void *_b) { const struct type *const *a = _a, *const *b = _b; if ((*a)->name->size != (*b)->name->size) return (*a)->name->size - (*b)->name->size; else return memcmp((*a)->name->content, (*b)->name->content, (*a)->name->size); } static int type_finder(const void *_key, const void *_ti) { const struct token *token = _key; const struct type *const *ti = _ti; const struct type *type = *ti; if (token->size != type->name->size) return token->size - type->name->size; else return memcmp(token->content, type->name->content, token->size); } /* * Build up a list of types and a sorted index to that list. */ static void build_type_list(void) { struct type *types; unsigned nr, t, n; nr = 0; for (n = 0; n < nr_tokens - 1; n++) if (token_list[n + 0].token_type == TOKEN_TYPE_NAME && token_list[n + 1].token_type == TOKEN_ASSIGNMENT) nr++; if (nr == 0) { fprintf(stderr, "%s: No defined types\n", filename); exit(1); } nr_types = nr; types = type_list = calloc(nr + 1, sizeof(type_list[0])); if (!type_list) { perror(NULL); exit(1); } type_index = calloc(nr, sizeof(type_index[0])); if (!type_index) { perror(NULL); exit(1); } t = 0; types[t].flags |= TYPE_BEGIN; for (n = 0; n < nr_tokens - 1; n++) { if (token_list[n + 0].token_type == TOKEN_TYPE_NAME && token_list[n + 1].token_type == TOKEN_ASSIGNMENT) { types[t].name = &token_list[n]; type_index[t] = &types[t]; t++; } } types[t].name = &token_list[n + 1]; types[t].flags |= TYPE_STOP_MARKER; qsort(type_index, nr, sizeof(type_index[0]), type_index_compare); verbose("Extracted %u types\n", nr_types); #if 0 for (n = 0; n < nr_types; n++) { struct type *type = type_index[n]; debug("- %*.*s\n", type->name->content); } #endif } static struct element *parse_type(struct token **_cursor, struct token *stop, struct token *name); /* * Parse the token stream */ static void parse(void) { struct token *cursor; struct type *type; /* Parse one type definition statement at a time */ type = type_list; do { cursor = type->name; if (cursor[0].token_type != TOKEN_TYPE_NAME || cursor[1].token_type != TOKEN_ASSIGNMENT) abort(); cursor += 2; type->element = parse_type(&cursor, type[1].name, NULL); type->element->type_def = type; if (cursor != type[1].name) { fprintf(stderr, "%s:%d: Parse error at token '%s'\n", filename, cursor->line, cursor->content); exit(1); } } while (type++, !(type->flags & TYPE_STOP_MARKER)); verbose("Extracted %u actions\n", nr_actions); } static struct element *element_list; static struct element *alloc_elem(void) { struct element *e = calloc(1, sizeof(*e)); if (!e) { perror(NULL); exit(1); } e->list_next = element_list; element_list = e; return e; } static struct element *parse_compound(struct token **_cursor, struct token *end, int alternates); /* * Parse one type definition statement */ static struct element *parse_type(struct token **_cursor, struct token *end, struct token *name) { struct element *top, *element; struct action *action, **ppaction; struct token *cursor = *_cursor; struct type **ref; char *p; int labelled = 0, implicit = 0; top = element = alloc_elem(); element->class = ASN1_UNIV; element->method = ASN1_PRIM; element->tag = token_to_tag[cursor->token_type]; element->name = name; /* Extract the tag value if one given */ if (cursor->token_type == TOKEN_OPEN_SQUARE) { cursor++; if (cursor >= end) goto overrun_error; switch (cursor->token_type) { case DIRECTIVE_UNIVERSAL: element->class = ASN1_UNIV; cursor++; break; case DIRECTIVE_APPLICATION: element->class = ASN1_APPL; cursor++; break; case TOKEN_NUMBER: element->class = ASN1_CONT; break; case DIRECTIVE_PRIVATE: element->class = ASN1_PRIV; cursor++; break; default: fprintf(stderr, "%s:%d: Unrecognised tag class token '%s'\n", filename, cursor->line, cursor->content); exit(1); } if (cursor >= end) goto overrun_error; if (cursor->token_type != TOKEN_NUMBER) { fprintf(stderr, "%s:%d: Missing tag number '%s'\n", filename, cursor->line, cursor->content); exit(1); } element->tag &= ~0x1f; element->tag |= strtoul(cursor->content, &p, 10); element->flags |= ELEMENT_TAG_SPECIFIED; if (p - cursor->content != cursor->size) abort(); cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type != TOKEN_CLOSE_SQUARE) { fprintf(stderr, "%s:%d: Missing closing square bracket '%s'\n", filename, cursor->line, cursor->content); exit(1); } cursor++; if (cursor >= end) goto overrun_error; labelled = 1; } /* Handle implicit and explicit markers */ if (cursor->token_type == DIRECTIVE_IMPLICIT) { element->flags |= ELEMENT_IMPLICIT; implicit = 1; cursor++; if (cursor >= end) goto overrun_error; } else if (cursor->token_type == DIRECTIVE_EXPLICIT) { element->flags |= ELEMENT_EXPLICIT; cursor++; if (cursor >= end) goto overrun_error; } if (labelled) { if (!implicit) element->method |= ASN1_CONS; element->compound = implicit ? TAG_OVERRIDE : SEQUENCE; element->children = alloc_elem(); element = element->children; element->class = ASN1_UNIV; element->method = ASN1_PRIM; element->tag = token_to_tag[cursor->token_type]; element->name = name; } /* Extract the type we're expecting here */ element->type = cursor; switch (cursor->token_type) { case DIRECTIVE_ANY: element->compound = ANY; cursor++; break; case DIRECTIVE_NULL: case DIRECTIVE_BOOLEAN: case DIRECTIVE_ENUMERATED: case DIRECTIVE_INTEGER: element->compound = NOT_COMPOUND; cursor++; break; case DIRECTIVE_EXTERNAL: element->method = ASN1_CONS; case DIRECTIVE_BMPString: case DIRECTIVE_GeneralString: case DIRECTIVE_GraphicString: case DIRECTIVE_IA5String: case DIRECTIVE_ISO646String: case DIRECTIVE_NumericString: case DIRECTIVE_PrintableString: case DIRECTIVE_T61String: case DIRECTIVE_TeletexString: case DIRECTIVE_UniversalString: case DIRECTIVE_UTF8String: case DIRECTIVE_VideotexString: case DIRECTIVE_VisibleString: case DIRECTIVE_ObjectDescriptor: case DIRECTIVE_GeneralizedTime: case DIRECTIVE_UTCTime: element->compound = NOT_COMPOUND; cursor++; break; case DIRECTIVE_BIT: case DIRECTIVE_OCTET: element->compound = NOT_COMPOUND; cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type != DIRECTIVE_STRING) goto parse_error; cursor++; break; case DIRECTIVE_OBJECT: element->compound = NOT_COMPOUND; cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type != DIRECTIVE_IDENTIFIER) goto parse_error; cursor++; break; case TOKEN_TYPE_NAME: element->compound = TYPE_REF; ref = bsearch(cursor, type_index, nr_types, sizeof(type_index[0]), type_finder); if (!ref) { fprintf(stderr, "%s:%d: Type '%s' undefined\n", filename, cursor->line, cursor->content); exit(1); } cursor->type = *ref; (*ref)->ref_count++; cursor++; break; case DIRECTIVE_CHOICE: element->compound = CHOICE; cursor++; element->children = parse_compound(&cursor, end, 1); break; case DIRECTIVE_SEQUENCE: element->compound = SEQUENCE; element->method = ASN1_CONS; cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type == DIRECTIVE_OF) { element->compound = SEQUENCE_OF; cursor++; if (cursor >= end) goto overrun_error; element->children = parse_type(&cursor, end, NULL); } else { element->children = parse_compound(&cursor, end, 0); } break; case DIRECTIVE_SET: element->compound = SET; element->method = ASN1_CONS; cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type == DIRECTIVE_OF) { element->compound = SET_OF; cursor++; if (cursor >= end) goto parse_error; element->children = parse_type(&cursor, end, NULL); } else { element->children = parse_compound(&cursor, end, 1); } break; default: fprintf(stderr, "%s:%d: Token '%s' does not introduce a type\n", filename, cursor->line, cursor->content); exit(1); } /* Handle elements that are optional */ if (cursor < end && (cursor->token_type == DIRECTIVE_OPTIONAL || cursor->token_type == DIRECTIVE_DEFAULT) ) { cursor++; top->flags |= ELEMENT_SKIPPABLE; } if (cursor < end && cursor->token_type == TOKEN_OPEN_ACTION) { cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type != TOKEN_ELEMENT_NAME) { fprintf(stderr, "%s:%d: Token '%s' is not an action function name\n", filename, cursor->line, cursor->content); exit(1); } action = malloc(sizeof(struct action)); if (!action) { perror(NULL); exit(1); } action->index = 0; action->name = cursor->content; for (ppaction = &action_list; *ppaction; ppaction = &(*ppaction)->next ) { int cmp = strcmp(action->name, (*ppaction)->name); if (cmp == 0) { free(action); action = *ppaction; goto found; } if (cmp < 0) { action->next = *ppaction; *ppaction = action; nr_actions++; goto found; } } action->next = NULL; *ppaction = action; nr_actions++; found: element->action = action; cursor->action = action; cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type != TOKEN_CLOSE_ACTION) { fprintf(stderr, "%s:%d: Missing close action, got '%s'\n", filename, cursor->line, cursor->content); exit(1); } cursor++; } *_cursor = cursor; return top; parse_error: fprintf(stderr, "%s:%d: Unexpected token '%s'\n", filename, cursor->line, cursor->content); exit(1); overrun_error: fprintf(stderr, "%s: Unexpectedly hit EOF\n", filename); exit(1); } /* * Parse a compound type list */ static struct element *parse_compound(struct token **_cursor, struct token *end, int alternates) { struct element *children, **child_p = &children, *element; struct token *cursor = *_cursor, *name; if (cursor->token_type != TOKEN_OPEN_CURLY) { fprintf(stderr, "%s:%d: Expected compound to start with brace not '%s'\n", filename, cursor->line, cursor->content); exit(1); } cursor++; if (cursor >= end) goto overrun_error; if (cursor->token_type == TOKEN_OPEN_CURLY) { fprintf(stderr, "%s:%d: Empty compound\n", filename, cursor->line); exit(1); } for (;;) { name = NULL; if (cursor->token_type == TOKEN_ELEMENT_NAME) { name = cursor; cursor++; if (cursor >= end) goto overrun_error; } element = parse_type(&cursor, end, name); if (alternates) element->flags |= ELEMENT_SKIPPABLE | ELEMENT_CONDITIONAL; *child_p = element; child_p = &element->next; if (cursor >= end) goto overrun_error; if (cursor->token_type != TOKEN_COMMA) break; cursor++; if (cursor >= end) goto overrun_error; } children->flags &= ~ELEMENT_CONDITIONAL; if (cursor->token_type != TOKEN_CLOSE_CURLY) { fprintf(stderr, "%s:%d: Expected compound closure, got '%s'\n", filename, cursor->line, cursor->content); exit(1); } cursor++; *_cursor = cursor; return children; overrun_error: fprintf(stderr, "%s: Unexpectedly hit EOF\n", filename); exit(1); } static void dump_element(const struct element *e, int level) { const struct element *c; const struct type *t = e->type_def; const char *name = e->name ? e->name->content : "."; const char *tname = t && t->name ? t->name->content : "."; char tag[32]; if (e->class == 0 && e->method == 0 && e->tag == 0) strcpy(tag, "<...>"); else if (e->class == ASN1_UNIV) sprintf(tag, "%s %s %s", asn1_classes[e->class], asn1_methods[e->method], asn1_universal_tags[e->tag]); else sprintf(tag, "%s %s %u", asn1_classes[e->class], asn1_methods[e->method], e->tag); printf("%c%c%c%c%c %c %*s[*] \e[33m%s\e[m %s %s \e[35m%s\e[m\n", e->flags & ELEMENT_IMPLICIT ? 'I' : '-', e->flags & ELEMENT_EXPLICIT ? 'E' : '-', e->flags & ELEMENT_TAG_SPECIFIED ? 'T' : '-', e->flags & ELEMENT_SKIPPABLE ? 'S' : '-', e->flags & ELEMENT_CONDITIONAL ? 'C' : '-', "-tTqQcaro"[e->compound], level, "", tag, tname, name, e->action ? e->action->name : ""); if (e->compound == TYPE_REF) dump_element(e->type->type->element, level + 3); else for (c = e->children; c; c = c->next) dump_element(c, level + 3); } static void dump_elements(void) { if (debug_opt) dump_element(type_list[0].element, 0); } static void render_element(FILE *out, struct element *e, struct element *tag); static void render_out_of_line_list(FILE *out); static int nr_entries; static int render_depth = 1; static struct element *render_list, **render_list_p = &render_list; __attribute__((format(printf, 2, 3))) static void render_opcode(FILE *out, const char *fmt, ...) { va_list va; if (out) { fprintf(out, "\t[%4d] =%*s", nr_entries, render_depth, ""); va_start(va, fmt); vfprintf(out, fmt, va); va_end(va); } nr_entries++; } __attribute__((format(printf, 2, 3))) static void render_more(FILE *out, const char *fmt, ...) { va_list va; if (out) { va_start(va, fmt); vfprintf(out, fmt, va); va_end(va); } } /* * Render the grammar into a state machine definition. */ static void render(FILE *out, FILE *hdr) { struct element *e; struct action *action; struct type *root; int index; fprintf(hdr, "/*\n"); fprintf(hdr, " * Automatically generated by asn1_compiler. Do not edit\n"); fprintf(hdr, " *\n"); fprintf(hdr, " * ASN.1 parser for %s\n", grammar_name); fprintf(hdr, " */\n"); fprintf(hdr, "#include <linux/asn1_decoder.h>\n"); fprintf(hdr, "\n"); fprintf(hdr, "extern const struct asn1_decoder %s_decoder;\n", grammar_name); if (ferror(hdr)) { perror(headername); exit(1); } fprintf(out, "/*\n"); fprintf(out, " * Automatically generated by asn1_compiler. Do not edit\n"); fprintf(out, " *\n"); fprintf(out, " * ASN.1 parser for %s\n", grammar_name); fprintf(out, " */\n"); fprintf(out, "#include <linux/asn1_ber_bytecode.h>\n"); fprintf(out, "#include \"%s.asn1.h\"\n", grammar_name); fprintf(out, "\n"); if (ferror(out)) { perror(outputname); exit(1); } /* Tabulate the action functions we might have to call */ fprintf(hdr, "\n"); index = 0; for (action = action_list; action; action = action->next) { action->index = index++; fprintf(hdr, "extern int %s(void *, size_t, unsigned char," " const void *, size_t);\n", action->name); } fprintf(hdr, "\n"); fprintf(out, "enum %s_actions {\n", grammar_name); for (action = action_list; action; action = action->next) fprintf(out, "\tACT_%s = %u,\n", action->name, action->index); fprintf(out, "\tNR__%s_actions = %u\n", grammar_name, nr_actions); fprintf(out, "};\n"); fprintf(out, "\n"); fprintf(out, "static const asn1_action_t %s_action_table[NR__%s_actions] = {\n", grammar_name, grammar_name); for (action = action_list; action; action = action->next) fprintf(out, "\t[%4u] = %s,\n", action->index, action->name); fprintf(out, "};\n"); if (ferror(out)) { perror(outputname); exit(1); } /* We do two passes - the first one calculates all the offsets */ verbose("Pass 1\n"); nr_entries = 0; root = &type_list[0]; render_element(NULL, root->element, NULL); render_opcode(NULL, "ASN1_OP_COMPLETE,\n"); render_out_of_line_list(NULL); for (e = element_list; e; e = e->list_next) e->flags &= ~ELEMENT_RENDERED; /* And then we actually render */ verbose("Pass 2\n"); fprintf(out, "\n"); fprintf(out, "static const unsigned char %s_machine[] = {\n", grammar_name); nr_entries = 0; root = &type_list[0]; render_element(out, root->element, NULL); render_opcode(out, "ASN1_OP_COMPLETE,\n"); render_out_of_line_list(out); fprintf(out, "};\n"); fprintf(out, "\n"); fprintf(out, "const struct asn1_decoder %s_decoder = {\n", grammar_name); fprintf(out, "\t.machine = %s_machine,\n", grammar_name); fprintf(out, "\t.machlen = sizeof(%s_machine),\n", grammar_name); fprintf(out, "\t.actions = %s_action_table,\n", grammar_name); fprintf(out, "};\n"); } /* * Render the out-of-line elements */ static void render_out_of_line_list(FILE *out) { struct element *e, *ce; const char *act; int entry; while ((e = render_list)) { render_list = e->render_next; if (!render_list) render_list_p = &render_list; render_more(out, "\n"); e->entry_index = entry = nr_entries; render_depth++; for (ce = e->children; ce; ce = ce->next) render_element(out, ce, NULL); render_depth--; act = e->action ? "_ACT" : ""; switch (e->compound) { case SEQUENCE: render_opcode(out, "ASN1_OP_END_SEQ%s,\n", act); break; case SEQUENCE_OF: render_opcode(out, "ASN1_OP_END_SEQ_OF%s,\n", act); render_opcode(out, "_jump_target(%u),\n", entry); break; case SET: render_opcode(out, "ASN1_OP_END_SET%s,\n", act); break; case SET_OF: render_opcode(out, "ASN1_OP_END_SET_OF%s,\n", act); render_opcode(out, "_jump_target(%u),\n", entry); break; default: break; } if (e->action) render_opcode(out, "_action(ACT_%s),\n", e->action->name); render_opcode(out, "ASN1_OP_RETURN,\n"); } } /* * Render an element. */ static void render_element(FILE *out, struct element *e, struct element *tag) { struct element *ec, *x; const char *cond, *act; int entry, skippable = 0, outofline = 0; if (e->flags & ELEMENT_SKIPPABLE || (tag && tag->flags & ELEMENT_SKIPPABLE)) skippable = 1; if ((e->type_def && e->type_def->ref_count > 1) || skippable) outofline = 1; if (e->type_def && out) { render_more(out, "\t// %s\n", e->type_def->name->content); } /* Render the operation */ cond = (e->flags & ELEMENT_CONDITIONAL || (tag && tag->flags & ELEMENT_CONDITIONAL)) ? "COND_" : ""; act = e->action ? "_ACT" : ""; switch (e->compound) { case ANY: render_opcode(out, "ASN1_OP_%sMATCH_ANY%s%s,", cond, act, skippable ? "_OR_SKIP" : ""); if (e->name) render_more(out, "\t\t// %s", e->name->content); render_more(out, "\n"); goto dont_render_tag; case TAG_OVERRIDE: render_element(out, e->children, e); return; case SEQUENCE: case SEQUENCE_OF: case SET: case SET_OF: render_opcode(out, "ASN1_OP_%sMATCH%s%s,", cond, outofline ? "_JUMP" : "", skippable ? "_OR_SKIP" : ""); break; case CHOICE: goto dont_render_tag; case TYPE_REF: if (e->class == ASN1_UNIV && e->method == ASN1_PRIM && e->tag == 0) goto dont_render_tag; default: render_opcode(out, "ASN1_OP_%sMATCH%s%s,", cond, act, skippable ? "_OR_SKIP" : ""); break; } x = tag ?: e; if (x->name) render_more(out, "\t\t// %s", x->name->content); render_more(out, "\n"); /* Render the tag */ if (!tag || !(tag->flags & ELEMENT_TAG_SPECIFIED)) tag = e; if (tag->class == ASN1_UNIV && tag->tag != 14 && tag->tag != 15 && tag->tag != 31) render_opcode(out, "_tag(%s, %s, %s),\n", asn1_classes[tag->class], asn1_methods[tag->method | e->method], asn1_universal_tags[tag->tag]); else render_opcode(out, "_tagn(%s, %s, %2u),\n", asn1_classes[tag->class], asn1_methods[tag->method | e->method], tag->tag); tag = NULL; dont_render_tag: /* Deal with compound types */ switch (e->compound) { case TYPE_REF: render_element(out, e->type->type->element, tag); if (e->action) render_opcode(out, "ASN1_OP_%sACT,\n", skippable ? "MAYBE_" : ""); break; case SEQUENCE: if (outofline) { /* Render out-of-line for multiple use or * skipability */ render_opcode(out, "_jump_target(%u),", e->entry_index); if (e->type_def && e->type_def->name) render_more(out, "\t\t// --> %s", e->type_def->name->content); render_more(out, "\n"); if (!(e->flags & ELEMENT_RENDERED)) { e->flags |= ELEMENT_RENDERED; *render_list_p = e; render_list_p = &e->render_next; } return; } else { /* Render inline for single use */ render_depth++; for (ec = e->children; ec; ec = ec->next) render_element(out, ec, NULL); render_depth--; render_opcode(out, "ASN1_OP_END_SEQ%s,\n", act); } break; case SEQUENCE_OF: case SET_OF: if (outofline) { /* Render out-of-line for multiple use or * skipability */ render_opcode(out, "_jump_target(%u),", e->entry_index); if (e->type_def && e->type_def->name) render_more(out, "\t\t// --> %s", e->type_def->name->content); render_more(out, "\n"); if (!(e->flags & ELEMENT_RENDERED)) { e->flags |= ELEMENT_RENDERED; *render_list_p = e; render_list_p = &e->render_next; } return; } else { /* Render inline for single use */ entry = nr_entries; render_depth++; render_element(out, e->children, NULL); render_depth--; if (e->compound == SEQUENCE_OF) render_opcode(out, "ASN1_OP_END_SEQ_OF%s,\n", act); else render_opcode(out, "ASN1_OP_END_SET_OF%s,\n", act); render_opcode(out, "_jump_target(%u),\n", entry); } break; case SET: /* I can't think of a nice way to do SET support without having * a stack of bitmasks to make sure no element is repeated. * The bitmask has also to be checked that no non-optional * elements are left out whilst not preventing optional * elements from being left out. */ fprintf(stderr, "The ASN.1 SET type is not currently supported.\n"); exit(1); case CHOICE: for (ec = e->children; ec; ec = ec->next) render_element(out, ec, ec); if (!skippable) render_opcode(out, "ASN1_OP_COND_FAIL,\n"); if (e->action) render_opcode(out, "ASN1_OP_ACT,\n"); break; default: break; } if (e->action) render_opcode(out, "_action(ACT_%s),\n", e->action->name); }
linux-master
scripts/asn1_compiler.c
// SPDX-License-Identifier: GPL-2.0-only /* * sorttable.c: Sort the kernel's table * * Added ORC unwind tables sort support and other updates: * Copyright (C) 1999-2019 Alibaba Group Holding Limited. by: * Shile Zhang <[email protected]> * * Copyright 2011 - 2012 Cavium, Inc. * * Based on code taken from recortmcount.c which is: * * Copyright 2009 John F. Reiser <[email protected]>. All rights reserved. * * Restructured to fit Linux format, as well as other updates: * Copyright 2010 Steven Rostedt <[email protected]>, Red Hat Inc. */ /* * Strategy: alter the vmlinux file in-place. */ #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <getopt.h> #include <elf.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include <tools/be_byteshift.h> #include <tools/le_byteshift.h> #ifndef EM_ARCOMPACT #define EM_ARCOMPACT 93 #endif #ifndef EM_XTENSA #define EM_XTENSA 94 #endif #ifndef EM_AARCH64 #define EM_AARCH64 183 #endif #ifndef EM_MICROBLAZE #define EM_MICROBLAZE 189 #endif #ifndef EM_ARCV2 #define EM_ARCV2 195 #endif #ifndef EM_RISCV #define EM_RISCV 243 #endif #ifndef EM_LOONGARCH #define EM_LOONGARCH 258 #endif static uint32_t (*r)(const uint32_t *); static uint16_t (*r2)(const uint16_t *); static uint64_t (*r8)(const uint64_t *); static void (*w)(uint32_t, uint32_t *); static void (*w2)(uint16_t, uint16_t *); static void (*w8)(uint64_t, uint64_t *); typedef void (*table_sort_t)(char *, int); /* * Get the whole file as a programming convenience in order to avoid * malloc+lseek+read+free of many pieces. If successful, then mmap * avoids copying unused pieces; else just read the whole file. * Open for both read and write. */ static void *mmap_file(char const *fname, size_t *size) { int fd; struct stat sb; void *addr = NULL; fd = open(fname, O_RDWR); if (fd < 0) { perror(fname); return NULL; } if (fstat(fd, &sb) < 0) { perror(fname); goto out; } if (!S_ISREG(sb.st_mode)) { fprintf(stderr, "not a regular file: %s\n", fname); goto out; } addr = mmap(0, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) { fprintf(stderr, "Could not mmap file: %s\n", fname); goto out; } *size = sb.st_size; out: close(fd); return addr; } static uint32_t rbe(const uint32_t *x) { return get_unaligned_be32(x); } static uint16_t r2be(const uint16_t *x) { return get_unaligned_be16(x); } static uint64_t r8be(const uint64_t *x) { return get_unaligned_be64(x); } static uint32_t rle(const uint32_t *x) { return get_unaligned_le32(x); } static uint16_t r2le(const uint16_t *x) { return get_unaligned_le16(x); } static uint64_t r8le(const uint64_t *x) { return get_unaligned_le64(x); } static void wbe(uint32_t val, uint32_t *x) { put_unaligned_be32(val, x); } static void w2be(uint16_t val, uint16_t *x) { put_unaligned_be16(val, x); } static void w8be(uint64_t val, uint64_t *x) { put_unaligned_be64(val, x); } static void wle(uint32_t val, uint32_t *x) { put_unaligned_le32(val, x); } static void w2le(uint16_t val, uint16_t *x) { put_unaligned_le16(val, x); } static void w8le(uint64_t val, uint64_t *x) { put_unaligned_le64(val, x); } /* * Move reserved section indices SHN_LORESERVE..SHN_HIRESERVE out of * the way to -256..-1, to avoid conflicting with real section * indices. */ #define SPECIAL(i) ((i) - (SHN_HIRESERVE + 1)) static inline int is_shndx_special(unsigned int i) { return i != SHN_XINDEX && i >= SHN_LORESERVE && i <= SHN_HIRESERVE; } /* Accessor for sym->st_shndx, hides ugliness of "64k sections" */ static inline unsigned int get_secindex(unsigned int shndx, unsigned int sym_offs, const Elf32_Word *symtab_shndx_start) { if (is_shndx_special(shndx)) return SPECIAL(shndx); if (shndx != SHN_XINDEX) return shndx; return r(&symtab_shndx_start[sym_offs]); } /* 32 bit and 64 bit are very similar */ #include "sorttable.h" #define SORTTABLE_64 #include "sorttable.h" static int compare_relative_table(const void *a, const void *b) { int32_t av = (int32_t)r(a); int32_t bv = (int32_t)r(b); if (av < bv) return -1; if (av > bv) return 1; return 0; } static void sort_relative_table(char *extab_image, int image_size) { int i = 0; /* * Do the same thing the runtime sort does, first normalize to * being relative to the start of the section. */ while (i < image_size) { uint32_t *loc = (uint32_t *)(extab_image + i); w(r(loc) + i, loc); i += 4; } qsort(extab_image, image_size / 8, 8, compare_relative_table); /* Now denormalize. */ i = 0; while (i < image_size) { uint32_t *loc = (uint32_t *)(extab_image + i); w(r(loc) - i, loc); i += 4; } } static void sort_relative_table_with_data(char *extab_image, int image_size) { int i = 0; while (i < image_size) { uint32_t *loc = (uint32_t *)(extab_image + i); w(r(loc) + i, loc); w(r(loc + 1) + i + 4, loc + 1); /* Don't touch the fixup type or data */ i += sizeof(uint32_t) * 3; } qsort(extab_image, image_size / 12, 12, compare_relative_table); i = 0; while (i < image_size) { uint32_t *loc = (uint32_t *)(extab_image + i); w(r(loc) - i, loc); w(r(loc + 1) - (i + 4), loc + 1); /* Don't touch the fixup type or data */ i += sizeof(uint32_t) * 3; } } static int do_file(char const *const fname, void *addr) { int rc = -1; Elf32_Ehdr *ehdr = addr; table_sort_t custom_sort = NULL; switch (ehdr->e_ident[EI_DATA]) { case ELFDATA2LSB: r = rle; r2 = r2le; r8 = r8le; w = wle; w2 = w2le; w8 = w8le; break; case ELFDATA2MSB: r = rbe; r2 = r2be; r8 = r8be; w = wbe; w2 = w2be; w8 = w8be; break; default: fprintf(stderr, "unrecognized ELF data encoding %d: %s\n", ehdr->e_ident[EI_DATA], fname); return -1; } if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0 || (r2(&ehdr->e_type) != ET_EXEC && r2(&ehdr->e_type) != ET_DYN) || ehdr->e_ident[EI_VERSION] != EV_CURRENT) { fprintf(stderr, "unrecognized ET_EXEC/ET_DYN file %s\n", fname); return -1; } switch (r2(&ehdr->e_machine)) { case EM_386: case EM_AARCH64: case EM_LOONGARCH: case EM_RISCV: case EM_S390: case EM_X86_64: custom_sort = sort_relative_table_with_data; break; case EM_PARISC: case EM_PPC: case EM_PPC64: custom_sort = sort_relative_table; break; case EM_ARCOMPACT: case EM_ARCV2: case EM_ARM: case EM_MICROBLAZE: case EM_MIPS: case EM_XTENSA: break; default: fprintf(stderr, "unrecognized e_machine %d %s\n", r2(&ehdr->e_machine), fname); return -1; } switch (ehdr->e_ident[EI_CLASS]) { case ELFCLASS32: if (r2(&ehdr->e_ehsize) != sizeof(Elf32_Ehdr) || r2(&ehdr->e_shentsize) != sizeof(Elf32_Shdr)) { fprintf(stderr, "unrecognized ET_EXEC/ET_DYN file: %s\n", fname); break; } rc = do_sort_32(ehdr, fname, custom_sort); break; case ELFCLASS64: { Elf64_Ehdr *const ghdr = (Elf64_Ehdr *)ehdr; if (r2(&ghdr->e_ehsize) != sizeof(Elf64_Ehdr) || r2(&ghdr->e_shentsize) != sizeof(Elf64_Shdr)) { fprintf(stderr, "unrecognized ET_EXEC/ET_DYN file: %s\n", fname); break; } rc = do_sort_64(ghdr, fname, custom_sort); } break; default: fprintf(stderr, "unrecognized ELF class %d %s\n", ehdr->e_ident[EI_CLASS], fname); break; } return rc; } int main(int argc, char *argv[]) { int i, n_error = 0; /* gcc-4.3.0 false positive complaint */ size_t size = 0; void *addr = NULL; if (argc < 2) { fprintf(stderr, "usage: sorttable vmlinux...\n"); return 0; } /* Process each file in turn, allowing deep failure. */ for (i = 1; i < argc; i++) { addr = mmap_file(argv[i], &size); if (!addr) { ++n_error; continue; } if (do_file(argv[i], addr)) ++n_error; munmap(addr, size); } return !!n_error; }
linux-master
scripts/sorttable.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Generate kernel symbol version hashes. Copyright 1996, 1997 Linux International. New implementation contributed by Richard Henderson <[email protected]> Based on original work by Bjorn Ekwall <[email protected]> This file was part of the Linux modutils 2.4.22: moved back into the kernel sources by Rusty Russell/Kai Germaschewski. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <stdarg.h> #ifdef __GNU_LIBRARY__ #include <getopt.h> #endif /* __GNU_LIBRARY__ */ #include "genksyms.h" /*----------------------------------------------------------------------*/ #define HASH_BUCKETS 4096 static struct symbol *symtab[HASH_BUCKETS]; static FILE *debugfile; int cur_line = 1; char *cur_filename; int in_source_file; static int flag_debug, flag_dump_defs, flag_reference, flag_dump_types, flag_preserve, flag_warnings; static int errors; static int nsyms; static struct symbol *expansion_trail; static struct symbol *visited_symbols; static const struct { int n; const char *name; } symbol_types[] = { [SYM_NORMAL] = { 0, NULL}, [SYM_TYPEDEF] = {'t', "typedef"}, [SYM_ENUM] = {'e', "enum"}, [SYM_STRUCT] = {'s', "struct"}, [SYM_UNION] = {'u', "union"}, [SYM_ENUM_CONST] = {'E', "enum constant"}, }; static int equal_list(struct string_list *a, struct string_list *b); static void print_list(FILE * f, struct string_list *list); static struct string_list *concat_list(struct string_list *start, ...); static struct string_list *mk_node(const char *string); static void print_location(void); static void print_type_name(enum symbol_type type, const char *name); /*----------------------------------------------------------------------*/ static const unsigned int crctab32[] = { 0x00000000U, 0x77073096U, 0xee0e612cU, 0x990951baU, 0x076dc419U, 0x706af48fU, 0xe963a535U, 0x9e6495a3U, 0x0edb8832U, 0x79dcb8a4U, 0xe0d5e91eU, 0x97d2d988U, 0x09b64c2bU, 0x7eb17cbdU, 0xe7b82d07U, 0x90bf1d91U, 0x1db71064U, 0x6ab020f2U, 0xf3b97148U, 0x84be41deU, 0x1adad47dU, 0x6ddde4ebU, 0xf4d4b551U, 0x83d385c7U, 0x136c9856U, 0x646ba8c0U, 0xfd62f97aU, 0x8a65c9ecU, 0x14015c4fU, 0x63066cd9U, 0xfa0f3d63U, 0x8d080df5U, 0x3b6e20c8U, 0x4c69105eU, 0xd56041e4U, 0xa2677172U, 0x3c03e4d1U, 0x4b04d447U, 0xd20d85fdU, 0xa50ab56bU, 0x35b5a8faU, 0x42b2986cU, 0xdbbbc9d6U, 0xacbcf940U, 0x32d86ce3U, 0x45df5c75U, 0xdcd60dcfU, 0xabd13d59U, 0x26d930acU, 0x51de003aU, 0xc8d75180U, 0xbfd06116U, 0x21b4f4b5U, 0x56b3c423U, 0xcfba9599U, 0xb8bda50fU, 0x2802b89eU, 0x5f058808U, 0xc60cd9b2U, 0xb10be924U, 0x2f6f7c87U, 0x58684c11U, 0xc1611dabU, 0xb6662d3dU, 0x76dc4190U, 0x01db7106U, 0x98d220bcU, 0xefd5102aU, 0x71b18589U, 0x06b6b51fU, 0x9fbfe4a5U, 0xe8b8d433U, 0x7807c9a2U, 0x0f00f934U, 0x9609a88eU, 0xe10e9818U, 0x7f6a0dbbU, 0x086d3d2dU, 0x91646c97U, 0xe6635c01U, 0x6b6b51f4U, 0x1c6c6162U, 0x856530d8U, 0xf262004eU, 0x6c0695edU, 0x1b01a57bU, 0x8208f4c1U, 0xf50fc457U, 0x65b0d9c6U, 0x12b7e950U, 0x8bbeb8eaU, 0xfcb9887cU, 0x62dd1ddfU, 0x15da2d49U, 0x8cd37cf3U, 0xfbd44c65U, 0x4db26158U, 0x3ab551ceU, 0xa3bc0074U, 0xd4bb30e2U, 0x4adfa541U, 0x3dd895d7U, 0xa4d1c46dU, 0xd3d6f4fbU, 0x4369e96aU, 0x346ed9fcU, 0xad678846U, 0xda60b8d0U, 0x44042d73U, 0x33031de5U, 0xaa0a4c5fU, 0xdd0d7cc9U, 0x5005713cU, 0x270241aaU, 0xbe0b1010U, 0xc90c2086U, 0x5768b525U, 0x206f85b3U, 0xb966d409U, 0xce61e49fU, 0x5edef90eU, 0x29d9c998U, 0xb0d09822U, 0xc7d7a8b4U, 0x59b33d17U, 0x2eb40d81U, 0xb7bd5c3bU, 0xc0ba6cadU, 0xedb88320U, 0x9abfb3b6U, 0x03b6e20cU, 0x74b1d29aU, 0xead54739U, 0x9dd277afU, 0x04db2615U, 0x73dc1683U, 0xe3630b12U, 0x94643b84U, 0x0d6d6a3eU, 0x7a6a5aa8U, 0xe40ecf0bU, 0x9309ff9dU, 0x0a00ae27U, 0x7d079eb1U, 0xf00f9344U, 0x8708a3d2U, 0x1e01f268U, 0x6906c2feU, 0xf762575dU, 0x806567cbU, 0x196c3671U, 0x6e6b06e7U, 0xfed41b76U, 0x89d32be0U, 0x10da7a5aU, 0x67dd4accU, 0xf9b9df6fU, 0x8ebeeff9U, 0x17b7be43U, 0x60b08ed5U, 0xd6d6a3e8U, 0xa1d1937eU, 0x38d8c2c4U, 0x4fdff252U, 0xd1bb67f1U, 0xa6bc5767U, 0x3fb506ddU, 0x48b2364bU, 0xd80d2bdaU, 0xaf0a1b4cU, 0x36034af6U, 0x41047a60U, 0xdf60efc3U, 0xa867df55U, 0x316e8eefU, 0x4669be79U, 0xcb61b38cU, 0xbc66831aU, 0x256fd2a0U, 0x5268e236U, 0xcc0c7795U, 0xbb0b4703U, 0x220216b9U, 0x5505262fU, 0xc5ba3bbeU, 0xb2bd0b28U, 0x2bb45a92U, 0x5cb36a04U, 0xc2d7ffa7U, 0xb5d0cf31U, 0x2cd99e8bU, 0x5bdeae1dU, 0x9b64c2b0U, 0xec63f226U, 0x756aa39cU, 0x026d930aU, 0x9c0906a9U, 0xeb0e363fU, 0x72076785U, 0x05005713U, 0x95bf4a82U, 0xe2b87a14U, 0x7bb12baeU, 0x0cb61b38U, 0x92d28e9bU, 0xe5d5be0dU, 0x7cdcefb7U, 0x0bdbdf21U, 0x86d3d2d4U, 0xf1d4e242U, 0x68ddb3f8U, 0x1fda836eU, 0x81be16cdU, 0xf6b9265bU, 0x6fb077e1U, 0x18b74777U, 0x88085ae6U, 0xff0f6a70U, 0x66063bcaU, 0x11010b5cU, 0x8f659effU, 0xf862ae69U, 0x616bffd3U, 0x166ccf45U, 0xa00ae278U, 0xd70dd2eeU, 0x4e048354U, 0x3903b3c2U, 0xa7672661U, 0xd06016f7U, 0x4969474dU, 0x3e6e77dbU, 0xaed16a4aU, 0xd9d65adcU, 0x40df0b66U, 0x37d83bf0U, 0xa9bcae53U, 0xdebb9ec5U, 0x47b2cf7fU, 0x30b5ffe9U, 0xbdbdf21cU, 0xcabac28aU, 0x53b39330U, 0x24b4a3a6U, 0xbad03605U, 0xcdd70693U, 0x54de5729U, 0x23d967bfU, 0xb3667a2eU, 0xc4614ab8U, 0x5d681b02U, 0x2a6f2b94U, 0xb40bbe37U, 0xc30c8ea1U, 0x5a05df1bU, 0x2d02ef8dU }; static unsigned long partial_crc32_one(unsigned char c, unsigned long crc) { return crctab32[(crc ^ c) & 0xff] ^ (crc >> 8); } static unsigned long partial_crc32(const char *s, unsigned long crc) { while (*s) crc = partial_crc32_one(*s++, crc); return crc; } static unsigned long crc32(const char *s) { return partial_crc32(s, 0xffffffff) ^ 0xffffffff; } /*----------------------------------------------------------------------*/ static enum symbol_type map_to_ns(enum symbol_type t) { switch (t) { case SYM_ENUM_CONST: case SYM_NORMAL: case SYM_TYPEDEF: return SYM_NORMAL; case SYM_ENUM: case SYM_STRUCT: case SYM_UNION: return SYM_STRUCT; } return t; } struct symbol *find_symbol(const char *name, enum symbol_type ns, int exact) { unsigned long h = crc32(name) % HASH_BUCKETS; struct symbol *sym; for (sym = symtab[h]; sym; sym = sym->hash_next) if (map_to_ns(sym->type) == map_to_ns(ns) && strcmp(name, sym->name) == 0 && sym->is_declared) break; if (exact && sym && sym->type != ns) return NULL; return sym; } static int is_unknown_symbol(struct symbol *sym) { struct string_list *defn; return ((sym->type == SYM_STRUCT || sym->type == SYM_UNION || sym->type == SYM_ENUM) && (defn = sym->defn) && defn->tag == SYM_NORMAL && strcmp(defn->string, "}") == 0 && (defn = defn->next) && defn->tag == SYM_NORMAL && strcmp(defn->string, "UNKNOWN") == 0 && (defn = defn->next) && defn->tag == SYM_NORMAL && strcmp(defn->string, "{") == 0); } static struct symbol *__add_symbol(const char *name, enum symbol_type type, struct string_list *defn, int is_extern, int is_reference) { unsigned long h; struct symbol *sym; enum symbol_status status = STATUS_UNCHANGED; /* The parser adds symbols in the order their declaration completes, * so it is safe to store the value of the previous enum constant in * a static variable. */ static int enum_counter; static struct string_list *last_enum_expr; if (type == SYM_ENUM_CONST) { if (defn) { free_list(last_enum_expr, NULL); last_enum_expr = copy_list_range(defn, NULL); enum_counter = 1; } else { struct string_list *expr; char buf[20]; snprintf(buf, sizeof(buf), "%d", enum_counter++); if (last_enum_expr) { expr = copy_list_range(last_enum_expr, NULL); defn = concat_list(mk_node("("), expr, mk_node(")"), mk_node("+"), mk_node(buf), NULL); } else { defn = mk_node(buf); } } } else if (type == SYM_ENUM) { free_list(last_enum_expr, NULL); last_enum_expr = NULL; enum_counter = 0; if (!name) /* Anonymous enum definition, nothing more to do */ return NULL; } h = crc32(name) % HASH_BUCKETS; for (sym = symtab[h]; sym; sym = sym->hash_next) { if (map_to_ns(sym->type) == map_to_ns(type) && strcmp(name, sym->name) == 0) { if (is_reference) /* fall through */ ; else if (sym->type == type && equal_list(sym->defn, defn)) { if (!sym->is_declared && sym->is_override) { print_location(); print_type_name(type, name); fprintf(stderr, " modversion is " "unchanged\n"); } sym->is_declared = 1; return sym; } else if (!sym->is_declared) { if (sym->is_override && flag_preserve) { print_location(); fprintf(stderr, "ignoring "); print_type_name(type, name); fprintf(stderr, " modversion change\n"); sym->is_declared = 1; return sym; } else { status = is_unknown_symbol(sym) ? STATUS_DEFINED : STATUS_MODIFIED; } } else { error_with_pos("redefinition of %s", name); return sym; } break; } } if (sym) { struct symbol **psym; for (psym = &symtab[h]; *psym; psym = &(*psym)->hash_next) { if (*psym == sym) { *psym = sym->hash_next; break; } } --nsyms; } sym = xmalloc(sizeof(*sym)); sym->name = name; sym->type = type; sym->defn = defn; sym->expansion_trail = NULL; sym->visited = NULL; sym->is_extern = is_extern; sym->hash_next = symtab[h]; symtab[h] = sym; sym->is_declared = !is_reference; sym->status = status; sym->is_override = 0; if (flag_debug) { if (symbol_types[type].name) fprintf(debugfile, "Defn for %s %s == <", symbol_types[type].name, name); else fprintf(debugfile, "Defn for type%d %s == <", type, name); if (is_extern) fputs("extern ", debugfile); print_list(debugfile, defn); fputs(">\n", debugfile); } ++nsyms; return sym; } struct symbol *add_symbol(const char *name, enum symbol_type type, struct string_list *defn, int is_extern) { return __add_symbol(name, type, defn, is_extern, 0); } static struct symbol *add_reference_symbol(const char *name, enum symbol_type type, struct string_list *defn, int is_extern) { return __add_symbol(name, type, defn, is_extern, 1); } /*----------------------------------------------------------------------*/ void free_node(struct string_list *node) { free(node->string); free(node); } void free_list(struct string_list *s, struct string_list *e) { while (s != e) { struct string_list *next = s->next; free_node(s); s = next; } } static struct string_list *mk_node(const char *string) { struct string_list *newnode; newnode = xmalloc(sizeof(*newnode)); newnode->string = xstrdup(string); newnode->tag = SYM_NORMAL; newnode->next = NULL; return newnode; } static struct string_list *concat_list(struct string_list *start, ...) { va_list ap; struct string_list *n, *n2; if (!start) return NULL; for (va_start(ap, start); (n = va_arg(ap, struct string_list *));) { for (n2 = n; n2->next; n2 = n2->next) ; n2->next = start; start = n; } va_end(ap); return start; } struct string_list *copy_node(struct string_list *node) { struct string_list *newnode; newnode = xmalloc(sizeof(*newnode)); newnode->string = xstrdup(node->string); newnode->tag = node->tag; return newnode; } struct string_list *copy_list_range(struct string_list *start, struct string_list *end) { struct string_list *res, *n; if (start == end) return NULL; n = res = copy_node(start); for (start = start->next; start != end; start = start->next) { n->next = copy_node(start); n = n->next; } n->next = NULL; return res; } static int equal_list(struct string_list *a, struct string_list *b) { while (a && b) { if (a->tag != b->tag || strcmp(a->string, b->string)) return 0; a = a->next; b = b->next; } return !a && !b; } #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) static struct string_list *read_node(FILE *f) { char buffer[256]; struct string_list node = { .string = buffer, .tag = SYM_NORMAL }; int c, in_string = 0; while ((c = fgetc(f)) != EOF) { if (!in_string && c == ' ') { if (node.string == buffer) continue; break; } else if (c == '"') { in_string = !in_string; } else if (c == '\n') { if (node.string == buffer) return NULL; ungetc(c, f); break; } if (node.string >= buffer + sizeof(buffer) - 1) { fprintf(stderr, "Token too long\n"); exit(1); } *node.string++ = c; } if (node.string == buffer) return NULL; *node.string = 0; node.string = buffer; if (node.string[1] == '#') { size_t n; for (n = 0; n < ARRAY_SIZE(symbol_types); n++) { if (node.string[0] == symbol_types[n].n) { node.tag = n; node.string += 2; return copy_node(&node); } } fprintf(stderr, "Unknown type %c\n", node.string[0]); exit(1); } return copy_node(&node); } static void read_reference(FILE *f) { while (!feof(f)) { struct string_list *defn = NULL; struct string_list *sym, *def; int is_extern = 0, is_override = 0; struct symbol *subsym; sym = read_node(f); if (sym && sym->tag == SYM_NORMAL && !strcmp(sym->string, "override")) { is_override = 1; free_node(sym); sym = read_node(f); } if (!sym) continue; def = read_node(f); if (def && def->tag == SYM_NORMAL && !strcmp(def->string, "extern")) { is_extern = 1; free_node(def); def = read_node(f); } while (def) { def->next = defn; defn = def; def = read_node(f); } subsym = add_reference_symbol(xstrdup(sym->string), sym->tag, defn, is_extern); subsym->is_override = is_override; free_node(sym); } } static void print_node(FILE * f, struct string_list *list) { if (symbol_types[list->tag].n) { putc(symbol_types[list->tag].n, f); putc('#', f); } fputs(list->string, f); } static void print_list(FILE * f, struct string_list *list) { struct string_list **e, **b; struct string_list *tmp, **tmp2; int elem = 1; if (list == NULL) { fputs("(nil)", f); return; } tmp = list; while ((tmp = tmp->next) != NULL) elem++; b = alloca(elem * sizeof(*e)); e = b + elem; tmp2 = e - 1; (*tmp2--) = list; while ((list = list->next) != NULL) *(tmp2--) = list; while (b != e) { print_node(f, *b++); putc(' ', f); } } static unsigned long expand_and_crc_sym(struct symbol *sym, unsigned long crc) { struct string_list *list = sym->defn; struct string_list **e, **b; struct string_list *tmp, **tmp2; int elem = 1; if (!list) return crc; tmp = list; while ((tmp = tmp->next) != NULL) elem++; b = alloca(elem * sizeof(*e)); e = b + elem; tmp2 = e - 1; *(tmp2--) = list; while ((list = list->next) != NULL) *(tmp2--) = list; while (b != e) { struct string_list *cur; struct symbol *subsym; cur = *(b++); switch (cur->tag) { case SYM_NORMAL: if (flag_dump_defs) fprintf(debugfile, "%s ", cur->string); crc = partial_crc32(cur->string, crc); crc = partial_crc32_one(' ', crc); break; case SYM_ENUM_CONST: case SYM_TYPEDEF: subsym = find_symbol(cur->string, cur->tag, 0); /* FIXME: Bad reference files can segfault here. */ if (subsym->expansion_trail) { if (flag_dump_defs) fprintf(debugfile, "%s ", cur->string); crc = partial_crc32(cur->string, crc); crc = partial_crc32_one(' ', crc); } else { subsym->expansion_trail = expansion_trail; expansion_trail = subsym; crc = expand_and_crc_sym(subsym, crc); } break; case SYM_STRUCT: case SYM_UNION: case SYM_ENUM: subsym = find_symbol(cur->string, cur->tag, 0); if (!subsym) { struct string_list *n; error_with_pos("expand undefined %s %s", symbol_types[cur->tag].name, cur->string); n = concat_list(mk_node (symbol_types[cur->tag].name), mk_node(cur->string), mk_node("{"), mk_node("UNKNOWN"), mk_node("}"), NULL); subsym = add_symbol(cur->string, cur->tag, n, 0); } if (subsym->expansion_trail) { if (flag_dump_defs) { fprintf(debugfile, "%s %s ", symbol_types[cur->tag].name, cur->string); } crc = partial_crc32(symbol_types[cur->tag].name, crc); crc = partial_crc32_one(' ', crc); crc = partial_crc32(cur->string, crc); crc = partial_crc32_one(' ', crc); } else { subsym->expansion_trail = expansion_trail; expansion_trail = subsym; crc = expand_and_crc_sym(subsym, crc); } break; } } { static struct symbol **end = &visited_symbols; if (!sym->visited) { *end = sym; end = &sym->visited; sym->visited = (struct symbol *)-1L; } } return crc; } void export_symbol(const char *name) { struct symbol *sym; sym = find_symbol(name, SYM_NORMAL, 0); if (!sym) error_with_pos("export undefined symbol %s", name); else { unsigned long crc; int has_changed = 0; if (flag_dump_defs) fprintf(debugfile, "Export %s == <", name); expansion_trail = (struct symbol *)-1L; sym->expansion_trail = expansion_trail; expansion_trail = sym; crc = expand_and_crc_sym(sym, 0xffffffff) ^ 0xffffffff; sym = expansion_trail; while (sym != (struct symbol *)-1L) { struct symbol *n = sym->expansion_trail; if (sym->status != STATUS_UNCHANGED) { if (!has_changed) { print_location(); fprintf(stderr, "%s: %s: modversion " "changed because of changes " "in ", flag_preserve ? "error" : "warning", name); } else fprintf(stderr, ", "); print_type_name(sym->type, sym->name); if (sym->status == STATUS_DEFINED) fprintf(stderr, " (became defined)"); has_changed = 1; if (flag_preserve) errors++; } sym->expansion_trail = 0; sym = n; } if (has_changed) fprintf(stderr, "\n"); if (flag_dump_defs) fputs(">\n", debugfile); printf("#SYMVER %s 0x%08lx\n", name, crc); } } /*----------------------------------------------------------------------*/ static void print_location(void) { fprintf(stderr, "%s:%d: ", cur_filename ? : "<stdin>", cur_line); } static void print_type_name(enum symbol_type type, const char *name) { if (symbol_types[type].name) fprintf(stderr, "%s %s", symbol_types[type].name, name); else fprintf(stderr, "%s", name); } void error_with_pos(const char *fmt, ...) { va_list args; if (flag_warnings) { print_location(); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); putc('\n', stderr); errors++; } } static void genksyms_usage(void) { fputs("Usage:\n" "genksyms [-adDTwqhVR] > /path/to/.tmp_obj.ver\n" "\n" #ifdef __GNU_LIBRARY__ " -s, --symbol-prefix Select symbol prefix\n" " -d, --debug Increment the debug level (repeatable)\n" " -D, --dump Dump expanded symbol defs (for debugging only)\n" " -r, --reference file Read reference symbols from a file\n" " -T, --dump-types file Dump expanded types into file\n" " -p, --preserve Preserve reference modversions or fail\n" " -w, --warnings Enable warnings\n" " -q, --quiet Disable warnings (default)\n" " -h, --help Print this message\n" " -V, --version Print the release version\n" #else /* __GNU_LIBRARY__ */ " -s Select symbol prefix\n" " -d Increment the debug level (repeatable)\n" " -D Dump expanded symbol defs (for debugging only)\n" " -r file Read reference symbols from a file\n" " -T file Dump expanded types into file\n" " -p Preserve reference modversions or fail\n" " -w Enable warnings\n" " -q Disable warnings (default)\n" " -h Print this message\n" " -V Print the release version\n" #endif /* __GNU_LIBRARY__ */ , stderr); } int main(int argc, char **argv) { FILE *dumpfile = NULL, *ref_file = NULL; int o; #ifdef __GNU_LIBRARY__ struct option long_opts[] = { {"debug", 0, 0, 'd'}, {"warnings", 0, 0, 'w'}, {"quiet", 0, 0, 'q'}, {"dump", 0, 0, 'D'}, {"reference", 1, 0, 'r'}, {"dump-types", 1, 0, 'T'}, {"preserve", 0, 0, 'p'}, {"version", 0, 0, 'V'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0} }; while ((o = getopt_long(argc, argv, "s:dwqVDr:T:ph", &long_opts[0], NULL)) != EOF) #else /* __GNU_LIBRARY__ */ while ((o = getopt(argc, argv, "s:dwqVDr:T:ph")) != EOF) #endif /* __GNU_LIBRARY__ */ switch (o) { case 'd': flag_debug++; break; case 'w': flag_warnings = 1; break; case 'q': flag_warnings = 0; break; case 'V': fputs("genksyms version 2.5.60\n", stderr); break; case 'D': flag_dump_defs = 1; break; case 'r': flag_reference = 1; ref_file = fopen(optarg, "r"); if (!ref_file) { perror(optarg); return 1; } break; case 'T': flag_dump_types = 1; dumpfile = fopen(optarg, "w"); if (!dumpfile) { perror(optarg); return 1; } break; case 'p': flag_preserve = 1; break; case 'h': genksyms_usage(); return 0; default: genksyms_usage(); return 1; } { extern int yydebug; extern int yy_flex_debug; yydebug = (flag_debug > 1); yy_flex_debug = (flag_debug > 2); debugfile = stderr; /* setlinebuf(debugfile); */ } if (flag_reference) { read_reference(ref_file); fclose(ref_file); } yyparse(); if (flag_dump_types && visited_symbols) { while (visited_symbols != (struct symbol *)-1L) { struct symbol *sym = visited_symbols; if (sym->is_override) fputs("override ", dumpfile); if (symbol_types[sym->type].n) { putc(symbol_types[sym->type].n, dumpfile); putc('#', dumpfile); } fputs(sym->name, dumpfile); putc(' ', dumpfile); if (sym->is_extern) fputs("extern ", dumpfile); print_list(dumpfile, sym->defn); putc('\n', dumpfile); visited_symbols = sym->visited; sym->visited = NULL; } } if (flag_debug) { fprintf(debugfile, "Hash table occupancy %d/%d = %g\n", nsyms, HASH_BUCKETS, (double)nsyms / (double)HASH_BUCKETS); } if (dumpfile) fclose(dumpfile); return errors != 0; }
linux-master
scripts/genksyms/genksyms.c
// SPDX-License-Identifier: GPL-2.0-only static struct resword { const char *name; int token; } keywords[] = { { "__GENKSYMS_EXPORT_SYMBOL", EXPORT_SYMBOL_KEYW }, { "__asm", ASM_KEYW }, { "__asm__", ASM_KEYW }, { "__attribute", ATTRIBUTE_KEYW }, { "__attribute__", ATTRIBUTE_KEYW }, { "__const", CONST_KEYW }, { "__const__", CONST_KEYW }, { "__extension__", EXTENSION_KEYW }, { "__inline", INLINE_KEYW }, { "__inline__", INLINE_KEYW }, { "__signed", SIGNED_KEYW }, { "__signed__", SIGNED_KEYW }, { "__typeof", TYPEOF_KEYW }, { "__typeof__", TYPEOF_KEYW }, { "__volatile", VOLATILE_KEYW }, { "__volatile__", VOLATILE_KEYW }, { "__builtin_va_list", VA_LIST_KEYW }, { "__int128", BUILTIN_INT_KEYW }, { "__int128_t", BUILTIN_INT_KEYW }, { "__uint128_t", BUILTIN_INT_KEYW }, // According to rth, c99 defines "_Bool", "__restrict", "__restrict__", "restrict". KAO { "_Bool", BOOL_KEYW }, { "__restrict", RESTRICT_KEYW }, { "__restrict__", RESTRICT_KEYW }, { "restrict", RESTRICT_KEYW }, { "asm", ASM_KEYW }, // c11 keywords that can be used at module scope { "_Static_assert", STATIC_ASSERT_KEYW }, // attribute commented out in modutils 2.4.2. People are using 'attribute' as a // field name which breaks the genksyms parser. It is not a gcc keyword anyway. // KAO. }, // { "attribute", ATTRIBUTE_KEYW }, { "auto", AUTO_KEYW }, { "char", CHAR_KEYW }, { "const", CONST_KEYW }, { "double", DOUBLE_KEYW }, { "enum", ENUM_KEYW }, { "extern", EXTERN_KEYW }, { "float", FLOAT_KEYW }, { "inline", INLINE_KEYW }, { "int", INT_KEYW }, { "long", LONG_KEYW }, { "register", REGISTER_KEYW }, { "short", SHORT_KEYW }, { "signed", SIGNED_KEYW }, { "static", STATIC_KEYW }, { "struct", STRUCT_KEYW }, { "typedef", TYPEDEF_KEYW }, { "typeof", TYPEOF_KEYW }, { "union", UNION_KEYW }, { "unsigned", UNSIGNED_KEYW }, { "void", VOID_KEYW }, { "volatile", VOLATILE_KEYW }, }; #define NR_KEYWORDS (sizeof(keywords)/sizeof(struct resword)) static int is_reserved_word(register const char *str, register unsigned int len) { int i; for (i = 0; i < NR_KEYWORDS; i++) { struct resword *r = keywords + i; int l = strlen(r->name); if (len == l && !memcmp(str, r->name, len)) return r->token; } return -1; }
linux-master
scripts/genksyms/keywords.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "lkc.h" /* return true if 'path' exists, false otherwise */ static bool is_present(const char *path) { struct stat st; return !stat(path, &st); } /* return true if 'path' exists and it is a directory, false otherwise */ static bool is_dir(const char *path) { struct stat st; if (stat(path, &st)) return false; return S_ISDIR(st.st_mode); } /* return true if the given two files are the same, false otherwise */ static bool is_same(const char *file1, const char *file2) { int fd1, fd2; struct stat st1, st2; void *map1, *map2; bool ret = false; fd1 = open(file1, O_RDONLY); if (fd1 < 0) return ret; fd2 = open(file2, O_RDONLY); if (fd2 < 0) goto close1; ret = fstat(fd1, &st1); if (ret) goto close2; ret = fstat(fd2, &st2); if (ret) goto close2; if (st1.st_size != st2.st_size) goto close2; map1 = mmap(NULL, st1.st_size, PROT_READ, MAP_PRIVATE, fd1, 0); if (map1 == MAP_FAILED) goto close2; map2 = mmap(NULL, st2.st_size, PROT_READ, MAP_PRIVATE, fd2, 0); if (map2 == MAP_FAILED) goto close2; if (bcmp(map1, map2, st1.st_size)) goto close2; ret = true; close2: close(fd2); close1: close(fd1); return ret; } /* * Create the parent directory of the given path. * * For example, if 'include/config/auto.conf' is given, create 'include/config'. */ static int make_parent_dir(const char *path) { char tmp[PATH_MAX + 1]; char *p; strncpy(tmp, path, sizeof(tmp)); tmp[sizeof(tmp) - 1] = 0; /* Remove the base name. Just return if nothing is left */ p = strrchr(tmp, '/'); if (!p) return 0; *(p + 1) = 0; /* Just in case it is an absolute path */ p = tmp; while (*p == '/') p++; while ((p = strchr(p, '/'))) { *p = 0; /* skip if the directory exists */ if (!is_dir(tmp) && mkdir(tmp, 0755)) return -1; *p = '/'; while (*p == '/') p++; } return 0; } static char depfile_path[PATH_MAX]; static size_t depfile_prefix_len; /* touch depfile for symbol 'name' */ static int conf_touch_dep(const char *name) { int fd; /* check overflow: prefix + name + '\0' must fit in buffer. */ if (depfile_prefix_len + strlen(name) + 1 > sizeof(depfile_path)) return -1; strcpy(depfile_path + depfile_prefix_len, name); fd = open(depfile_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd == -1) return -1; close(fd); return 0; } static void conf_warning(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); static void conf_message(const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); static const char *conf_filename; static int conf_lineno, conf_warnings; static void conf_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s:%d:warning: ", conf_filename, conf_lineno); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); conf_warnings++; } static void conf_default_message_callback(const char *s) { printf("#\n# "); printf("%s", s); printf("\n#\n"); } static void (*conf_message_callback)(const char *s) = conf_default_message_callback; void conf_set_message_callback(void (*fn)(const char *s)) { conf_message_callback = fn; } static void conf_message(const char *fmt, ...) { va_list ap; char buf[4096]; if (!conf_message_callback) return; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); conf_message_callback(buf); va_end(ap); } const char *conf_get_configname(void) { char *name = getenv("KCONFIG_CONFIG"); return name ? name : ".config"; } static const char *conf_get_autoconfig_name(void) { char *name = getenv("KCONFIG_AUTOCONFIG"); return name ? name : "include/config/auto.conf"; } static const char *conf_get_autoheader_name(void) { char *name = getenv("KCONFIG_AUTOHEADER"); return name ? name : "include/generated/autoconf.h"; } static const char *conf_get_rustccfg_name(void) { char *name = getenv("KCONFIG_RUSTCCFG"); return name ? name : "include/generated/rustc_cfg"; } static int conf_set_sym_val(struct symbol *sym, int def, int def_flags, char *p) { char *p2; switch (sym->type) { case S_TRISTATE: if (p[0] == 'm') { sym->def[def].tri = mod; sym->flags |= def_flags; break; } /* fall through */ case S_BOOLEAN: if (p[0] == 'y') { sym->def[def].tri = yes; sym->flags |= def_flags; break; } if (p[0] == 'n') { sym->def[def].tri = no; sym->flags |= def_flags; break; } if (def != S_DEF_AUTO) conf_warning("symbol value '%s' invalid for %s", p, sym->name); return 1; case S_STRING: /* No escaping for S_DEF_AUTO (include/config/auto.conf) */ if (def != S_DEF_AUTO) { if (*p++ != '"') break; for (p2 = p; (p2 = strpbrk(p2, "\"\\")); p2++) { if (*p2 == '"') { *p2 = 0; break; } memmove(p2, p2 + 1, strlen(p2)); } if (!p2) { conf_warning("invalid string found"); return 1; } } /* fall through */ case S_INT: case S_HEX: if (sym_string_valid(sym, p)) { sym->def[def].val = xstrdup(p); sym->flags |= def_flags; } else { if (def != S_DEF_AUTO) conf_warning("symbol value '%s' invalid for %s", p, sym->name); return 1; } break; default: ; } return 0; } #define LINE_GROWTH 16 static int add_byte(int c, char **lineptr, size_t slen, size_t *n) { char *nline; size_t new_size = slen + 1; if (new_size > *n) { new_size += LINE_GROWTH - 1; new_size *= 2; nline = xrealloc(*lineptr, new_size); if (!nline) return -1; *lineptr = nline; *n = new_size; } (*lineptr)[slen] = c; return 0; } static ssize_t compat_getline(char **lineptr, size_t *n, FILE *stream) { char *line = *lineptr; size_t slen = 0; for (;;) { int c = getc(stream); switch (c) { case '\n': if (add_byte(c, &line, slen, n) < 0) goto e_out; slen++; /* fall through */ case EOF: if (add_byte('\0', &line, slen, n) < 0) goto e_out; *lineptr = line; if (slen == 0) return -1; return slen; default: if (add_byte(c, &line, slen, n) < 0) goto e_out; slen++; } } e_out: line[slen-1] = '\0'; *lineptr = line; return -1; } int conf_read_simple(const char *name, int def) { FILE *in = NULL; char *line = NULL; size_t line_asize = 0; char *p, *p2; struct symbol *sym; int i, def_flags; const char *warn_unknown; const char *werror; warn_unknown = getenv("KCONFIG_WARN_UNKNOWN_SYMBOLS"); werror = getenv("KCONFIG_WERROR"); if (name) { in = zconf_fopen(name); } else { char *env; name = conf_get_configname(); in = zconf_fopen(name); if (in) goto load; conf_set_changed(true); env = getenv("KCONFIG_DEFCONFIG_LIST"); if (!env) return 1; while (1) { bool is_last; while (isspace(*env)) env++; if (!*env) break; p = env; while (*p && !isspace(*p)) p++; is_last = (*p == '\0'); *p = '\0'; in = zconf_fopen(env); if (in) { conf_message("using defaults found in %s", env); goto load; } if (is_last) break; env = p + 1; } } if (!in) return 1; load: conf_filename = name; conf_lineno = 0; conf_warnings = 0; def_flags = SYMBOL_DEF << def; for_all_symbols(i, sym) { sym->flags |= SYMBOL_CHANGED; sym->flags &= ~(def_flags|SYMBOL_VALID); if (sym_is_choice(sym)) sym->flags |= def_flags; switch (sym->type) { case S_INT: case S_HEX: case S_STRING: if (sym->def[def].val) free(sym->def[def].val); /* fall through */ default: sym->def[def].val = NULL; sym->def[def].tri = no; } } while (compat_getline(&line, &line_asize, in) != -1) { conf_lineno++; sym = NULL; if (line[0] == '#') { if (memcmp(line + 2, CONFIG_, strlen(CONFIG_))) continue; p = strchr(line + 2 + strlen(CONFIG_), ' '); if (!p) continue; *p++ = 0; if (strncmp(p, "is not set", 10)) continue; if (def == S_DEF_USER) { sym = sym_find(line + 2 + strlen(CONFIG_)); if (!sym) { if (warn_unknown) conf_warning("unknown symbol: %s", line + 2 + strlen(CONFIG_)); conf_set_changed(true); continue; } } else { sym = sym_lookup(line + 2 + strlen(CONFIG_), 0); if (sym->type == S_UNKNOWN) sym->type = S_BOOLEAN; } if (sym->flags & def_flags) { conf_warning("override: reassigning to symbol %s", sym->name); } switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: sym->def[def].tri = no; sym->flags |= def_flags; break; default: ; } } else if (memcmp(line, CONFIG_, strlen(CONFIG_)) == 0) { p = strchr(line + strlen(CONFIG_), '='); if (!p) continue; *p++ = 0; p2 = strchr(p, '\n'); if (p2) { *p2-- = 0; if (*p2 == '\r') *p2 = 0; } sym = sym_find(line + strlen(CONFIG_)); if (!sym) { if (def == S_DEF_AUTO) { /* * Reading from include/config/auto.conf * If CONFIG_FOO previously existed in * auto.conf but it is missing now, * include/config/FOO must be touched. */ conf_touch_dep(line + strlen(CONFIG_)); } else { if (warn_unknown) conf_warning("unknown symbol: %s", line + strlen(CONFIG_)); conf_set_changed(true); } continue; } if (sym->flags & def_flags) { conf_warning("override: reassigning to symbol %s", sym->name); } if (conf_set_sym_val(sym, def, def_flags, p)) continue; } else { if (line[0] != '\r' && line[0] != '\n') conf_warning("unexpected data: %.*s", (int)strcspn(line, "\r\n"), line); continue; } if (sym && sym_is_choice_value(sym)) { struct symbol *cs = prop_get_symbol(sym_get_choice_prop(sym)); switch (sym->def[def].tri) { case no: break; case mod: if (cs->def[def].tri == yes) { conf_warning("%s creates inconsistent choice state", sym->name); cs->flags &= ~def_flags; } break; case yes: if (cs->def[def].tri != no) conf_warning("override: %s changes choice state", sym->name); cs->def[def].val = sym; break; } cs->def[def].tri = EXPR_OR(cs->def[def].tri, sym->def[def].tri); } } free(line); fclose(in); if (conf_warnings && werror) exit(1); return 0; } int conf_read(const char *name) { struct symbol *sym; int conf_unsaved = 0; int i; conf_set_changed(false); if (conf_read_simple(name, S_DEF_USER)) { sym_calc_value(modules_sym); return 1; } sym_calc_value(modules_sym); for_all_symbols(i, sym) { sym_calc_value(sym); if (sym_is_choice(sym) || (sym->flags & SYMBOL_NO_WRITE)) continue; if (sym_has_value(sym) && (sym->flags & SYMBOL_WRITE)) { /* check that calculated value agrees with saved value */ switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: if (sym->def[S_DEF_USER].tri == sym_get_tristate_value(sym)) continue; break; default: if (!strcmp(sym->curr.val, sym->def[S_DEF_USER].val)) continue; break; } } else if (!sym_has_value(sym) && !(sym->flags & SYMBOL_WRITE)) /* no previous value and not saved */ continue; conf_unsaved++; /* maybe print value in verbose mode... */ } for_all_symbols(i, sym) { if (sym_has_value(sym) && !sym_is_choice_value(sym)) { /* Reset values of generates values, so they'll appear * as new, if they should become visible, but that * doesn't quite work if the Kconfig and the saved * configuration disagree. */ if (sym->visible == no && !conf_unsaved) sym->flags &= ~SYMBOL_DEF_USER; switch (sym->type) { case S_STRING: case S_INT: case S_HEX: /* Reset a string value if it's out of range */ if (sym_string_within_range(sym, sym->def[S_DEF_USER].val)) break; sym->flags &= ~(SYMBOL_VALID|SYMBOL_DEF_USER); conf_unsaved++; break; default: break; } } } if (conf_warnings || conf_unsaved) conf_set_changed(true); return 0; } struct comment_style { const char *decoration; const char *prefix; const char *postfix; }; static const struct comment_style comment_style_pound = { .decoration = "#", .prefix = "#", .postfix = "#", }; static const struct comment_style comment_style_c = { .decoration = " *", .prefix = "/*", .postfix = " */", }; static void conf_write_heading(FILE *fp, const struct comment_style *cs) { if (!cs) return; fprintf(fp, "%s\n", cs->prefix); fprintf(fp, "%s Automatically generated file; DO NOT EDIT.\n", cs->decoration); fprintf(fp, "%s %s\n", cs->decoration, rootmenu.prompt->text); fprintf(fp, "%s\n", cs->postfix); } /* The returned pointer must be freed on the caller side */ static char *escape_string_value(const char *in) { const char *p; char *out; size_t len; len = strlen(in) + strlen("\"\"") + 1; p = in; while (1) { p += strcspn(p, "\"\\"); if (p[0] == '\0') break; len++; p++; } out = xmalloc(len); out[0] = '\0'; strcat(out, "\""); p = in; while (1) { len = strcspn(p, "\"\\"); strncat(out, p, len); p += len; if (p[0] == '\0') break; strcat(out, "\\"); strncat(out, p++, 1); } strcat(out, "\""); return out; } enum output_n { OUTPUT_N, OUTPUT_N_AS_UNSET, OUTPUT_N_NONE }; static void __print_symbol(FILE *fp, struct symbol *sym, enum output_n output_n, bool escape_string) { const char *val; char *escaped = NULL; if (sym->type == S_UNKNOWN) return; val = sym_get_string_value(sym); if ((sym->type == S_BOOLEAN || sym->type == S_TRISTATE) && output_n != OUTPUT_N && *val == 'n') { if (output_n == OUTPUT_N_AS_UNSET) fprintf(fp, "# %s%s is not set\n", CONFIG_, sym->name); return; } if (sym->type == S_STRING && escape_string) { escaped = escape_string_value(val); val = escaped; } fprintf(fp, "%s%s=%s\n", CONFIG_, sym->name, val); free(escaped); } static void print_symbol_for_dotconfig(FILE *fp, struct symbol *sym) { __print_symbol(fp, sym, OUTPUT_N_AS_UNSET, true); } static void print_symbol_for_autoconf(FILE *fp, struct symbol *sym) { __print_symbol(fp, sym, OUTPUT_N_NONE, false); } void print_symbol_for_listconfig(struct symbol *sym) { __print_symbol(stdout, sym, OUTPUT_N, true); } static void print_symbol_for_c(FILE *fp, struct symbol *sym) { const char *val; const char *sym_suffix = ""; const char *val_prefix = ""; char *escaped = NULL; if (sym->type == S_UNKNOWN) return; val = sym_get_string_value(sym); switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: switch (*val) { case 'n': return; case 'm': sym_suffix = "_MODULE"; /* fall through */ default: val = "1"; } break; case S_HEX: if (val[0] != '0' || (val[1] != 'x' && val[1] != 'X')) val_prefix = "0x"; break; case S_STRING: escaped = escape_string_value(val); val = escaped; default: break; } fprintf(fp, "#define %s%s%s %s%s\n", CONFIG_, sym->name, sym_suffix, val_prefix, val); free(escaped); } static void print_symbol_for_rustccfg(FILE *fp, struct symbol *sym) { const char *val; const char *val_prefix = ""; char *val_prefixed = NULL; size_t val_prefixed_len; char *escaped = NULL; if (sym->type == S_UNKNOWN) return; val = sym_get_string_value(sym); switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: /* * We do not care about disabled ones, i.e. no need for * what otherwise are "comments" in other printers. */ if (*val == 'n') return; /* * To have similar functionality to the C macro `IS_ENABLED()` * we provide an empty `--cfg CONFIG_X` here in both `y` * and `m` cases. * * Then, the common `fprintf()` below will also give us * a `--cfg CONFIG_X="y"` or `--cfg CONFIG_X="m"`, which can * be used as the equivalent of `IS_BUILTIN()`/`IS_MODULE()`. */ fprintf(fp, "--cfg=%s%s\n", CONFIG_, sym->name); break; case S_HEX: if (val[0] != '0' || (val[1] != 'x' && val[1] != 'X')) val_prefix = "0x"; break; default: break; } if (strlen(val_prefix) > 0) { val_prefixed_len = strlen(val) + strlen(val_prefix) + 1; val_prefixed = xmalloc(val_prefixed_len); snprintf(val_prefixed, val_prefixed_len, "%s%s", val_prefix, val); val = val_prefixed; } /* All values get escaped: the `--cfg` option only takes strings */ escaped = escape_string_value(val); val = escaped; fprintf(fp, "--cfg=%s%s=%s\n", CONFIG_, sym->name, val); free(escaped); free(val_prefixed); } /* * Write out a minimal config. * All values that has default values are skipped as this is redundant. */ int conf_write_defconfig(const char *filename) { struct symbol *sym; struct menu *menu; FILE *out; out = fopen(filename, "w"); if (!out) return 1; sym_clear_all_valid(); /* Traverse all menus to find all relevant symbols */ menu = rootmenu.list; while (menu != NULL) { sym = menu->sym; if (sym == NULL) { if (!menu_is_visible(menu)) goto next_menu; } else if (!sym_is_choice(sym)) { sym_calc_value(sym); if (!(sym->flags & SYMBOL_WRITE)) goto next_menu; sym->flags &= ~SYMBOL_WRITE; /* If we cannot change the symbol - skip */ if (!sym_is_changeable(sym)) goto next_menu; /* If symbol equals to default value - skip */ if (strcmp(sym_get_string_value(sym), sym_get_string_default(sym)) == 0) goto next_menu; /* * If symbol is a choice value and equals to the * default for a choice - skip. * But only if value is bool and equal to "y" and * choice is not "optional". * (If choice is "optional" then all values can be "n") */ if (sym_is_choice_value(sym)) { struct symbol *cs; struct symbol *ds; cs = prop_get_symbol(sym_get_choice_prop(sym)); ds = sym_choice_default(cs); if (!sym_is_optional(cs) && sym == ds) { if ((sym->type == S_BOOLEAN) && sym_get_tristate_value(sym) == yes) goto next_menu; } } print_symbol_for_dotconfig(out, sym); } next_menu: if (menu->list != NULL) { menu = menu->list; } else if (menu->next != NULL) { menu = menu->next; } else { while ((menu = menu->parent)) { if (menu->next != NULL) { menu = menu->next; break; } } } } fclose(out); return 0; } int conf_write(const char *name) { FILE *out; struct symbol *sym; struct menu *menu; const char *str; char tmpname[PATH_MAX + 1], oldname[PATH_MAX + 1]; char *env; int i; bool need_newline = false; if (!name) name = conf_get_configname(); if (!*name) { fprintf(stderr, "config name is empty\n"); return -1; } if (is_dir(name)) { fprintf(stderr, "%s: Is a directory\n", name); return -1; } if (make_parent_dir(name)) return -1; env = getenv("KCONFIG_OVERWRITECONFIG"); if (env && *env) { *tmpname = 0; out = fopen(name, "w"); } else { snprintf(tmpname, sizeof(tmpname), "%s.%d.tmp", name, (int)getpid()); out = fopen(tmpname, "w"); } if (!out) return 1; conf_write_heading(out, &comment_style_pound); if (!conf_get_changed()) sym_clear_all_valid(); menu = rootmenu.list; while (menu) { sym = menu->sym; if (!sym) { if (!menu_is_visible(menu)) goto next; str = menu_get_prompt(menu); fprintf(out, "\n" "#\n" "# %s\n" "#\n", str); need_newline = false; } else if (!(sym->flags & SYMBOL_CHOICE) && !(sym->flags & SYMBOL_WRITTEN)) { sym_calc_value(sym); if (!(sym->flags & SYMBOL_WRITE)) goto next; if (need_newline) { fprintf(out, "\n"); need_newline = false; } sym->flags |= SYMBOL_WRITTEN; print_symbol_for_dotconfig(out, sym); } next: if (menu->list) { menu = menu->list; continue; } end_check: if (!menu->sym && menu_is_visible(menu) && menu != &rootmenu && menu->prompt->type == P_MENU) { fprintf(out, "# end of %s\n", menu_get_prompt(menu)); need_newline = true; } if (menu->next) { menu = menu->next; } else { menu = menu->parent; if (menu) goto end_check; } } fclose(out); for_all_symbols(i, sym) sym->flags &= ~SYMBOL_WRITTEN; if (*tmpname) { if (is_same(name, tmpname)) { conf_message("No change to %s", name); unlink(tmpname); conf_set_changed(false); return 0; } snprintf(oldname, sizeof(oldname), "%s.old", name); rename(name, oldname); if (rename(tmpname, name)) return 1; } conf_message("configuration written to %s", name); conf_set_changed(false); return 0; } /* write a dependency file as used by kbuild to track dependencies */ static int conf_write_autoconf_cmd(const char *autoconf_name) { char name[PATH_MAX], tmp[PATH_MAX]; struct file *file; FILE *out; int ret; ret = snprintf(name, sizeof(name), "%s.cmd", autoconf_name); if (ret >= sizeof(name)) /* check truncation */ return -1; if (make_parent_dir(name)) return -1; ret = snprintf(tmp, sizeof(tmp), "%s.cmd.tmp", autoconf_name); if (ret >= sizeof(tmp)) /* check truncation */ return -1; out = fopen(tmp, "w"); if (!out) { perror("fopen"); return -1; } fprintf(out, "deps_config := \\\n"); for (file = file_list; file; file = file->next) fprintf(out, "\t%s \\\n", file->name); fprintf(out, "\n%s: $(deps_config)\n\n", autoconf_name); env_write_dep(out, autoconf_name); fprintf(out, "\n$(deps_config): ;\n"); fflush(out); ret = ferror(out); /* error check for all fprintf() calls */ fclose(out); if (ret) return -1; if (rename(tmp, name)) { perror("rename"); return -1; } return 0; } static int conf_touch_deps(void) { const char *name, *tmp; struct symbol *sym; int res, i; name = conf_get_autoconfig_name(); tmp = strrchr(name, '/'); depfile_prefix_len = tmp ? tmp - name + 1 : 0; if (depfile_prefix_len + 1 > sizeof(depfile_path)) return -1; strncpy(depfile_path, name, depfile_prefix_len); depfile_path[depfile_prefix_len] = 0; conf_read_simple(name, S_DEF_AUTO); sym_calc_value(modules_sym); for_all_symbols(i, sym) { sym_calc_value(sym); if ((sym->flags & SYMBOL_NO_WRITE) || !sym->name) continue; if (sym->flags & SYMBOL_WRITE) { if (sym->flags & SYMBOL_DEF_AUTO) { /* * symbol has old and new value, * so compare them... */ switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: if (sym_get_tristate_value(sym) == sym->def[S_DEF_AUTO].tri) continue; break; case S_STRING: case S_HEX: case S_INT: if (!strcmp(sym_get_string_value(sym), sym->def[S_DEF_AUTO].val)) continue; break; default: break; } } else { /* * If there is no old value, only 'no' (unset) * is allowed as new value. */ switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: if (sym_get_tristate_value(sym) == no) continue; break; default: break; } } } else if (!(sym->flags & SYMBOL_DEF_AUTO)) /* There is neither an old nor a new value. */ continue; /* else * There is an old value, but no new value ('no' (unset) * isn't saved in auto.conf, so the old value is always * different from 'no'). */ res = conf_touch_dep(sym->name); if (res) return res; } return 0; } static int __conf_write_autoconf(const char *filename, void (*print_symbol)(FILE *, struct symbol *), const struct comment_style *comment_style) { char tmp[PATH_MAX]; FILE *file; struct symbol *sym; int ret, i; if (make_parent_dir(filename)) return -1; ret = snprintf(tmp, sizeof(tmp), "%s.tmp", filename); if (ret >= sizeof(tmp)) /* check truncation */ return -1; file = fopen(tmp, "w"); if (!file) { perror("fopen"); return -1; } conf_write_heading(file, comment_style); for_all_symbols(i, sym) if ((sym->flags & SYMBOL_WRITE) && sym->name) print_symbol(file, sym); fflush(file); /* check possible errors in conf_write_heading() and print_symbol() */ ret = ferror(file); fclose(file); if (ret) return -1; if (rename(tmp, filename)) { perror("rename"); return -1; } return 0; } int conf_write_autoconf(int overwrite) { struct symbol *sym; const char *autoconf_name = conf_get_autoconfig_name(); int ret, i; if (!overwrite && is_present(autoconf_name)) return 0; ret = conf_write_autoconf_cmd(autoconf_name); if (ret) return -1; if (conf_touch_deps()) return 1; for_all_symbols(i, sym) sym_calc_value(sym); ret = __conf_write_autoconf(conf_get_autoheader_name(), print_symbol_for_c, &comment_style_c); if (ret) return ret; ret = __conf_write_autoconf(conf_get_rustccfg_name(), print_symbol_for_rustccfg, NULL); if (ret) return ret; /* * Create include/config/auto.conf. This must be the last step because * Kbuild has a dependency on auto.conf and this marks the successful * completion of the previous steps. */ ret = __conf_write_autoconf(conf_get_autoconfig_name(), print_symbol_for_autoconf, &comment_style_pound); if (ret) return ret; return 0; } static bool conf_changed; static void (*conf_changed_callback)(void); void conf_set_changed(bool val) { bool changed = conf_changed != val; conf_changed = val; if (conf_changed_callback && changed) conf_changed_callback(); } bool conf_get_changed(void) { return conf_changed; } void conf_set_changed_callback(void (*fn)(void)) { conf_changed_callback = fn; } void set_all_choice_values(struct symbol *csym) { struct property *prop; struct symbol *sym; struct expr *e; prop = sym_get_choice_prop(csym); /* * Set all non-assinged choice values to no */ expr_list_for_each_sym(prop->expr, e, sym) { if (!sym_has_value(sym)) sym->def[S_DEF_USER].tri = no; } csym->flags |= SYMBOL_DEF_USER; /* clear VALID to get value calculated */ csym->flags &= ~(SYMBOL_VALID | SYMBOL_NEED_SET_CHOICE_VALUES); }
linux-master
scripts/kconfig/confdata.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002-2005 Roman Zippel <[email protected]> * Copyright (C) 2002-2005 Sam Ravnborg <[email protected]> */ #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "lkc.h" /* file already present in list? If not add it */ struct file *file_lookup(const char *name) { struct file *file; for (file = file_list; file; file = file->next) { if (!strcmp(name, file->name)) { return file; } } file = xmalloc(sizeof(*file)); memset(file, 0, sizeof(*file)); file->name = xstrdup(name); file->next = file_list; file_list = file; return file; } /* Allocate initial growable string */ struct gstr str_new(void) { struct gstr gs; gs.s = xmalloc(sizeof(char) * 64); gs.len = 64; gs.max_width = 0; strcpy(gs.s, "\0"); return gs; } /* Free storage for growable string */ void str_free(struct gstr *gs) { if (gs->s) free(gs->s); gs->s = NULL; gs->len = 0; } /* Append to growable string */ void str_append(struct gstr *gs, const char *s) { size_t l; if (s) { l = strlen(gs->s) + strlen(s) + 1; if (l > gs->len) { gs->s = xrealloc(gs->s, l); gs->len = l; } strcat(gs->s, s); } } /* Append printf formatted string to growable string */ void str_printf(struct gstr *gs, const char *fmt, ...) { va_list ap; char s[10000]; /* big enough... */ va_start(ap, fmt); vsnprintf(s, sizeof(s), fmt, ap); str_append(gs, s); va_end(ap); } /* Retrieve value of growable string */ char *str_get(struct gstr *gs) { return gs->s; } void *xmalloc(size_t size) { void *p = malloc(size); if (p) return p; fprintf(stderr, "Out of memory.\n"); exit(1); } void *xcalloc(size_t nmemb, size_t size) { void *p = calloc(nmemb, size); if (p) return p; fprintf(stderr, "Out of memory.\n"); exit(1); } void *xrealloc(void *p, size_t size) { p = realloc(p, size); if (p) return p; fprintf(stderr, "Out of memory.\n"); exit(1); } char *xstrdup(const char *s) { char *p; p = strdup(s); if (p) return p; fprintf(stderr, "Out of memory.\n"); exit(1); } char *xstrndup(const char *s, size_t n) { char *p; p = strndup(s, n); if (p) return p; fprintf(stderr, "Out of memory.\n"); exit(1); }
linux-master
scripts/kconfig/util.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include <ctype.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "lkc.h" #include "internal.h" static const char nohelp_text[] = "There is no help available for this option."; struct menu rootmenu; static struct menu **last_entry_ptr; struct file *file_list; struct file *current_file; void menu_warn(struct menu *menu, const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s:%d:warning: ", menu->file->name, menu->lineno); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } static void prop_warn(struct property *prop, const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s:%d:warning: ", prop->file->name, prop->lineno); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void _menu_init(void) { current_entry = current_menu = &rootmenu; last_entry_ptr = &rootmenu.list; } void menu_add_entry(struct symbol *sym) { struct menu *menu; menu = xmalloc(sizeof(*menu)); memset(menu, 0, sizeof(*menu)); menu->sym = sym; menu->parent = current_menu; menu->file = current_file; menu->lineno = zconf_lineno(); *last_entry_ptr = menu; last_entry_ptr = &menu->next; current_entry = menu; if (sym) menu_add_symbol(P_SYMBOL, sym, NULL); } struct menu *menu_add_menu(void) { last_entry_ptr = &current_entry->list; current_menu = current_entry; return current_menu; } void menu_end_menu(void) { last_entry_ptr = &current_menu->next; current_menu = current_menu->parent; } /* * Rewrites 'm' to 'm' && MODULES, so that it evaluates to 'n' when running * without modules */ static struct expr *rewrite_m(struct expr *e) { if (!e) return e; switch (e->type) { case E_NOT: e->left.expr = rewrite_m(e->left.expr); break; case E_OR: case E_AND: e->left.expr = rewrite_m(e->left.expr); e->right.expr = rewrite_m(e->right.expr); break; case E_SYMBOL: /* change 'm' into 'm' && MODULES */ if (e->left.sym == &symbol_mod) return expr_alloc_and(e, expr_alloc_symbol(modules_sym)); break; default: break; } return e; } void menu_add_dep(struct expr *dep) { current_entry->dep = expr_alloc_and(current_entry->dep, dep); } void menu_set_type(int type) { struct symbol *sym = current_entry->sym; if (sym->type == type) return; if (sym->type == S_UNKNOWN) { sym->type = type; return; } menu_warn(current_entry, "ignoring type redefinition of '%s' from '%s' to '%s'", sym->name ? sym->name : "<choice>", sym_type_name(sym->type), sym_type_name(type)); } static struct property *menu_add_prop(enum prop_type type, struct expr *expr, struct expr *dep) { struct property *prop; prop = xmalloc(sizeof(*prop)); memset(prop, 0, sizeof(*prop)); prop->type = type; prop->file = current_file; prop->lineno = zconf_lineno(); prop->menu = current_entry; prop->expr = expr; prop->visible.expr = dep; /* append property to the prop list of symbol */ if (current_entry->sym) { struct property **propp; for (propp = &current_entry->sym->prop; *propp; propp = &(*propp)->next) ; *propp = prop; } return prop; } struct property *menu_add_prompt(enum prop_type type, char *prompt, struct expr *dep) { struct property *prop = menu_add_prop(type, NULL, dep); if (isspace(*prompt)) { prop_warn(prop, "leading whitespace ignored"); while (isspace(*prompt)) prompt++; } if (current_entry->prompt) prop_warn(prop, "prompt redefined"); /* Apply all upper menus' visibilities to actual prompts. */ if (type == P_PROMPT) { struct menu *menu = current_entry; while ((menu = menu->parent) != NULL) { struct expr *dup_expr; if (!menu->visibility) continue; /* * Do not add a reference to the menu's visibility * expression but use a copy of it. Otherwise the * expression reduction functions will modify * expressions that have multiple references which * can cause unwanted side effects. */ dup_expr = expr_copy(menu->visibility); prop->visible.expr = expr_alloc_and(prop->visible.expr, dup_expr); } } current_entry->prompt = prop; prop->text = prompt; return prop; } void menu_add_visibility(struct expr *expr) { current_entry->visibility = expr_alloc_and(current_entry->visibility, expr); } void menu_add_expr(enum prop_type type, struct expr *expr, struct expr *dep) { menu_add_prop(type, expr, dep); } void menu_add_symbol(enum prop_type type, struct symbol *sym, struct expr *dep) { menu_add_prop(type, expr_alloc_symbol(sym), dep); } static int menu_validate_number(struct symbol *sym, struct symbol *sym2) { return sym2->type == S_INT || sym2->type == S_HEX || (sym2->type == S_UNKNOWN && sym_string_valid(sym, sym2->name)); } static void sym_check_prop(struct symbol *sym) { struct property *prop; struct symbol *sym2; char *use; for (prop = sym->prop; prop; prop = prop->next) { switch (prop->type) { case P_DEFAULT: if ((sym->type == S_STRING || sym->type == S_INT || sym->type == S_HEX) && prop->expr->type != E_SYMBOL) prop_warn(prop, "default for config symbol '%s'" " must be a single symbol", sym->name); if (prop->expr->type != E_SYMBOL) break; sym2 = prop_get_symbol(prop); if (sym->type == S_HEX || sym->type == S_INT) { if (!menu_validate_number(sym, sym2)) prop_warn(prop, "'%s': number is invalid", sym->name); } if (sym_is_choice(sym)) { struct property *choice_prop = sym_get_choice_prop(sym2); if (!choice_prop || prop_get_symbol(choice_prop) != sym) prop_warn(prop, "choice default symbol '%s' is not contained in the choice", sym2->name); } break; case P_SELECT: case P_IMPLY: use = prop->type == P_SELECT ? "select" : "imply"; sym2 = prop_get_symbol(prop); if (sym->type != S_BOOLEAN && sym->type != S_TRISTATE) prop_warn(prop, "config symbol '%s' uses %s, but is " "not bool or tristate", sym->name, use); else if (sym2->type != S_UNKNOWN && sym2->type != S_BOOLEAN && sym2->type != S_TRISTATE) prop_warn(prop, "'%s' has wrong type. '%s' only " "accept arguments of bool and " "tristate type", sym2->name, use); break; case P_RANGE: if (sym->type != S_INT && sym->type != S_HEX) prop_warn(prop, "range is only allowed " "for int or hex symbols"); if (!menu_validate_number(sym, prop->expr->left.sym) || !menu_validate_number(sym, prop->expr->right.sym)) prop_warn(prop, "range is invalid"); break; default: ; } } } void menu_finalize(struct menu *parent) { struct menu *menu, *last_menu; struct symbol *sym; struct property *prop; struct expr *parentdep, *basedep, *dep, *dep2, **ep; sym = parent->sym; if (parent->list) { /* * This menu node has children. We (recursively) process them * and propagate parent dependencies before moving on. */ if (sym && sym_is_choice(sym)) { if (sym->type == S_UNKNOWN) { /* find the first choice value to find out choice type */ current_entry = parent; for (menu = parent->list; menu; menu = menu->next) { if (menu->sym && menu->sym->type != S_UNKNOWN) { menu_set_type(menu->sym->type); break; } } } /* set the type of the remaining choice values */ for (menu = parent->list; menu; menu = menu->next) { current_entry = menu; if (menu->sym && menu->sym->type == S_UNKNOWN) menu_set_type(sym->type); } /* * Use the choice itself as the parent dependency of * the contained items. This turns the mode of the * choice into an upper bound on the visibility of the * choice value symbols. */ parentdep = expr_alloc_symbol(sym); } else { /* Menu node for 'menu', 'if' */ parentdep = parent->dep; } /* For each child menu node... */ for (menu = parent->list; menu; menu = menu->next) { /* * Propagate parent dependencies to the child menu * node, also rewriting and simplifying expressions */ basedep = rewrite_m(menu->dep); basedep = expr_transform(basedep); basedep = expr_alloc_and(expr_copy(parentdep), basedep); basedep = expr_eliminate_dups(basedep); menu->dep = basedep; if (menu->sym) /* * Note: For symbols, all prompts are included * too in the symbol's own property list */ prop = menu->sym->prop; else /* * For non-symbol menu nodes, we just need to * handle the prompt */ prop = menu->prompt; /* For each property... */ for (; prop; prop = prop->next) { if (prop->menu != menu) /* * Two possibilities: * * 1. The property lacks dependencies * and so isn't location-specific, * e.g. an 'option' * * 2. The property belongs to a symbol * defined in multiple locations and * is from some other location. It * will be handled there in that * case. * * Skip the property. */ continue; /* * Propagate parent dependencies to the * property's condition, rewriting and * simplifying expressions at the same time */ dep = rewrite_m(prop->visible.expr); dep = expr_transform(dep); dep = expr_alloc_and(expr_copy(basedep), dep); dep = expr_eliminate_dups(dep); if (menu->sym && menu->sym->type != S_TRISTATE) dep = expr_trans_bool(dep); prop->visible.expr = dep; /* * Handle selects and implies, which modify the * dependencies of the selected/implied symbol */ if (prop->type == P_SELECT) { struct symbol *es = prop_get_symbol(prop); es->rev_dep.expr = expr_alloc_or(es->rev_dep.expr, expr_alloc_and(expr_alloc_symbol(menu->sym), expr_copy(dep))); } else if (prop->type == P_IMPLY) { struct symbol *es = prop_get_symbol(prop); es->implied.expr = expr_alloc_or(es->implied.expr, expr_alloc_and(expr_alloc_symbol(menu->sym), expr_copy(dep))); } } } if (sym && sym_is_choice(sym)) expr_free(parentdep); /* * Recursively process children in the same fashion before * moving on */ for (menu = parent->list; menu; menu = menu->next) menu_finalize(menu); } else if (sym) { /* * Automatic submenu creation. If sym is a symbol and A, B, C, * ... are consecutive items (symbols, menus, ifs, etc.) that * all depend on sym, then the following menu structure is * created: * * sym * +-A * +-B * +-C * ... * * This also works recursively, giving the following structure * if A is a symbol and B depends on A: * * sym * +-A * | +-B * +-C * ... */ basedep = parent->prompt ? parent->prompt->visible.expr : NULL; basedep = expr_trans_compare(basedep, E_UNEQUAL, &symbol_no); basedep = expr_eliminate_dups(expr_transform(basedep)); /* Examine consecutive elements after sym */ last_menu = NULL; for (menu = parent->next; menu; menu = menu->next) { dep = menu->prompt ? menu->prompt->visible.expr : menu->dep; if (!expr_contains_symbol(dep, sym)) /* No dependency, quit */ break; if (expr_depends_symbol(dep, sym)) /* Absolute dependency, put in submenu */ goto next; /* * Also consider it a dependency on sym if our * dependencies contain sym and are a "superset" of * sym's dependencies, e.g. '(sym || Q) && R' when sym * depends on R. * * Note that 'R' might be from an enclosing menu or if, * making this a more common case than it might seem. */ dep = expr_trans_compare(dep, E_UNEQUAL, &symbol_no); dep = expr_eliminate_dups(expr_transform(dep)); dep2 = expr_copy(basedep); expr_eliminate_eq(&dep, &dep2); expr_free(dep); if (!expr_is_yes(dep2)) { /* Not superset, quit */ expr_free(dep2); break; } /* Superset, put in submenu */ expr_free(dep2); next: menu_finalize(menu); menu->parent = parent; last_menu = menu; } expr_free(basedep); if (last_menu) { parent->list = parent->next; parent->next = last_menu->next; last_menu->next = NULL; } sym->dir_dep.expr = expr_alloc_or(sym->dir_dep.expr, parent->dep); } for (menu = parent->list; menu; menu = menu->next) { if (sym && sym_is_choice(sym) && menu->sym && !sym_is_choice_value(menu->sym)) { current_entry = menu; menu->sym->flags |= SYMBOL_CHOICEVAL; if (!menu->prompt) menu_warn(menu, "choice value must have a prompt"); for (prop = menu->sym->prop; prop; prop = prop->next) { if (prop->type == P_DEFAULT) prop_warn(prop, "defaults for choice " "values not supported"); if (prop->menu == menu) continue; if (prop->type == P_PROMPT && prop->menu->parent->sym != sym) prop_warn(prop, "choice value used outside its choice group"); } /* Non-tristate choice values of tristate choices must * depend on the choice being set to Y. The choice * values' dependencies were propagated to their * properties above, so the change here must be re- * propagated. */ if (sym->type == S_TRISTATE && menu->sym->type != S_TRISTATE) { basedep = expr_alloc_comp(E_EQUAL, sym, &symbol_yes); menu->dep = expr_alloc_and(basedep, menu->dep); for (prop = menu->sym->prop; prop; prop = prop->next) { if (prop->menu != menu) continue; prop->visible.expr = expr_alloc_and(expr_copy(basedep), prop->visible.expr); } } menu_add_symbol(P_CHOICE, sym, NULL); prop = sym_get_choice_prop(sym); for (ep = &prop->expr; *ep; ep = &(*ep)->left.expr) ; *ep = expr_alloc_one(E_LIST, NULL); (*ep)->right.sym = menu->sym; } /* * This code serves two purposes: * * (1) Flattening 'if' blocks, which do not specify a submenu * and only add dependencies. * * (Automatic submenu creation might still create a submenu * from an 'if' before this code runs.) * * (2) "Undoing" any automatic submenus created earlier below * promptless symbols. * * Before: * * A * if ... (or promptless symbol) * +-B * +-C * D * * After: * * A * if ... (or promptless symbol) * B * C * D */ if (menu->list && (!menu->prompt || !menu->prompt->text)) { for (last_menu = menu->list; ; last_menu = last_menu->next) { last_menu->parent = parent; if (!last_menu->next) break; } last_menu->next = menu->next; menu->next = menu->list; menu->list = NULL; } } if (sym && !(sym->flags & SYMBOL_WARNED)) { if (sym->type == S_UNKNOWN) menu_warn(parent, "config symbol defined without type"); if (sym_is_choice(sym) && !parent->prompt) menu_warn(parent, "choice must have a prompt"); /* Check properties connected to this symbol */ sym_check_prop(sym); sym->flags |= SYMBOL_WARNED; } /* * For non-optional choices, add a reverse dependency (corresponding to * a select) of '<visibility> && m'. This prevents the user from * setting the choice mode to 'n' when the choice is visible. * * This would also work for non-choice symbols, but only non-optional * choices clear SYMBOL_OPTIONAL as of writing. Choices are implemented * as a type of symbol. */ if (sym && !sym_is_optional(sym) && parent->prompt) { sym->rev_dep.expr = expr_alloc_or(sym->rev_dep.expr, expr_alloc_and(parent->prompt->visible.expr, expr_alloc_symbol(&symbol_mod))); } } bool menu_has_prompt(struct menu *menu) { if (!menu->prompt) return false; return true; } /* * Determine if a menu is empty. * A menu is considered empty if it contains no or only * invisible entries. */ bool menu_is_empty(struct menu *menu) { struct menu *child; for (child = menu->list; child; child = child->next) { if (menu_is_visible(child)) return(false); } return(true); } bool menu_is_visible(struct menu *menu) { struct menu *child; struct symbol *sym; tristate visible; if (!menu->prompt) return false; if (menu->visibility) { if (expr_calc_value(menu->visibility) == no) return false; } sym = menu->sym; if (sym) { sym_calc_value(sym); visible = menu->prompt->visible.tri; } else visible = menu->prompt->visible.tri = expr_calc_value(menu->prompt->visible.expr); if (visible != no) return true; if (!sym || sym_get_tristate_value(menu->sym) == no) return false; for (child = menu->list; child; child = child->next) { if (menu_is_visible(child)) { if (sym) sym->flags |= SYMBOL_DEF_USER; return true; } } return false; } const char *menu_get_prompt(struct menu *menu) { if (menu->prompt) return menu->prompt->text; else if (menu->sym) return menu->sym->name; return NULL; } struct menu *menu_get_parent_menu(struct menu *menu) { enum prop_type type; for (; menu != &rootmenu; menu = menu->parent) { type = menu->prompt ? menu->prompt->type : 0; if (type == P_MENU) break; } return menu; } bool menu_has_help(struct menu *menu) { return menu->help != NULL; } const char *menu_get_help(struct menu *menu) { if (menu->help) return menu->help; else return ""; } static void get_def_str(struct gstr *r, struct menu *menu) { str_printf(r, "Defined at %s:%d\n", menu->file->name, menu->lineno); } static void get_dep_str(struct gstr *r, struct expr *expr, const char *prefix) { if (!expr_is_yes(expr)) { str_append(r, prefix); expr_gstr_print(expr, r); str_append(r, "\n"); } } int __attribute__((weak)) get_jump_key_char(void) { return -1; } static void get_prompt_str(struct gstr *r, struct property *prop, struct list_head *head) { int i, j; struct menu *submenu[8], *menu, *location = NULL; struct jump_key *jump = NULL; str_printf(r, " Prompt: %s\n", prop->text); get_dep_str(r, prop->menu->dep, " Depends on: "); /* * Most prompts in Linux have visibility that exactly matches their * dependencies. For these, we print only the dependencies to improve * readability. However, prompts with inline "if" expressions and * prompts with a parent that has a "visible if" expression have * differing dependencies and visibility. In these rare cases, we * print both. */ if (!expr_eq(prop->menu->dep, prop->visible.expr)) get_dep_str(r, prop->visible.expr, " Visible if: "); menu = prop->menu; for (i = 0; menu != &rootmenu && i < 8; menu = menu->parent) { submenu[i++] = menu; if (location == NULL && menu_is_visible(menu)) location = menu; } if (head && location) { jump = xmalloc(sizeof(struct jump_key)); jump->target = location; list_add_tail(&jump->entries, head); } str_printf(r, " Location:\n"); for (j = 0; --i >= 0; j++) { int jk = -1; int indent = 2 * j + 4; menu = submenu[i]; if (jump && menu == location) { jump->offset = strlen(r->s); jk = get_jump_key_char(); } if (jk >= 0) { str_printf(r, "(%c)", jk); indent -= 3; } str_printf(r, "%*c-> %s", indent, ' ', menu_get_prompt(menu)); if (menu->sym) { str_printf(r, " (%s [=%s])", menu->sym->name ? menu->sym->name : "<choice>", sym_get_string_value(menu->sym)); } str_append(r, "\n"); } } static void get_symbol_props_str(struct gstr *r, struct symbol *sym, enum prop_type tok, const char *prefix) { bool hit = false; struct property *prop; for_all_properties(sym, prop, tok) { if (!hit) { str_append(r, prefix); hit = true; } else str_printf(r, " && "); expr_gstr_print(prop->expr, r); } if (hit) str_append(r, "\n"); } /* * head is optional and may be NULL */ static void get_symbol_str(struct gstr *r, struct symbol *sym, struct list_head *head) { struct property *prop; if (sym && sym->name) { str_printf(r, "Symbol: %s [=%s]\n", sym->name, sym_get_string_value(sym)); str_printf(r, "Type : %s\n", sym_type_name(sym->type)); if (sym->type == S_INT || sym->type == S_HEX) { prop = sym_get_range_prop(sym); if (prop) { str_printf(r, "Range : "); expr_gstr_print(prop->expr, r); str_append(r, "\n"); } } } /* Print the definitions with prompts before the ones without */ for_all_properties(sym, prop, P_SYMBOL) { if (prop->menu->prompt) { get_def_str(r, prop->menu); get_prompt_str(r, prop->menu->prompt, head); } } for_all_properties(sym, prop, P_SYMBOL) { if (!prop->menu->prompt) { get_def_str(r, prop->menu); get_dep_str(r, prop->menu->dep, " Depends on: "); } } get_symbol_props_str(r, sym, P_SELECT, "Selects: "); if (sym->rev_dep.expr) { expr_gstr_print_revdep(sym->rev_dep.expr, r, yes, "Selected by [y]:\n"); expr_gstr_print_revdep(sym->rev_dep.expr, r, mod, "Selected by [m]:\n"); expr_gstr_print_revdep(sym->rev_dep.expr, r, no, "Selected by [n]:\n"); } get_symbol_props_str(r, sym, P_IMPLY, "Implies: "); if (sym->implied.expr) { expr_gstr_print_revdep(sym->implied.expr, r, yes, "Implied by [y]:\n"); expr_gstr_print_revdep(sym->implied.expr, r, mod, "Implied by [m]:\n"); expr_gstr_print_revdep(sym->implied.expr, r, no, "Implied by [n]:\n"); } str_append(r, "\n\n"); } struct gstr get_relations_str(struct symbol **sym_arr, struct list_head *head) { struct symbol *sym; struct gstr res = str_new(); int i; for (i = 0; sym_arr && (sym = sym_arr[i]); i++) get_symbol_str(&res, sym, head); if (!i) str_append(&res, "No matches found.\n"); return res; } void menu_get_ext_help(struct menu *menu, struct gstr *help) { struct symbol *sym = menu->sym; const char *help_text = nohelp_text; if (menu_has_help(menu)) { if (sym->name) str_printf(help, "%s%s:\n\n", CONFIG_, sym->name); help_text = menu_get_help(menu); } str_printf(help, "%s\n", help_text); if (sym) get_symbol_str(help, sym, NULL); }
linux-master
scripts/kconfig/menu.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include "images.h" const char * const xpm_load[] = { "22 22 5 1", ". c None", "# c #000000", "c c #838100", "a c #ffff00", "b c #ffffff", "......................", "......................", "......................", "............####....#.", "...........#....##.##.", "..................###.", ".................####.", ".####...........#####.", "#abab##########.......", "#babababababab#.......", "#ababababababa#.......", "#babababababab#.......", "#ababab###############", "#babab##cccccccccccc##", "#abab##cccccccccccc##.", "#bab##cccccccccccc##..", "#ab##cccccccccccc##...", "#b##cccccccccccc##....", "###cccccccccccc##.....", "##cccccccccccc##......", "###############.......", "......................"}; const char * const xpm_save[] = { "22 22 5 1", ". c None", "# c #000000", "a c #838100", "b c #c5c2c5", "c c #cdb6d5", "......................", ".####################.", ".#aa#bbbbbbbbbbbb#bb#.", ".#aa#bbbbbbbbbbbb#bb#.", ".#aa#bbbbbbbbbcbb####.", ".#aa#bbbccbbbbbbb#aa#.", ".#aa#bbbccbbbbbbb#aa#.", ".#aa#bbbbbbbbbbbb#aa#.", ".#aa#bbbbbbbbbbbb#aa#.", ".#aa#bbbbbbbbbbbb#aa#.", ".#aa#bbbbbbbbbbbb#aa#.", ".#aaa############aaa#.", ".#aaaaaaaaaaaaaaaaaa#.", ".#aaaaaaaaaaaaaaaaaa#.", ".#aaa#############aa#.", ".#aaa#########bbb#aa#.", ".#aaa#########bbb#aa#.", ".#aaa#########bbb#aa#.", ".#aaa#########bbb#aa#.", ".#aaa#########bbb#aa#.", "..##################..", "......................"}; const char * const xpm_back[] = { "22 22 3 1", ". c None", "# c #000083", "a c #838183", "......................", "......................", "......................", "......................", "......................", "...........######a....", "..#......##########...", "..##...####......##a..", "..###.###.........##..", "..######..........##..", "..#####...........##..", "..######..........##..", "..#######.........##..", "..########.......##a..", "...............a###...", "...............###....", "......................", "......................", "......................", "......................", "......................", "......................"}; const char * const xpm_tree_view[] = { "22 22 2 1", ". c None", "# c #000000", "......................", "......................", "......#...............", "......#...............", "......#...............", "......#...............", "......#...............", "......########........", "......#...............", "......#...............", "......#...............", "......#...............", "......#...............", "......########........", "......#...............", "......#...............", "......#...............", "......#...............", "......#...............", "......########........", "......................", "......................"}; const char * const xpm_single_view[] = { "22 22 2 1", ". c None", "# c #000000", "......................", "......................", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "..........#...........", "......................", "......................"}; const char * const xpm_split_view[] = { "22 22 2 1", ". c None", "# c #000000", "......................", "......................", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......#......#........", "......................", "......................"}; const char * const xpm_symbol_no[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " . . ", " . . ", " . . ", " . . ", " . . ", " . . ", " . . ", " . . ", " .......... ", " "}; const char * const xpm_symbol_mod[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " . . ", " . . ", " . .. . ", " . .... . ", " . .... . ", " . .. . ", " . . ", " . . ", " .......... ", " "}; const char * const xpm_symbol_yes[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " . . ", " . . ", " . . . ", " . .. . ", " . . .. . ", " . .... . ", " . .. . ", " . . ", " .......... ", " "}; const char * const xpm_choice_no[] = { "12 12 2 1", " c white", ". c black", " ", " .... ", " .. .. ", " . . ", " . . ", " . . ", " . . ", " . . ", " . . ", " .. .. ", " .... ", " "}; const char * const xpm_choice_yes[] = { "12 12 2 1", " c white", ". c black", " ", " .... ", " .. .. ", " . . ", " . .. . ", " . .... . ", " . .... . ", " . .. . ", " . . ", " .. .. ", " .... ", " "}; const char * const xpm_menu[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " . . ", " . .. . ", " . .... . ", " . ...... . ", " . ...... . ", " . .... . ", " . .. . ", " . . ", " .......... ", " "}; const char * const xpm_menu_inv[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " .......... ", " .. ...... ", " .. .... ", " .. .. ", " .. .. ", " .. .... ", " .. ...... ", " .......... ", " .......... ", " "}; const char * const xpm_menuback[] = { "12 12 2 1", " c white", ". c black", " ", " .......... ", " . . ", " . .. . ", " . .... . ", " . ...... . ", " . ...... . ", " . .... . ", " . .. . ", " . . ", " .......... ", " "}; const char * const xpm_void[] = { "12 12 2 1", " c white", ". c black", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
linux-master
scripts/kconfig/images.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002-2003 Romain Lievin <[email protected]> */ #include <stdlib.h> #include "lkc.h" #include "images.h" #include <glade/glade.h> #include <gtk/gtk.h> #include <glib.h> #include <gdk/gdkkeysyms.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <time.h> //#define DEBUG enum { SINGLE_VIEW, SPLIT_VIEW, FULL_VIEW }; enum { OPT_NORMAL, OPT_ALL, OPT_PROMPT }; static gint view_mode = FULL_VIEW; static gboolean show_name = TRUE; static gboolean show_range = TRUE; static gboolean show_value = TRUE; static gboolean resizeable = FALSE; static int opt_mode = OPT_NORMAL; GtkWidget *main_wnd = NULL; GtkWidget *tree1_w = NULL; // left frame GtkWidget *tree2_w = NULL; // right frame GtkWidget *text_w = NULL; GtkWidget *hpaned = NULL; GtkWidget *vpaned = NULL; GtkWidget *back_btn = NULL; GtkWidget *save_btn = NULL; GtkWidget *save_menu_item = NULL; GtkTextTag *tag1, *tag2; GdkColor color; GtkTreeStore *tree1, *tree2, *tree; GtkTreeModel *model1, *model2; static GtkTreeIter *parents[256]; static gint indent; static struct menu *current; // current node for SINGLE view static struct menu *browsed; // browsed node for SPLIT view enum { COL_OPTION, COL_NAME, COL_NO, COL_MOD, COL_YES, COL_VALUE, COL_MENU, COL_COLOR, COL_EDIT, COL_PIXBUF, COL_PIXVIS, COL_BTNVIS, COL_BTNACT, COL_BTNINC, COL_BTNRAD, COL_NUMBER }; static void display_list(void); static void display_tree(struct menu *menu); static void display_tree_part(void); static void update_tree(struct menu *src, GtkTreeIter * dst); static void set_node(GtkTreeIter * node, struct menu *menu, gchar ** row); static gchar **fill_row(struct menu *menu); static void conf_changed(void); /* Helping/Debugging Functions */ #ifdef DEBUG static const char *dbg_sym_flags(int val) { static char buf[256]; bzero(buf, 256); if (val & SYMBOL_CONST) strcat(buf, "const/"); if (val & SYMBOL_CHECK) strcat(buf, "check/"); if (val & SYMBOL_CHOICE) strcat(buf, "choice/"); if (val & SYMBOL_CHOICEVAL) strcat(buf, "choiceval/"); if (val & SYMBOL_VALID) strcat(buf, "valid/"); if (val & SYMBOL_OPTIONAL) strcat(buf, "optional/"); if (val & SYMBOL_WRITE) strcat(buf, "write/"); if (val & SYMBOL_CHANGED) strcat(buf, "changed/"); if (val & SYMBOL_NO_WRITE) strcat(buf, "no_write/"); buf[strlen(buf) - 1] = '\0'; return buf; } #endif static void replace_button_icon(GladeXML *xml, GdkDrawable *window, GtkStyle *style, gchar *btn_name, gchar **xpm) { GdkPixmap *pixmap; GdkBitmap *mask; GtkToolButton *button; GtkWidget *image; pixmap = gdk_pixmap_create_from_xpm_d(window, &mask, &style->bg[GTK_STATE_NORMAL], xpm); button = GTK_TOOL_BUTTON(glade_xml_get_widget(xml, btn_name)); image = gtk_image_new_from_pixmap(pixmap, mask); gtk_widget_show(image); gtk_tool_button_set_icon_widget(button, image); } /* Main Window Initialization */ static void init_main_window(const gchar *glade_file) { GladeXML *xml; GtkWidget *widget; GtkTextBuffer *txtbuf; GtkStyle *style; xml = glade_xml_new(glade_file, "window1", NULL); if (!xml) g_error("GUI loading failed !\n"); glade_xml_signal_autoconnect(xml); main_wnd = glade_xml_get_widget(xml, "window1"); hpaned = glade_xml_get_widget(xml, "hpaned1"); vpaned = glade_xml_get_widget(xml, "vpaned1"); tree1_w = glade_xml_get_widget(xml, "treeview1"); tree2_w = glade_xml_get_widget(xml, "treeview2"); text_w = glade_xml_get_widget(xml, "textview3"); back_btn = glade_xml_get_widget(xml, "button1"); gtk_widget_set_sensitive(back_btn, FALSE); widget = glade_xml_get_widget(xml, "show_name1"); gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget, show_name); widget = glade_xml_get_widget(xml, "show_range1"); gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget, show_range); widget = glade_xml_get_widget(xml, "show_data1"); gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget, show_value); save_btn = glade_xml_get_widget(xml, "button3"); save_menu_item = glade_xml_get_widget(xml, "save1"); conf_set_changed_callback(conf_changed); style = gtk_widget_get_style(main_wnd); widget = glade_xml_get_widget(xml, "toolbar1"); replace_button_icon(xml, main_wnd->window, style, "button4", (gchar **) xpm_single_view); replace_button_icon(xml, main_wnd->window, style, "button5", (gchar **) xpm_split_view); replace_button_icon(xml, main_wnd->window, style, "button6", (gchar **) xpm_tree_view); txtbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w)); tag1 = gtk_text_buffer_create_tag(txtbuf, "mytag1", "foreground", "red", "weight", PANGO_WEIGHT_BOLD, NULL); tag2 = gtk_text_buffer_create_tag(txtbuf, "mytag2", /*"style", PANGO_STYLE_OBLIQUE, */ NULL); gtk_window_set_title(GTK_WINDOW(main_wnd), rootmenu.prompt->text); gtk_widget_show(main_wnd); } static void init_tree_model(void) { gint i; tree = tree2 = gtk_tree_store_new(COL_NUMBER, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, GDK_TYPE_COLOR, G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); model2 = GTK_TREE_MODEL(tree2); for (parents[0] = NULL, i = 1; i < 256; i++) parents[i] = (GtkTreeIter *) g_malloc(sizeof(GtkTreeIter)); tree1 = gtk_tree_store_new(COL_NUMBER, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, GDK_TYPE_COLOR, G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); model1 = GTK_TREE_MODEL(tree1); } static void init_left_tree(void) { GtkTreeView *view = GTK_TREE_VIEW(tree1_w); GtkCellRenderer *renderer; GtkTreeSelection *sel; GtkTreeViewColumn *column; gtk_tree_view_set_model(view, model1); gtk_tree_view_set_headers_visible(view, TRUE); gtk_tree_view_set_rules_hint(view, TRUE); column = gtk_tree_view_column_new(); gtk_tree_view_append_column(view, column); gtk_tree_view_column_set_title(column, "Options"); renderer = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, FALSE); gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "active", COL_BTNACT, "inconsistent", COL_BTNINC, "visible", COL_BTNVIS, "radio", COL_BTNRAD, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, FALSE); gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "text", COL_OPTION, "foreground-gdk", COL_COLOR, NULL); sel = gtk_tree_view_get_selection(view); gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE); gtk_widget_realize(tree1_w); } static void renderer_edited(GtkCellRendererText * cell, const gchar * path_string, const gchar * new_text, gpointer user_data); static void init_right_tree(void) { GtkTreeView *view = GTK_TREE_VIEW(tree2_w); GtkCellRenderer *renderer; GtkTreeSelection *sel; GtkTreeViewColumn *column; gint i; gtk_tree_view_set_model(view, model2); gtk_tree_view_set_headers_visible(view, TRUE); gtk_tree_view_set_rules_hint(view, TRUE); column = gtk_tree_view_column_new(); gtk_tree_view_append_column(view, column); gtk_tree_view_column_set_title(column, "Options"); renderer = gtk_cell_renderer_pixbuf_new(); gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, FALSE); gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "pixbuf", COL_PIXBUF, "visible", COL_PIXVIS, NULL); renderer = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, FALSE); gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "active", COL_BTNACT, "inconsistent", COL_BTNINC, "visible", COL_BTNVIS, "radio", COL_BTNRAD, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, FALSE); gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "text", COL_OPTION, "foreground-gdk", COL_COLOR, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_attributes(view, -1, "Name", renderer, "text", COL_NAME, "foreground-gdk", COL_COLOR, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_attributes(view, -1, "N", renderer, "text", COL_NO, "foreground-gdk", COL_COLOR, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_attributes(view, -1, "M", renderer, "text", COL_MOD, "foreground-gdk", COL_COLOR, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_attributes(view, -1, "Y", renderer, "text", COL_YES, "foreground-gdk", COL_COLOR, NULL); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_insert_column_with_attributes(view, -1, "Value", renderer, "text", COL_VALUE, "editable", COL_EDIT, "foreground-gdk", COL_COLOR, NULL); g_signal_connect(G_OBJECT(renderer), "edited", G_CALLBACK(renderer_edited), NULL); column = gtk_tree_view_get_column(view, COL_NAME); gtk_tree_view_column_set_visible(column, show_name); column = gtk_tree_view_get_column(view, COL_NO); gtk_tree_view_column_set_visible(column, show_range); column = gtk_tree_view_get_column(view, COL_MOD); gtk_tree_view_column_set_visible(column, show_range); column = gtk_tree_view_get_column(view, COL_YES); gtk_tree_view_column_set_visible(column, show_range); column = gtk_tree_view_get_column(view, COL_VALUE); gtk_tree_view_column_set_visible(column, show_value); if (resizeable) { for (i = 0; i < COL_VALUE; i++) { column = gtk_tree_view_get_column(view, i); gtk_tree_view_column_set_resizable(column, TRUE); } } sel = gtk_tree_view_get_selection(view); gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE); } /* Utility Functions */ static void text_insert_help(struct menu *menu) { GtkTextBuffer *buffer; GtkTextIter start, end; const char *prompt = menu_get_prompt(menu); struct gstr help = str_new(); menu_get_ext_help(menu, &help); buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w)); gtk_text_buffer_get_bounds(buffer, &start, &end); gtk_text_buffer_delete(buffer, &start, &end); gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_w), 15); gtk_text_buffer_get_end_iter(buffer, &end); gtk_text_buffer_insert_with_tags(buffer, &end, prompt, -1, tag1, NULL); gtk_text_buffer_insert_at_cursor(buffer, "\n\n", 2); gtk_text_buffer_get_end_iter(buffer, &end); gtk_text_buffer_insert_with_tags(buffer, &end, str_get(&help), -1, tag2, NULL); str_free(&help); } static void text_insert_msg(const char *title, const char *message) { GtkTextBuffer *buffer; GtkTextIter start, end; const char *msg = message; buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w)); gtk_text_buffer_get_bounds(buffer, &start, &end); gtk_text_buffer_delete(buffer, &start, &end); gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_w), 15); gtk_text_buffer_get_end_iter(buffer, &end); gtk_text_buffer_insert_with_tags(buffer, &end, title, -1, tag1, NULL); gtk_text_buffer_insert_at_cursor(buffer, "\n\n", 2); gtk_text_buffer_get_end_iter(buffer, &end); gtk_text_buffer_insert_with_tags(buffer, &end, msg, -1, tag2, NULL); } /* Main Windows Callbacks */ void on_save_activate(GtkMenuItem * menuitem, gpointer user_data); gboolean on_window1_delete_event(GtkWidget * widget, GdkEvent * event, gpointer user_data) { GtkWidget *dialog, *label; gint result; if (!conf_get_changed()) return FALSE; dialog = gtk_dialog_new_with_buttons("Warning !", GTK_WINDOW(main_wnd), (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_OK, GTK_RESPONSE_YES, GTK_STOCK_NO, GTK_RESPONSE_NO, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL); label = gtk_label_new("\nSave configuration ?\n"); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), label); gtk_widget_show(label); result = gtk_dialog_run(GTK_DIALOG(dialog)); switch (result) { case GTK_RESPONSE_YES: on_save_activate(NULL, NULL); return FALSE; case GTK_RESPONSE_NO: return FALSE; case GTK_RESPONSE_CANCEL: case GTK_RESPONSE_DELETE_EVENT: default: gtk_widget_destroy(dialog); return TRUE; } return FALSE; } void on_window1_destroy(GtkObject * object, gpointer user_data) { gtk_main_quit(); } void on_window1_size_request(GtkWidget * widget, GtkRequisition * requisition, gpointer user_data) { static gint old_h; gint w, h; if (widget->window == NULL) gtk_window_get_default_size(GTK_WINDOW(main_wnd), &w, &h); else gdk_window_get_size(widget->window, &w, &h); if (h == old_h) return; old_h = h; gtk_paned_set_position(GTK_PANED(vpaned), 2 * h / 3); } /* Menu & Toolbar Callbacks */ static void load_filename(GtkFileSelection * file_selector, gpointer user_data) { const gchar *fn; fn = gtk_file_selection_get_filename(GTK_FILE_SELECTION (user_data)); if (conf_read(fn)) text_insert_msg("Error", "Unable to load configuration !"); else display_tree(&rootmenu); } void on_load1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkWidget *fs; fs = gtk_file_selection_new("Load file..."); g_signal_connect(GTK_OBJECT(GTK_FILE_SELECTION(fs)->ok_button), "clicked", G_CALLBACK(load_filename), (gpointer) fs); g_signal_connect_swapped(GTK_OBJECT (GTK_FILE_SELECTION(fs)->ok_button), "clicked", G_CALLBACK(gtk_widget_destroy), (gpointer) fs); g_signal_connect_swapped(GTK_OBJECT (GTK_FILE_SELECTION(fs)->cancel_button), "clicked", G_CALLBACK(gtk_widget_destroy), (gpointer) fs); gtk_widget_show(fs); } void on_save_activate(GtkMenuItem * menuitem, gpointer user_data) { if (conf_write(NULL)) text_insert_msg("Error", "Unable to save configuration !"); conf_write_autoconf(0); } static void store_filename(GtkFileSelection * file_selector, gpointer user_data) { const gchar *fn; fn = gtk_file_selection_get_filename(GTK_FILE_SELECTION (user_data)); if (conf_write(fn)) text_insert_msg("Error", "Unable to save configuration !"); gtk_widget_destroy(GTK_WIDGET(user_data)); } void on_save_as1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkWidget *fs; fs = gtk_file_selection_new("Save file as..."); g_signal_connect(GTK_OBJECT(GTK_FILE_SELECTION(fs)->ok_button), "clicked", G_CALLBACK(store_filename), (gpointer) fs); g_signal_connect_swapped(GTK_OBJECT (GTK_FILE_SELECTION(fs)->ok_button), "clicked", G_CALLBACK(gtk_widget_destroy), (gpointer) fs); g_signal_connect_swapped(GTK_OBJECT (GTK_FILE_SELECTION(fs)->cancel_button), "clicked", G_CALLBACK(gtk_widget_destroy), (gpointer) fs); gtk_widget_show(fs); } void on_quit1_activate(GtkMenuItem * menuitem, gpointer user_data) { if (!on_window1_delete_event(NULL, NULL, NULL)) gtk_widget_destroy(GTK_WIDGET(main_wnd)); } void on_show_name1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkTreeViewColumn *col; show_name = GTK_CHECK_MENU_ITEM(menuitem)->active; col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_NAME); if (col) gtk_tree_view_column_set_visible(col, show_name); } void on_show_range1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkTreeViewColumn *col; show_range = GTK_CHECK_MENU_ITEM(menuitem)->active; col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_NO); if (col) gtk_tree_view_column_set_visible(col, show_range); col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_MOD); if (col) gtk_tree_view_column_set_visible(col, show_range); col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_YES); if (col) gtk_tree_view_column_set_visible(col, show_range); } void on_show_data1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkTreeViewColumn *col; show_value = GTK_CHECK_MENU_ITEM(menuitem)->active; col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_VALUE); if (col) gtk_tree_view_column_set_visible(col, show_value); } void on_set_option_mode1_activate(GtkMenuItem *menuitem, gpointer user_data) { opt_mode = OPT_NORMAL; gtk_tree_store_clear(tree2); display_tree(&rootmenu); /* instead of update_tree to speed-up */ } void on_set_option_mode2_activate(GtkMenuItem *menuitem, gpointer user_data) { opt_mode = OPT_ALL; gtk_tree_store_clear(tree2); display_tree(&rootmenu); /* instead of update_tree to speed-up */ } void on_set_option_mode3_activate(GtkMenuItem *menuitem, gpointer user_data) { opt_mode = OPT_PROMPT; gtk_tree_store_clear(tree2); display_tree(&rootmenu); /* instead of update_tree to speed-up */ } void on_introduction1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkWidget *dialog; const gchar *intro_text = "Welcome to gconfig, the GTK+ graphical configuration tool.\n" "For each option, a blank box indicates the feature is disabled, a\n" "check indicates it is enabled, and a dot indicates that it is to\n" "be compiled as a module. Clicking on the box will cycle through the three states.\n" "\n" "If you do not see an option (e.g., a device driver) that you\n" "believe should be present, try turning on Show All Options\n" "under the Options menu.\n" "Although there is no cross reference yet to help you figure out\n" "what other options must be enabled to support the option you\n" "are interested in, you can still view the help of a grayed-out\n" "option."; dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", intro_text); g_signal_connect_swapped(GTK_OBJECT(dialog), "response", G_CALLBACK(gtk_widget_destroy), GTK_OBJECT(dialog)); gtk_widget_show_all(dialog); } void on_about1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkWidget *dialog; const gchar *about_text = "gconfig is copyright (c) 2002 Romain Lievin <[email protected]>.\n" "Based on the source code from Roman Zippel.\n"; dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", about_text); g_signal_connect_swapped(GTK_OBJECT(dialog), "response", G_CALLBACK(gtk_widget_destroy), GTK_OBJECT(dialog)); gtk_widget_show_all(dialog); } void on_license1_activate(GtkMenuItem * menuitem, gpointer user_data) { GtkWidget *dialog; const gchar *license_text = "gconfig is released under the terms of the GNU GPL v2.\n" "For more information, please see the source code or\n" "visit http://www.fsf.org/licenses/licenses.html\n"; dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", license_text); g_signal_connect_swapped(GTK_OBJECT(dialog), "response", G_CALLBACK(gtk_widget_destroy), GTK_OBJECT(dialog)); gtk_widget_show_all(dialog); } void on_back_clicked(GtkButton * button, gpointer user_data) { enum prop_type ptype; current = current->parent; ptype = current->prompt ? current->prompt->type : P_UNKNOWN; if (ptype != P_MENU) current = current->parent; display_tree_part(); if (current == &rootmenu) gtk_widget_set_sensitive(back_btn, FALSE); } void on_load_clicked(GtkButton * button, gpointer user_data) { on_load1_activate(NULL, user_data); } void on_single_clicked(GtkButton * button, gpointer user_data) { view_mode = SINGLE_VIEW; gtk_widget_hide(tree1_w); current = &rootmenu; display_tree_part(); } void on_split_clicked(GtkButton * button, gpointer user_data) { gint w, h; view_mode = SPLIT_VIEW; gtk_widget_show(tree1_w); gtk_window_get_default_size(GTK_WINDOW(main_wnd), &w, &h); gtk_paned_set_position(GTK_PANED(hpaned), w / 2); if (tree2) gtk_tree_store_clear(tree2); display_list(); /* Disable back btn, like in full mode. */ gtk_widget_set_sensitive(back_btn, FALSE); } void on_full_clicked(GtkButton * button, gpointer user_data) { view_mode = FULL_VIEW; gtk_widget_hide(tree1_w); if (tree2) gtk_tree_store_clear(tree2); display_tree(&rootmenu); gtk_widget_set_sensitive(back_btn, FALSE); } void on_collapse_clicked(GtkButton * button, gpointer user_data) { gtk_tree_view_collapse_all(GTK_TREE_VIEW(tree2_w)); } void on_expand_clicked(GtkButton * button, gpointer user_data) { gtk_tree_view_expand_all(GTK_TREE_VIEW(tree2_w)); } /* CTree Callbacks */ /* Change hex/int/string value in the cell */ static void renderer_edited(GtkCellRendererText * cell, const gchar * path_string, const gchar * new_text, gpointer user_data) { GtkTreePath *path = gtk_tree_path_new_from_string(path_string); GtkTreeIter iter; const char *old_def, *new_def; struct menu *menu; struct symbol *sym; if (!gtk_tree_model_get_iter(model2, &iter, path)) return; gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1); sym = menu->sym; gtk_tree_model_get(model2, &iter, COL_VALUE, &old_def, -1); new_def = new_text; sym_set_string_value(sym, new_def); update_tree(&rootmenu, NULL); gtk_tree_path_free(path); } /* Change the value of a symbol and update the tree */ static void change_sym_value(struct menu *menu, gint col) { struct symbol *sym = menu->sym; tristate newval; if (!sym) return; if (col == COL_NO) newval = no; else if (col == COL_MOD) newval = mod; else if (col == COL_YES) newval = yes; else return; switch (sym_get_type(sym)) { case S_BOOLEAN: case S_TRISTATE: if (!sym_tristate_within_range(sym, newval)) newval = yes; sym_set_tristate_value(sym, newval); if (view_mode == FULL_VIEW) update_tree(&rootmenu, NULL); else if (view_mode == SPLIT_VIEW) { update_tree(browsed, NULL); display_list(); } else if (view_mode == SINGLE_VIEW) display_tree_part(); //fixme: keep exp/coll break; case S_INT: case S_HEX: case S_STRING: default: break; } } static void toggle_sym_value(struct menu *menu) { if (!menu->sym) return; sym_toggle_tristate_value(menu->sym); if (view_mode == FULL_VIEW) update_tree(&rootmenu, NULL); else if (view_mode == SPLIT_VIEW) { update_tree(browsed, NULL); display_list(); } else if (view_mode == SINGLE_VIEW) display_tree_part(); //fixme: keep exp/coll } static gint column2index(GtkTreeViewColumn * column) { gint i; for (i = 0; i < COL_NUMBER; i++) { GtkTreeViewColumn *col; col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), i); if (col == column) return i; } return -1; } /* User click: update choice (full) or goes down (single) */ gboolean on_treeview2_button_press_event(GtkWidget * widget, GdkEventButton * event, gpointer user_data) { GtkTreeView *view = GTK_TREE_VIEW(widget); GtkTreePath *path; GtkTreeViewColumn *column; GtkTreeIter iter; struct menu *menu; gint col; #if GTK_CHECK_VERSION(2,1,4) // bug in ctree with earlier version of GTK gint tx = (gint) event->x; gint ty = (gint) event->y; gint cx, cy; gtk_tree_view_get_path_at_pos(view, tx, ty, &path, &column, &cx, &cy); #else gtk_tree_view_get_cursor(view, &path, &column); #endif if (path == NULL) return FALSE; if (!gtk_tree_model_get_iter(model2, &iter, path)) return FALSE; gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1); col = column2index(column); if (event->type == GDK_2BUTTON_PRESS) { enum prop_type ptype; ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; if (ptype == P_MENU && view_mode != FULL_VIEW && col == COL_OPTION) { // goes down into menu current = menu; display_tree_part(); gtk_widget_set_sensitive(back_btn, TRUE); } else if (col == COL_OPTION) { toggle_sym_value(menu); gtk_tree_view_expand_row(view, path, TRUE); } } else { if (col == COL_VALUE) { toggle_sym_value(menu); gtk_tree_view_expand_row(view, path, TRUE); } else if (col == COL_NO || col == COL_MOD || col == COL_YES) { change_sym_value(menu, col); gtk_tree_view_expand_row(view, path, TRUE); } } return FALSE; } /* Key pressed: update choice */ gboolean on_treeview2_key_press_event(GtkWidget * widget, GdkEventKey * event, gpointer user_data) { GtkTreeView *view = GTK_TREE_VIEW(widget); GtkTreePath *path; GtkTreeViewColumn *column; GtkTreeIter iter; struct menu *menu; gint col; gtk_tree_view_get_cursor(view, &path, &column); if (path == NULL) return FALSE; if (event->keyval == GDK_space) { if (gtk_tree_view_row_expanded(view, path)) gtk_tree_view_collapse_row(view, path); else gtk_tree_view_expand_row(view, path, FALSE); return TRUE; } if (event->keyval == GDK_KP_Enter) { } if (widget == tree1_w) return FALSE; gtk_tree_model_get_iter(model2, &iter, path); gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1); if (!strcasecmp(event->string, "n")) col = COL_NO; else if (!strcasecmp(event->string, "m")) col = COL_MOD; else if (!strcasecmp(event->string, "y")) col = COL_YES; else col = -1; change_sym_value(menu, col); return FALSE; } /* Row selection changed: update help */ void on_treeview2_cursor_changed(GtkTreeView * treeview, gpointer user_data) { GtkTreeSelection *selection; GtkTreeIter iter; struct menu *menu; selection = gtk_tree_view_get_selection(treeview); if (gtk_tree_selection_get_selected(selection, &model2, &iter)) { gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1); text_insert_help(menu); } } /* User click: display sub-tree in the right frame. */ gboolean on_treeview1_button_press_event(GtkWidget * widget, GdkEventButton * event, gpointer user_data) { GtkTreeView *view = GTK_TREE_VIEW(widget); GtkTreePath *path; GtkTreeViewColumn *column; GtkTreeIter iter; struct menu *menu; gint tx = (gint) event->x; gint ty = (gint) event->y; gint cx, cy; gtk_tree_view_get_path_at_pos(view, tx, ty, &path, &column, &cx, &cy); if (path == NULL) return FALSE; gtk_tree_model_get_iter(model1, &iter, path); gtk_tree_model_get(model1, &iter, COL_MENU, &menu, -1); if (event->type == GDK_2BUTTON_PRESS) { toggle_sym_value(menu); current = menu; display_tree_part(); } else { browsed = menu; display_tree_part(); } gtk_widget_realize(tree2_w); gtk_tree_view_set_cursor(view, path, NULL, FALSE); gtk_widget_grab_focus(tree2_w); return FALSE; } /* Fill a row of strings */ static gchar **fill_row(struct menu *menu) { static gchar *row[COL_NUMBER]; struct symbol *sym = menu->sym; const char *def; int stype; tristate val; enum prop_type ptype; int i; for (i = COL_OPTION; i <= COL_COLOR; i++) g_free(row[i]); bzero(row, sizeof(row)); ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; row[COL_OPTION] = g_strdup_printf("%s %s %s %s", ptype == P_COMMENT ? "***" : "", menu_get_prompt(menu), ptype == P_COMMENT ? "***" : "", sym && !sym_has_value(sym) ? "(NEW)" : ""); if (opt_mode == OPT_ALL && !menu_is_visible(menu)) row[COL_COLOR] = g_strdup("DarkGray"); else if (opt_mode == OPT_PROMPT && menu_has_prompt(menu) && !menu_is_visible(menu)) row[COL_COLOR] = g_strdup("DarkGray"); else row[COL_COLOR] = g_strdup("Black"); switch (ptype) { case P_MENU: row[COL_PIXBUF] = (gchar *) xpm_menu; if (view_mode == SINGLE_VIEW) row[COL_PIXVIS] = GINT_TO_POINTER(TRUE); row[COL_BTNVIS] = GINT_TO_POINTER(FALSE); break; case P_COMMENT: row[COL_PIXBUF] = (gchar *) xpm_void; row[COL_PIXVIS] = GINT_TO_POINTER(FALSE); row[COL_BTNVIS] = GINT_TO_POINTER(FALSE); break; default: row[COL_PIXBUF] = (gchar *) xpm_void; row[COL_PIXVIS] = GINT_TO_POINTER(FALSE); row[COL_BTNVIS] = GINT_TO_POINTER(TRUE); break; } if (!sym) return row; row[COL_NAME] = g_strdup(sym->name); sym_calc_value(sym); sym->flags &= ~SYMBOL_CHANGED; if (sym_is_choice(sym)) { // parse childs for getting final value struct menu *child; struct symbol *def_sym = sym_get_choice_value(sym); struct menu *def_menu = NULL; row[COL_BTNVIS] = GINT_TO_POINTER(FALSE); for (child = menu->list; child; child = child->next) { if (menu_is_visible(child) && child->sym == def_sym) def_menu = child; } if (def_menu) row[COL_VALUE] = g_strdup(menu_get_prompt(def_menu)); } if (sym->flags & SYMBOL_CHOICEVAL) row[COL_BTNRAD] = GINT_TO_POINTER(TRUE); stype = sym_get_type(sym); switch (stype) { case S_BOOLEAN: if (GPOINTER_TO_INT(row[COL_PIXVIS]) == FALSE) row[COL_BTNVIS] = GINT_TO_POINTER(TRUE); if (sym_is_choice(sym)) break; /* fall through */ case S_TRISTATE: val = sym_get_tristate_value(sym); switch (val) { case no: row[COL_NO] = g_strdup("N"); row[COL_VALUE] = g_strdup("N"); row[COL_BTNACT] = GINT_TO_POINTER(FALSE); row[COL_BTNINC] = GINT_TO_POINTER(FALSE); break; case mod: row[COL_MOD] = g_strdup("M"); row[COL_VALUE] = g_strdup("M"); row[COL_BTNINC] = GINT_TO_POINTER(TRUE); break; case yes: row[COL_YES] = g_strdup("Y"); row[COL_VALUE] = g_strdup("Y"); row[COL_BTNACT] = GINT_TO_POINTER(TRUE); row[COL_BTNINC] = GINT_TO_POINTER(FALSE); break; } if (val != no && sym_tristate_within_range(sym, no)) row[COL_NO] = g_strdup("_"); if (val != mod && sym_tristate_within_range(sym, mod)) row[COL_MOD] = g_strdup("_"); if (val != yes && sym_tristate_within_range(sym, yes)) row[COL_YES] = g_strdup("_"); break; case S_INT: case S_HEX: case S_STRING: def = sym_get_string_value(sym); row[COL_VALUE] = g_strdup(def); row[COL_EDIT] = GINT_TO_POINTER(TRUE); row[COL_BTNVIS] = GINT_TO_POINTER(FALSE); break; } return row; } /* Set the node content with a row of strings */ static void set_node(GtkTreeIter * node, struct menu *menu, gchar ** row) { GdkColor color; gboolean success; GdkPixbuf *pix; pix = gdk_pixbuf_new_from_xpm_data((const char **) row[COL_PIXBUF]); gdk_color_parse(row[COL_COLOR], &color); gdk_colormap_alloc_colors(gdk_colormap_get_system(), &color, 1, FALSE, FALSE, &success); gtk_tree_store_set(tree, node, COL_OPTION, row[COL_OPTION], COL_NAME, row[COL_NAME], COL_NO, row[COL_NO], COL_MOD, row[COL_MOD], COL_YES, row[COL_YES], COL_VALUE, row[COL_VALUE], COL_MENU, (gpointer) menu, COL_COLOR, &color, COL_EDIT, GPOINTER_TO_INT(row[COL_EDIT]), COL_PIXBUF, pix, COL_PIXVIS, GPOINTER_TO_INT(row[COL_PIXVIS]), COL_BTNVIS, GPOINTER_TO_INT(row[COL_BTNVIS]), COL_BTNACT, GPOINTER_TO_INT(row[COL_BTNACT]), COL_BTNINC, GPOINTER_TO_INT(row[COL_BTNINC]), COL_BTNRAD, GPOINTER_TO_INT(row[COL_BTNRAD]), -1); g_object_unref(pix); } /* Add a node to the tree */ static void place_node(struct menu *menu, char **row) { GtkTreeIter *parent = parents[indent - 1]; GtkTreeIter *node = parents[indent]; gtk_tree_store_append(tree, node, parent); set_node(node, menu, row); } /* Find a node in the GTK+ tree */ static GtkTreeIter found; /* * Find a menu in the GtkTree starting at parent. */ static GtkTreeIter *gtktree_iter_find_node(GtkTreeIter *parent, struct menu *tofind) { GtkTreeIter iter; GtkTreeIter *child = &iter; gboolean valid; GtkTreeIter *ret; valid = gtk_tree_model_iter_children(model2, child, parent); while (valid) { struct menu *menu; gtk_tree_model_get(model2, child, 6, &menu, -1); if (menu == tofind) { memcpy(&found, child, sizeof(GtkTreeIter)); return &found; } ret = gtktree_iter_find_node(child, tofind); if (ret) return ret; valid = gtk_tree_model_iter_next(model2, child); } return NULL; } /* * Update the tree by adding/removing entries * Does not change other nodes */ static void update_tree(struct menu *src, GtkTreeIter * dst) { struct menu *child1; GtkTreeIter iter, tmp; GtkTreeIter *child2 = &iter; gboolean valid; GtkTreeIter *sibling; struct symbol *sym; struct menu *menu1, *menu2; if (src == &rootmenu) indent = 1; valid = gtk_tree_model_iter_children(model2, child2, dst); for (child1 = src->list; child1; child1 = child1->next) { sym = child1->sym; reparse: menu1 = child1; if (valid) gtk_tree_model_get(model2, child2, COL_MENU, &menu2, -1); else menu2 = NULL; // force adding of a first child #ifdef DEBUG printf("%*c%s | %s\n", indent, ' ', menu1 ? menu_get_prompt(menu1) : "nil", menu2 ? menu_get_prompt(menu2) : "nil"); #endif if ((opt_mode == OPT_NORMAL && !menu_is_visible(child1)) || (opt_mode == OPT_PROMPT && !menu_has_prompt(child1)) || (opt_mode == OPT_ALL && !menu_get_prompt(child1))) { /* remove node */ if (gtktree_iter_find_node(dst, menu1) != NULL) { memcpy(&tmp, child2, sizeof(GtkTreeIter)); valid = gtk_tree_model_iter_next(model2, child2); gtk_tree_store_remove(tree2, &tmp); if (!valid) return; /* next parent */ else goto reparse; /* next child */ } else continue; } if (menu1 != menu2) { if (gtktree_iter_find_node(dst, menu1) == NULL) { // add node if (!valid && !menu2) sibling = NULL; else sibling = child2; gtk_tree_store_insert_before(tree2, child2, dst, sibling); set_node(child2, menu1, fill_row(menu1)); if (menu2 == NULL) valid = TRUE; } else { // remove node memcpy(&tmp, child2, sizeof(GtkTreeIter)); valid = gtk_tree_model_iter_next(model2, child2); gtk_tree_store_remove(tree2, &tmp); if (!valid) return; // next parent else goto reparse; // next child } } else if (sym && (sym->flags & SYMBOL_CHANGED)) { set_node(child2, menu1, fill_row(menu1)); } indent++; update_tree(child1, child2); indent--; valid = gtk_tree_model_iter_next(model2, child2); } } /* Display the whole tree (single/split/full view) */ static void display_tree(struct menu *menu) { struct symbol *sym; struct property *prop; struct menu *child; enum prop_type ptype; if (menu == &rootmenu) { indent = 1; current = &rootmenu; } for (child = menu->list; child; child = child->next) { prop = child->prompt; sym = child->sym; ptype = prop ? prop->type : P_UNKNOWN; if (sym) sym->flags &= ~SYMBOL_CHANGED; if ((view_mode == SPLIT_VIEW) && !(child->flags & MENU_ROOT) && (tree == tree1)) continue; if ((view_mode == SPLIT_VIEW) && (child->flags & MENU_ROOT) && (tree == tree2)) continue; if ((opt_mode == OPT_NORMAL && menu_is_visible(child)) || (opt_mode == OPT_PROMPT && menu_has_prompt(child)) || (opt_mode == OPT_ALL && menu_get_prompt(child))) place_node(child, fill_row(child)); #ifdef DEBUG printf("%*c%s: ", indent, ' ', menu_get_prompt(child)); printf("%s", child->flags & MENU_ROOT ? "rootmenu | " : ""); printf("%s", prop_get_type_name(ptype)); printf(" | "); if (sym) { printf("%s", sym_type_name(sym->type)); printf(" | "); printf("%s", dbg_sym_flags(sym->flags)); printf("\n"); } else printf("\n"); #endif if ((view_mode != FULL_VIEW) && (ptype == P_MENU) && (tree == tree2)) continue; /* if (((menu != &rootmenu) && !(menu->flags & MENU_ROOT)) || (view_mode == FULL_VIEW) || (view_mode == SPLIT_VIEW))*/ /* Change paned position if the view is not in 'split mode' */ if (view_mode == SINGLE_VIEW || view_mode == FULL_VIEW) { gtk_paned_set_position(GTK_PANED(hpaned), 0); } if (((view_mode == SINGLE_VIEW) && (menu->flags & MENU_ROOT)) || (view_mode == FULL_VIEW) || (view_mode == SPLIT_VIEW)) { indent++; display_tree(child); indent--; } } } /* Display a part of the tree starting at current node (single/split view) */ static void display_tree_part(void) { if (tree2) gtk_tree_store_clear(tree2); if (view_mode == SINGLE_VIEW) display_tree(current); else if (view_mode == SPLIT_VIEW) display_tree(browsed); gtk_tree_view_expand_all(GTK_TREE_VIEW(tree2_w)); } /* Display the list in the left frame (split view) */ static void display_list(void) { if (tree1) gtk_tree_store_clear(tree1); tree = tree1; display_tree(&rootmenu); gtk_tree_view_expand_all(GTK_TREE_VIEW(tree1_w)); tree = tree2; } static void fixup_rootmenu(struct menu *menu) { struct menu *child; static int menu_cnt = 0; menu->flags |= MENU_ROOT; for (child = menu->list; child; child = child->next) { if (child->prompt && child->prompt->type == P_MENU) { menu_cnt++; fixup_rootmenu(child); menu_cnt--; } else if (!menu_cnt) fixup_rootmenu(child); } } /* Main */ int main(int ac, char *av[]) { const char *name; char *env; gchar *glade_file; /* GTK stuffs */ gtk_set_locale(); gtk_init(&ac, &av); glade_init(); /* Determine GUI path */ env = getenv(SRCTREE); if (env) glade_file = g_strconcat(env, "/scripts/kconfig/gconf.glade", NULL); else if (av[0][0] == '/') glade_file = g_strconcat(av[0], ".glade", NULL); else glade_file = g_strconcat(g_get_current_dir(), "/", av[0], ".glade", NULL); /* Conf stuffs */ if (ac > 1 && av[1][0] == '-') { switch (av[1][1]) { case 'a': //showAll = 1; break; case 's': conf_set_message_callback(NULL); break; case 'h': case '?': printf("%s [-s] <config>\n", av[0]); exit(0); } name = av[2]; } else name = av[1]; conf_parse(name); fixup_rootmenu(&rootmenu); conf_read(NULL); /* Load the interface and connect signals */ init_main_window(glade_file); init_tree_model(); init_left_tree(); init_right_tree(); switch (view_mode) { case SINGLE_VIEW: display_tree_part(); break; case SPLIT_VIEW: display_list(); break; case FULL_VIEW: display_tree(&rootmenu); break; } gtk_main(); return 0; } static void conf_changed(void) { bool changed = conf_get_changed(); gtk_widget_set_sensitive(save_btn, changed); gtk_widget_set_sensitive(save_menu_item, changed); }
linux-master
scripts/kconfig/gconf.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2008 Nir Tzachar <[email protected]> * * Derived from menuconfig. */ #include "nconf.h" #include "lkc.h" int attr_normal; int attr_main_heading; int attr_main_menu_box; int attr_main_menu_fore; int attr_main_menu_back; int attr_main_menu_grey; int attr_main_menu_heading; int attr_scrollwin_text; int attr_scrollwin_heading; int attr_scrollwin_box; int attr_dialog_text; int attr_dialog_menu_fore; int attr_dialog_menu_back; int attr_dialog_box; int attr_input_box; int attr_input_heading; int attr_input_text; int attr_input_field; int attr_function_text; int attr_function_highlight; #define COLOR_ATTR(_at, _fg, _bg, _hl) \ { .attr = &(_at), .has_color = true, .color_fg = _fg, .color_bg = _bg, .highlight = _hl } #define NO_COLOR_ATTR(_at, _hl) \ { .attr = &(_at), .has_color = false, .highlight = _hl } #define COLOR_DEFAULT -1 struct nconf_attr_param { int *attr; bool has_color; int color_fg; int color_bg; int highlight; }; static const struct nconf_attr_param color_theme_params[] = { COLOR_ATTR(attr_normal, COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_main_heading, COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD | A_UNDERLINE), COLOR_ATTR(attr_main_menu_box, COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_main_menu_fore, COLOR_DEFAULT, COLOR_DEFAULT, A_REVERSE), COLOR_ATTR(attr_main_menu_back, COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_main_menu_grey, COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_main_menu_heading, COLOR_GREEN, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_scrollwin_text, COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_scrollwin_heading, COLOR_GREEN, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_scrollwin_box, COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_dialog_text, COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_dialog_menu_fore, COLOR_RED, COLOR_DEFAULT, A_STANDOUT), COLOR_ATTR(attr_dialog_menu_back, COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_dialog_box, COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_input_box, COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_input_heading, COLOR_GREEN, COLOR_DEFAULT, A_BOLD), COLOR_ATTR(attr_input_text, COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), COLOR_ATTR(attr_input_field, COLOR_DEFAULT, COLOR_DEFAULT, A_UNDERLINE), COLOR_ATTR(attr_function_text, COLOR_YELLOW, COLOR_DEFAULT, A_REVERSE), COLOR_ATTR(attr_function_highlight, COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), { /* sentinel */ } }; static const struct nconf_attr_param no_color_theme_params[] = { NO_COLOR_ATTR(attr_normal, A_NORMAL), NO_COLOR_ATTR(attr_main_heading, A_BOLD | A_UNDERLINE), NO_COLOR_ATTR(attr_main_menu_box, A_NORMAL), NO_COLOR_ATTR(attr_main_menu_fore, A_STANDOUT), NO_COLOR_ATTR(attr_main_menu_back, A_NORMAL), NO_COLOR_ATTR(attr_main_menu_grey, A_NORMAL), NO_COLOR_ATTR(attr_main_menu_heading, A_BOLD), NO_COLOR_ATTR(attr_scrollwin_text, A_NORMAL), NO_COLOR_ATTR(attr_scrollwin_heading, A_BOLD), NO_COLOR_ATTR(attr_scrollwin_box, A_BOLD), NO_COLOR_ATTR(attr_dialog_text, A_NORMAL), NO_COLOR_ATTR(attr_dialog_menu_fore, A_STANDOUT), NO_COLOR_ATTR(attr_dialog_menu_back, A_NORMAL), NO_COLOR_ATTR(attr_dialog_box, A_BOLD), NO_COLOR_ATTR(attr_input_box, A_BOLD), NO_COLOR_ATTR(attr_input_heading, A_BOLD), NO_COLOR_ATTR(attr_input_text, A_NORMAL), NO_COLOR_ATTR(attr_input_field, A_UNDERLINE), NO_COLOR_ATTR(attr_function_text, A_REVERSE), NO_COLOR_ATTR(attr_function_highlight, A_BOLD), { /* sentinel */ } }; void set_colors(void) { const struct nconf_attr_param *p; int pair = 0; if (has_colors()) { start_color(); use_default_colors(); p = color_theme_params; } else { p = no_color_theme_params; } for (; p->attr; p++) { int attr = p->highlight; if (p->has_color) { pair++; init_pair(pair, p->color_fg, p->color_bg); attr |= COLOR_PAIR(pair); } *p->attr = attr; } } /* this changes the windows attributes !!! */ void print_in_middle(WINDOW *win, int y, int width, const char *str, int attrs) { wattrset(win, attrs); mvwprintw(win, y, (width - strlen(str)) / 2, "%s", str); } int get_line_no(const char *text) { int i; int total = 1; if (!text) return 0; for (i = 0; text[i] != '\0'; i++) if (text[i] == '\n') total++; return total; } const char *get_line(const char *text, int line_no) { int i; int lines = 0; if (!text) return NULL; for (i = 0; text[i] != '\0' && lines < line_no; i++) if (text[i] == '\n') lines++; return text+i; } int get_line_length(const char *line) { int res = 0; while (*line != '\0' && *line != '\n') { line++; res++; } return res; } /* print all lines to the window. */ void fill_window(WINDOW *win, const char *text) { int x, y; int total_lines = get_line_no(text); int i; getmaxyx(win, y, x); /* do not go over end of line */ total_lines = min(total_lines, y); for (i = 0; i < total_lines; i++) { char tmp[x+10]; const char *line = get_line(text, i); int len = get_line_length(line); strncpy(tmp, line, min(len, x)); tmp[len] = '\0'; mvwprintw(win, i, 0, "%s", tmp); } } /* get the message, and buttons. * each button must be a char* * return the selected button * * this dialog is used for 2 different things: * 1) show a text box, no buttons. * 2) show a dialog, with horizontal buttons */ int btn_dialog(WINDOW *main_window, const char *msg, int btn_num, ...) { va_list ap; char *btn; int btns_width = 0; int msg_lines = 0; int msg_width = 0; int total_width; int win_rows = 0; WINDOW *win; WINDOW *msg_win; WINDOW *menu_win; MENU *menu; ITEM *btns[btn_num+1]; int i, x, y; int res = -1; va_start(ap, btn_num); for (i = 0; i < btn_num; i++) { btn = va_arg(ap, char *); btns[i] = new_item(btn, ""); btns_width += strlen(btn)+1; } va_end(ap); btns[btn_num] = NULL; /* find the widest line of msg: */ msg_lines = get_line_no(msg); for (i = 0; i < msg_lines; i++) { const char *line = get_line(msg, i); int len = get_line_length(line); if (msg_width < len) msg_width = len; } total_width = max(msg_width, btns_width); /* place dialog in middle of screen */ y = (getmaxy(stdscr)-(msg_lines+4))/2; x = (getmaxx(stdscr)-(total_width+4))/2; /* create the windows */ if (btn_num > 0) win_rows = msg_lines+4; else win_rows = msg_lines+2; win = newwin(win_rows, total_width+4, y, x); keypad(win, TRUE); menu_win = derwin(win, 1, btns_width, win_rows-2, 1+(total_width+2-btns_width)/2); menu = new_menu(btns); msg_win = derwin(win, win_rows-2, msg_width, 1, 1+(total_width+2-msg_width)/2); set_menu_fore(menu, attr_dialog_menu_fore); set_menu_back(menu, attr_dialog_menu_back); wattrset(win, attr_dialog_box); box(win, 0, 0); /* print message */ wattrset(msg_win, attr_dialog_text); fill_window(msg_win, msg); set_menu_win(menu, win); set_menu_sub(menu, menu_win); set_menu_format(menu, 1, btn_num); menu_opts_off(menu, O_SHOWDESC); menu_opts_off(menu, O_SHOWMATCH); menu_opts_on(menu, O_ONEVALUE); menu_opts_on(menu, O_NONCYCLIC); set_menu_mark(menu, ""); post_menu(menu); touchwin(win); refresh_all_windows(main_window); while ((res = wgetch(win))) { switch (res) { case KEY_LEFT: menu_driver(menu, REQ_LEFT_ITEM); break; case KEY_RIGHT: menu_driver(menu, REQ_RIGHT_ITEM); break; case 10: /* ENTER */ case 27: /* ESCAPE */ case ' ': case KEY_F(F_BACK): case KEY_F(F_EXIT): break; } touchwin(win); refresh_all_windows(main_window); if (res == 10 || res == ' ') { res = item_index(current_item(menu)); break; } else if (res == 27 || res == KEY_F(F_BACK) || res == KEY_F(F_EXIT)) { res = KEY_EXIT; break; } } unpost_menu(menu); free_menu(menu); for (i = 0; i < btn_num; i++) free_item(btns[i]); delwin(win); return res; } int dialog_inputbox(WINDOW *main_window, const char *title, const char *prompt, const char *init, char **resultp, int *result_len) { int prompt_lines = 0; int prompt_width = 0; WINDOW *win; WINDOW *prompt_win; WINDOW *form_win; PANEL *panel; int i, x, y, lines, columns, win_lines, win_cols; int res = -1; int cursor_position = strlen(init); int cursor_form_win; char *result = *resultp; getmaxyx(stdscr, lines, columns); if (strlen(init)+1 > *result_len) { *result_len = strlen(init)+1; *resultp = result = xrealloc(result, *result_len); } /* find the widest line of msg: */ prompt_lines = get_line_no(prompt); for (i = 0; i < prompt_lines; i++) { const char *line = get_line(prompt, i); int len = get_line_length(line); prompt_width = max(prompt_width, len); } if (title) prompt_width = max(prompt_width, strlen(title)); win_lines = min(prompt_lines+6, lines-2); win_cols = min(prompt_width+7, columns-2); prompt_lines = max(win_lines-6, 0); prompt_width = max(win_cols-7, 0); /* place dialog in middle of screen */ y = (lines-win_lines)/2; x = (columns-win_cols)/2; strncpy(result, init, *result_len); /* create the windows */ win = newwin(win_lines, win_cols, y, x); prompt_win = derwin(win, prompt_lines+1, prompt_width, 2, 2); form_win = derwin(win, 1, prompt_width, prompt_lines+3, 2); keypad(form_win, TRUE); wattrset(form_win, attr_input_field); wattrset(win, attr_input_box); box(win, 0, 0); wattrset(win, attr_input_heading); if (title) mvwprintw(win, 0, 3, "%s", title); /* print message */ wattrset(prompt_win, attr_input_text); fill_window(prompt_win, prompt); mvwprintw(form_win, 0, 0, "%*s", prompt_width, " "); cursor_form_win = min(cursor_position, prompt_width-1); mvwprintw(form_win, 0, 0, "%s", result + cursor_position-cursor_form_win); /* create panels */ panel = new_panel(win); /* show the cursor */ curs_set(1); touchwin(win); refresh_all_windows(main_window); while ((res = wgetch(form_win))) { int len = strlen(result); switch (res) { case 10: /* ENTER */ case 27: /* ESCAPE */ case KEY_F(F_HELP): case KEY_F(F_EXIT): case KEY_F(F_BACK): break; case 8: /* ^H */ case 127: /* ^? */ case KEY_BACKSPACE: if (cursor_position > 0) { memmove(&result[cursor_position-1], &result[cursor_position], len-cursor_position+1); cursor_position--; cursor_form_win--; len--; } break; case KEY_DC: if (cursor_position >= 0 && cursor_position < len) { memmove(&result[cursor_position], &result[cursor_position+1], len-cursor_position+1); len--; } break; case KEY_UP: case KEY_RIGHT: if (cursor_position < len) { cursor_position++; cursor_form_win++; } break; case KEY_DOWN: case KEY_LEFT: if (cursor_position > 0) { cursor_position--; cursor_form_win--; } break; case KEY_HOME: cursor_position = 0; cursor_form_win = 0; break; case KEY_END: cursor_position = len; cursor_form_win = min(cursor_position, prompt_width-1); break; default: if ((isgraph(res) || isspace(res))) { /* one for new char, one for '\0' */ if (len+2 > *result_len) { *result_len = len+2; *resultp = result = realloc(result, *result_len); } /* insert the char at the proper position */ memmove(&result[cursor_position+1], &result[cursor_position], len-cursor_position+1); result[cursor_position] = res; cursor_position++; cursor_form_win++; len++; } else { mvprintw(0, 0, "unknown key: %d\n", res); } break; } if (cursor_form_win < 0) cursor_form_win = 0; else if (cursor_form_win > prompt_width-1) cursor_form_win = prompt_width-1; wmove(form_win, 0, 0); wclrtoeol(form_win); mvwprintw(form_win, 0, 0, "%*s", prompt_width, " "); mvwprintw(form_win, 0, 0, "%s", result + cursor_position-cursor_form_win); wmove(form_win, 0, cursor_form_win); touchwin(win); refresh_all_windows(main_window); if (res == 10) { res = 0; break; } else if (res == 27 || res == KEY_F(F_BACK) || res == KEY_F(F_EXIT)) { res = KEY_EXIT; break; } else if (res == KEY_F(F_HELP)) { res = 1; break; } } /* hide the cursor */ curs_set(0); del_panel(panel); delwin(prompt_win); delwin(form_win); delwin(win); return res; } /* refresh all windows in the correct order */ void refresh_all_windows(WINDOW *main_window) { update_panels(); touchwin(main_window); refresh(); } void show_scroll_win(WINDOW *main_window, const char *title, const char *text) { (void)show_scroll_win_ext(main_window, title, (char *)text, NULL, NULL, NULL, NULL); } /* layman's scrollable window... */ int show_scroll_win_ext(WINDOW *main_window, const char *title, char *text, int *vscroll, int *hscroll, extra_key_cb_fn extra_key_cb, void *data) { int res; int total_lines = get_line_no(text); int x, y, lines, columns; int start_x = 0, start_y = 0; int text_lines = 0, text_cols = 0; int total_cols = 0; int win_cols = 0; int win_lines = 0; int i = 0; WINDOW *win; WINDOW *pad; PANEL *panel; bool done = false; if (hscroll) start_x = *hscroll; if (vscroll) start_y = *vscroll; getmaxyx(stdscr, lines, columns); /* find the widest line of msg: */ total_lines = get_line_no(text); for (i = 0; i < total_lines; i++) { const char *line = get_line(text, i); int len = get_line_length(line); total_cols = max(total_cols, len+2); } /* create the pad */ pad = newpad(total_lines+10, total_cols+10); wattrset(pad, attr_scrollwin_text); fill_window(pad, text); win_lines = min(total_lines+4, lines-2); win_cols = min(total_cols+2, columns-2); text_lines = max(win_lines-4, 0); text_cols = max(win_cols-2, 0); /* place window in middle of screen */ y = (lines-win_lines)/2; x = (columns-win_cols)/2; win = newwin(win_lines, win_cols, y, x); keypad(win, TRUE); /* show the help in the help window, and show the help panel */ wattrset(win, attr_scrollwin_box); box(win, 0, 0); wattrset(win, attr_scrollwin_heading); mvwprintw(win, 0, 3, " %s ", title); panel = new_panel(win); /* handle scrolling */ while (!done) { copywin(pad, win, start_y, start_x, 2, 2, text_lines, text_cols, 0); print_in_middle(win, text_lines+2, text_cols, "<OK>", attr_dialog_menu_fore); wrefresh(win); res = wgetch(win); switch (res) { case KEY_NPAGE: case ' ': case 'd': start_y += text_lines-2; break; case KEY_PPAGE: case 'u': start_y -= text_lines+2; break; case KEY_HOME: start_y = 0; break; case KEY_END: start_y = total_lines-text_lines; break; case KEY_DOWN: case 'j': start_y++; break; case KEY_UP: case 'k': start_y--; break; case KEY_LEFT: case 'h': start_x--; break; case KEY_RIGHT: case 'l': start_x++; break; default: if (extra_key_cb) { size_t start = (get_line(text, start_y) - text); size_t end = (get_line(text, start_y + text_lines) - text); if (extra_key_cb(res, start, end, data)) { done = true; break; } } } if (res == 0 || res == 10 || res == 27 || res == 'q' || res == KEY_F(F_HELP) || res == KEY_F(F_BACK) || res == KEY_F(F_EXIT)) break; if (start_y < 0) start_y = 0; if (start_y >= total_lines-text_lines) start_y = total_lines-text_lines; if (start_x < 0) start_x = 0; if (start_x >= total_cols-text_cols) start_x = total_cols-text_cols; } if (hscroll) *hscroll = start_x; if (vscroll) *vscroll = start_y; del_panel(panel); delwin(win); refresh_all_windows(main_window); return res; }
linux-master
scripts/kconfig/nconf.gui.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> * * Introduced single menu mode (show all sub-menus in one large tree). * 2002-11-06 Petr Baudis <[email protected]> * * i18n, 2005, Arnaldo Carvalho de Melo <[email protected]> */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <signal.h> #include <unistd.h> #include "lkc.h" #include "lxdialog/dialog.h" static const char mconf_readme[] = "Overview\n" "--------\n" "This interface lets you select features and parameters for the build.\n" "Features can either be built-in, modularized, or ignored. Parameters\n" "must be entered in as decimal or hexadecimal numbers or text.\n" "\n" "Menu items beginning with following braces represent features that\n" " [ ] can be built in or removed\n" " < > can be built in, modularized or removed\n" " { } can be built in or modularized (selected by other feature)\n" " - - are selected by other feature,\n" "while *, M or whitespace inside braces means to build in, build as\n" "a module or to exclude the feature respectively.\n" "\n" "To change any of these features, highlight it with the cursor\n" "keys and press <Y> to build it in, <M> to make it a module or\n" "<N> to remove it. You may also press the <Space Bar> to cycle\n" "through the available options (i.e. Y->N->M->Y).\n" "\n" "Some additional keyboard hints:\n" "\n" "Menus\n" "----------\n" "o Use the Up/Down arrow keys (cursor keys) to highlight the item you\n" " wish to change or the submenu you wish to select and press <Enter>.\n" " Submenus are designated by \"--->\", empty ones by \"----\".\n" "\n" " Shortcut: Press the option's highlighted letter (hotkey).\n" " Pressing a hotkey more than once will sequence\n" " through all visible items which use that hotkey.\n" "\n" " You may also use the <PAGE UP> and <PAGE DOWN> keys to scroll\n" " unseen options into view.\n" "\n" "o To exit a menu use the cursor keys to highlight the <Exit> button\n" " and press <ENTER>.\n" "\n" " Shortcut: Press <ESC><ESC> or <E> or <X> if there is no hotkey\n" " using those letters. You may press a single <ESC>, but\n" " there is a delayed response which you may find annoying.\n" "\n" " Also, the <TAB> and cursor keys will cycle between <Select>,\n" " <Exit>, <Help>, <Save>, and <Load>.\n" "\n" "o To get help with an item, use the cursor keys to highlight <Help>\n" " and press <ENTER>.\n" "\n" " Shortcut: Press <H> or <?>.\n" "\n" "o To toggle the display of hidden options, press <Z>.\n" "\n" "\n" "Radiolists (Choice lists)\n" "-----------\n" "o Use the cursor keys to select the option you wish to set and press\n" " <S> or the <SPACE BAR>.\n" "\n" " Shortcut: Press the first letter of the option you wish to set then\n" " press <S> or <SPACE BAR>.\n" "\n" "o To see available help for the item, use the cursor keys to highlight\n" " <Help> and Press <ENTER>.\n" "\n" " Shortcut: Press <H> or <?>.\n" "\n" " Also, the <TAB> and cursor keys will cycle between <Select> and\n" " <Help>\n" "\n" "\n" "Data Entry\n" "-----------\n" "o Enter the requested information and press <ENTER>\n" " If you are entering hexadecimal values, it is not necessary to\n" " add the '0x' prefix to the entry.\n" "\n" "o For help, use the <TAB> or cursor keys to highlight the help option\n" " and press <ENTER>. You can try <TAB><H> as well.\n" "\n" "\n" "Text Box (Help Window)\n" "--------\n" "o Use the cursor keys to scroll up/down/left/right. The VI editor\n" " keys h,j,k,l function here as do <u>, <d>, <SPACE BAR> and <B> for\n" " those who are familiar with less and lynx.\n" "\n" "o Press <E>, <X>, <q>, <Enter> or <Esc><Esc> to exit.\n" "\n" "\n" "Alternate Configuration Files\n" "-----------------------------\n" "Menuconfig supports the use of alternate configuration files for\n" "those who, for various reasons, find it necessary to switch\n" "between different configurations.\n" "\n" "The <Save> button will let you save the current configuration to\n" "a file of your choosing. Use the <Load> button to load a previously\n" "saved alternate configuration.\n" "\n" "Even if you don't use alternate configuration files, but you find\n" "during a Menuconfig session that you have completely messed up your\n" "settings, you may use the <Load> button to restore your previously\n" "saved settings from \".config\" without restarting Menuconfig.\n" "\n" "Other information\n" "-----------------\n" "If you use Menuconfig in an XTERM window, make sure you have your\n" "$TERM variable set to point to an xterm definition which supports\n" "color. Otherwise, Menuconfig will look rather bad. Menuconfig will\n" "not display correctly in an RXVT window because rxvt displays only one\n" "intensity of color, bright.\n" "\n" "Menuconfig will display larger menus on screens or xterms which are\n" "set to display more than the standard 25 row by 80 column geometry.\n" "In order for this to work, the \"stty size\" command must be able to\n" "display the screen's current row and column geometry. I STRONGLY\n" "RECOMMEND that you make sure you do NOT have the shell variables\n" "LINES and COLUMNS exported into your environment. Some distributions\n" "export those variables via /etc/profile. Some ncurses programs can\n" "become confused when those variables (LINES & COLUMNS) don't reflect\n" "the true screen size.\n" "\n" "Optional personality available\n" "------------------------------\n" "If you prefer to have all of the options listed in a single menu,\n" "rather than the default multimenu hierarchy, run the menuconfig with\n" "MENUCONFIG_MODE environment variable set to single_menu. Example:\n" "\n" "make MENUCONFIG_MODE=single_menu menuconfig\n" "\n" "<Enter> will then unroll the appropriate category, or enfold it if it\n" "is already unrolled.\n" "\n" "Note that this mode can eventually be a little more CPU expensive\n" "(especially with a larger number of unrolled categories) than the\n" "default mode.\n" "\n" "Search\n" "-------\n" "Pressing the forward-slash (/) anywhere brings up a search dialog box.\n" "\n" "Different color themes available\n" "--------------------------------\n" "It is possible to select different color themes using the variable\n" "MENUCONFIG_COLOR. To select a theme use:\n" "\n" "make MENUCONFIG_COLOR=<theme> menuconfig\n" "\n" "Available themes are\n" " mono => selects colors suitable for monochrome displays\n" " blackbg => selects a color scheme with black background\n" " classic => theme with blue background. The classic look\n" " bluetitle => an LCD friendly version of classic. (default)\n" "\n", menu_instructions[] = "Arrow keys navigate the menu. " "<Enter> selects submenus ---> (or empty submenus ----). " "Highlighted letters are hotkeys. " "Pressing <Y> includes, <N> excludes, <M> modularizes features. " "Press <Esc><Esc> to exit, <?> for Help, </> for Search. " "Legend: [*] built-in [ ] excluded <M> module < > module capable", radiolist_instructions[] = "Use the arrow keys to navigate this window or " "press the hotkey of the item you wish to select " "followed by the <SPACE BAR>. " "Press <?> for additional information about this option.", inputbox_instructions_int[] = "Please enter a decimal value. " "Fractions will not be accepted. " "Use the <TAB> key to move from the input field to the buttons below it.", inputbox_instructions_hex[] = "Please enter a hexadecimal value. " "Use the <TAB> key to move from the input field to the buttons below it.", inputbox_instructions_string[] = "Please enter a string value. " "Use the <TAB> key to move from the input field to the buttons below it.", setmod_text[] = "This feature depends on another which has been configured as a module.\n" "As a result, this feature will be built as a module.", load_config_text[] = "Enter the name of the configuration file you wish to load. " "Accept the name shown to restore the configuration you " "last retrieved. Leave blank to abort.", load_config_help[] = "\n" "For various reasons, one may wish to keep several different\n" "configurations available on a single machine.\n" "\n" "If you have saved a previous configuration in a file other than the\n" "default one, entering its name here will allow you to modify that\n" "configuration.\n" "\n" "If you are uncertain, then you have probably never used alternate\n" "configuration files. You should therefore leave this blank to abort.\n", save_config_text[] = "Enter a filename to which this configuration should be saved " "as an alternate. Leave blank to abort.", save_config_help[] = "\n" "For various reasons, one may wish to keep different configurations\n" "available on a single machine.\n" "\n" "Entering a file name here will allow you to later retrieve, modify\n" "and use the current configuration as an alternate to whatever\n" "configuration options you have selected at that time.\n" "\n" "If you are uncertain what all this means then you should probably\n" "leave this blank.\n", search_help[] = "\n" "Search for symbols and display their relations.\n" "Regular expressions are allowed.\n" "Example: search for \"^FOO\"\n" "Result:\n" "-----------------------------------------------------------------\n" "Symbol: FOO [=m]\n" "Type : tristate\n" "Prompt: Foo bus is used to drive the bar HW\n" " Location:\n" " -> Bus options (PCI, PCMCIA, EISA, ISA)\n" " -> PCI support (PCI [=y])\n" "(1) -> PCI access mode (<choice> [=y])\n" " Defined at drivers/pci/Kconfig:47\n" " Depends on: X86_LOCAL_APIC && X86_IO_APIC || IA64\n" " Selects: LIBCRC32\n" " Selected by: BAR [=n]\n" "-----------------------------------------------------------------\n" "o The line 'Type:' shows the type of the configuration option for\n" " this symbol (bool, tristate, string, ...)\n" "o The line 'Prompt:' shows the text used in the menu structure for\n" " this symbol\n" "o The 'Defined at' line tells at what file / line number the symbol\n" " is defined\n" "o The 'Depends on:' line tells what symbols need to be defined for\n" " this symbol to be visible in the menu (selectable)\n" "o The 'Location:' lines tells where in the menu structure this symbol\n" " is located\n" " A location followed by a [=y] indicates that this is a\n" " selectable menu item - and the current value is displayed inside\n" " brackets.\n" " Press the key in the (#) prefix to jump directly to that\n" " location. You will be returned to the current search results\n" " after exiting this new menu.\n" "o The 'Selects:' line tells what symbols will be automatically\n" " selected if this symbol is selected (y or m)\n" "o The 'Selected by' line tells what symbol has selected this symbol\n" "\n" "Only relevant lines are shown.\n" "\n\n" "Search examples:\n" "Examples: USB => find all symbols containing USB\n" " ^USB => find all symbols starting with USB\n" " USB$ => find all symbols ending with USB\n" "\n"; static int indent; static struct menu *current_menu; static int child_count; static int single_menu_mode; static int show_all_options; static int save_and_exit; static int silent; static int jump_key_char; static void conf(struct menu *menu, struct menu *active_menu); static char filename[PATH_MAX+1]; static void set_config_filename(const char *config_filename) { static char menu_backtitle[PATH_MAX+128]; snprintf(menu_backtitle, sizeof(menu_backtitle), "%s - %s", config_filename, rootmenu.prompt->text); set_dialog_backtitle(menu_backtitle); snprintf(filename, sizeof(filename), "%s", config_filename); } struct subtitle_part { struct list_head entries; const char *text; }; static LIST_HEAD(trail); static struct subtitle_list *subtitles; static void set_subtitle(void) { struct subtitle_part *sp; struct subtitle_list *pos, *tmp; for (pos = subtitles; pos != NULL; pos = tmp) { tmp = pos->next; free(pos); } subtitles = NULL; list_for_each_entry(sp, &trail, entries) { if (sp->text) { if (pos) { pos->next = xcalloc(1, sizeof(*pos)); pos = pos->next; } else { subtitles = pos = xcalloc(1, sizeof(*pos)); } pos->text = sp->text; } } set_dialog_subtitles(subtitles); } static void reset_subtitle(void) { struct subtitle_list *pos, *tmp; for (pos = subtitles; pos != NULL; pos = tmp) { tmp = pos->next; free(pos); } subtitles = NULL; set_dialog_subtitles(subtitles); } static int show_textbox_ext(const char *title, const char *text, int r, int c, int *vscroll, int *hscroll, int (*extra_key_cb)(int, size_t, size_t, void *), void *data) { dialog_clear(); return dialog_textbox(title, text, r, c, vscroll, hscroll, extra_key_cb, data); } static void show_textbox(const char *title, const char *text, int r, int c) { show_textbox_ext(title, text, r, c, NULL, NULL, NULL, NULL); } static void show_helptext(const char *title, const char *text) { show_textbox(title, text, 0, 0); } static void show_help(struct menu *menu) { struct gstr help = str_new(); help.max_width = getmaxx(stdscr) - 10; menu_get_ext_help(menu, &help); show_helptext(menu_get_prompt(menu), str_get(&help)); str_free(&help); } struct search_data { struct list_head *head; struct menu *target; }; static int next_jump_key(int key) { if (key < '1' || key > '9') return '1'; key++; if (key > '9') key = '1'; return key; } static int handle_search_keys(int key, size_t start, size_t end, void *_data) { struct search_data *data = _data; struct jump_key *pos; int index = 0; if (key < '1' || key > '9') return 0; list_for_each_entry(pos, data->head, entries) { index = next_jump_key(index); if (pos->offset < start) continue; if (pos->offset >= end) break; if (key == index) { data->target = pos->target; return 1; } } return 0; } int get_jump_key_char(void) { jump_key_char = next_jump_key(jump_key_char); return jump_key_char; } static void search_conf(void) { struct symbol **sym_arr; struct gstr res; struct gstr title; char *dialog_input; int dres, vscroll = 0, hscroll = 0; bool again; struct gstr sttext; struct subtitle_part stpart; title = str_new(); str_printf( &title, "Enter (sub)string or regexp to search for " "(with or without \"%s\")", CONFIG_); again: dialog_clear(); dres = dialog_inputbox("Search Configuration Parameter", str_get(&title), 10, 75, ""); switch (dres) { case 0: break; case 1: show_helptext("Search Configuration", search_help); goto again; default: str_free(&title); return; } /* strip the prefix if necessary */ dialog_input = dialog_input_result; if (strncasecmp(dialog_input_result, CONFIG_, strlen(CONFIG_)) == 0) dialog_input += strlen(CONFIG_); sttext = str_new(); str_printf(&sttext, "Search (%s)", dialog_input_result); stpart.text = str_get(&sttext); list_add_tail(&stpart.entries, &trail); sym_arr = sym_re_search(dialog_input); do { LIST_HEAD(head); struct search_data data = { .head = &head, }; struct jump_key *pos, *tmp; jump_key_char = 0; res = get_relations_str(sym_arr, &head); set_subtitle(); dres = show_textbox_ext("Search Results", str_get(&res), 0, 0, &vscroll, &hscroll, handle_search_keys, &data); again = false; if (dres >= '1' && dres <= '9') { assert(data.target != NULL); conf(data.target->parent, data.target); again = true; } str_free(&res); list_for_each_entry_safe(pos, tmp, &head, entries) free(pos); } while (again); free(sym_arr); str_free(&title); list_del(trail.prev); str_free(&sttext); } static void build_conf(struct menu *menu) { struct symbol *sym; struct property *prop; struct menu *child; int type, tmp, doint = 2; tristate val; char ch; bool visible; /* * note: menu_is_visible() has side effect that it will * recalc the value of the symbol. */ visible = menu_is_visible(menu); if (show_all_options && !menu_has_prompt(menu)) return; else if (!show_all_options && !visible) return; sym = menu->sym; prop = menu->prompt; if (!sym) { if (prop && menu != current_menu) { const char *prompt = menu_get_prompt(menu); switch (prop->type) { case P_MENU: child_count++; if (single_menu_mode) { item_make("%s%*c%s", menu->data ? "-->" : "++>", indent + 1, ' ', prompt); } else item_make(" %*c%s %s", indent + 1, ' ', prompt, menu_is_empty(menu) ? "----" : "--->"); item_set_tag('m'); item_set_data(menu); if (single_menu_mode && menu->data) goto conf_childs; return; case P_COMMENT: if (prompt) { child_count++; item_make(" %*c*** %s ***", indent + 1, ' ', prompt); item_set_tag(':'); item_set_data(menu); } break; default: if (prompt) { child_count++; item_make("---%*c%s", indent + 1, ' ', prompt); item_set_tag(':'); item_set_data(menu); } } } else doint = 0; goto conf_childs; } type = sym_get_type(sym); if (sym_is_choice(sym)) { struct symbol *def_sym = sym_get_choice_value(sym); struct menu *def_menu = NULL; child_count++; for (child = menu->list; child; child = child->next) { if (menu_is_visible(child) && child->sym == def_sym) def_menu = child; } val = sym_get_tristate_value(sym); if (sym_is_changeable(sym)) { switch (type) { case S_BOOLEAN: item_make("[%c]", val == no ? ' ' : '*'); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } item_make("<%c>", ch); break; } item_set_tag('t'); item_set_data(menu); } else { item_make(" "); item_set_tag(def_menu ? 't' : ':'); item_set_data(menu); } item_add_str("%*c%s", indent + 1, ' ', menu_get_prompt(menu)); if (val == yes) { if (def_menu) { item_add_str(" (%s)", menu_get_prompt(def_menu)); item_add_str(" --->"); if (def_menu->list) { indent += 2; build_conf(def_menu); indent -= 2; } } return; } } else { if (menu == current_menu) { item_make("---%*c%s", indent + 1, ' ', menu_get_prompt(menu)); item_set_tag(':'); item_set_data(menu); goto conf_childs; } child_count++; val = sym_get_tristate_value(sym); if (sym_is_choice_value(sym) && val == yes) { item_make(" "); item_set_tag(':'); item_set_data(menu); } else { switch (type) { case S_BOOLEAN: if (sym_is_changeable(sym)) item_make("[%c]", val == no ? ' ' : '*'); else item_make("-%c-", val == no ? ' ' : '*'); item_set_tag('t'); item_set_data(menu); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } if (sym_is_changeable(sym)) { if (sym->rev_dep.tri == mod) item_make("{%c}", ch); else item_make("<%c>", ch); } else item_make("-%c-", ch); item_set_tag('t'); item_set_data(menu); break; default: tmp = 2 + strlen(sym_get_string_value(sym)); /* () = 2 */ item_make("(%s)", sym_get_string_value(sym)); tmp = indent - tmp + 4; if (tmp < 0) tmp = 0; item_add_str("%*c%s%s", tmp, ' ', menu_get_prompt(menu), (sym_has_value(sym) || !sym_is_changeable(sym)) ? "" : " (NEW)"); item_set_tag('s'); item_set_data(menu); goto conf_childs; } } item_add_str("%*c%s%s", indent + 1, ' ', menu_get_prompt(menu), (sym_has_value(sym) || !sym_is_changeable(sym)) ? "" : " (NEW)"); if (menu->prompt->type == P_MENU) { item_add_str(" %s", menu_is_empty(menu) ? "----" : "--->"); return; } } conf_childs: indent += doint; for (child = menu->list; child; child = child->next) build_conf(child); indent -= doint; } static void conf_choice(struct menu *menu) { const char *prompt = menu_get_prompt(menu); struct menu *child; struct symbol *active; active = sym_get_choice_value(menu->sym); while (1) { int res; int selected; item_reset(); current_menu = menu; for (child = menu->list; child; child = child->next) { if (!menu_is_visible(child)) continue; if (child->sym) item_make("%s", menu_get_prompt(child)); else { item_make("*** %s ***", menu_get_prompt(child)); item_set_tag(':'); } item_set_data(child); if (child->sym == active) item_set_selected(1); if (child->sym == sym_get_choice_value(menu->sym)) item_set_tag('X'); } dialog_clear(); res = dialog_checklist(prompt ? prompt : "Main Menu", radiolist_instructions, MENUBOX_HEIGTH_MIN, MENUBOX_WIDTH_MIN, CHECKLIST_HEIGTH_MIN); selected = item_activate_selected(); switch (res) { case 0: if (selected) { child = item_data(); if (!child->sym) break; sym_set_tristate_value(child->sym, yes); } return; case 1: if (selected) { child = item_data(); show_help(child); active = child->sym; } else show_help(menu); break; case KEY_ESC: return; case -ERRDISPLAYTOOSMALL: return; } } } static void conf_string(struct menu *menu) { const char *prompt = menu_get_prompt(menu); while (1) { int res; const char *heading; switch (sym_get_type(menu->sym)) { case S_INT: heading = inputbox_instructions_int; break; case S_HEX: heading = inputbox_instructions_hex; break; case S_STRING: heading = inputbox_instructions_string; break; default: heading = "Internal mconf error!"; } dialog_clear(); res = dialog_inputbox(prompt ? prompt : "Main Menu", heading, 10, 75, sym_get_string_value(menu->sym)); switch (res) { case 0: if (sym_set_string_value(menu->sym, dialog_input_result)) return; show_textbox(NULL, "You have made an invalid entry.", 5, 43); break; case 1: show_help(menu); break; case KEY_ESC: return; } } } static void conf_load(void) { while (1) { int res; dialog_clear(); res = dialog_inputbox(NULL, load_config_text, 11, 55, filename); switch(res) { case 0: if (!dialog_input_result[0]) return; if (!conf_read(dialog_input_result)) { set_config_filename(dialog_input_result); conf_set_changed(true); return; } show_textbox(NULL, "File does not exist!", 5, 38); break; case 1: show_helptext("Load Alternate Configuration", load_config_help); break; case KEY_ESC: return; } } } static void conf_save(void) { while (1) { int res; dialog_clear(); res = dialog_inputbox(NULL, save_config_text, 11, 55, filename); switch(res) { case 0: if (!dialog_input_result[0]) return; if (!conf_write(dialog_input_result)) { set_config_filename(dialog_input_result); return; } show_textbox(NULL, "Can't create file!", 5, 60); break; case 1: show_helptext("Save Alternate Configuration", save_config_help); break; case KEY_ESC: return; } } } static void conf(struct menu *menu, struct menu *active_menu) { struct menu *submenu; const char *prompt = menu_get_prompt(menu); struct subtitle_part stpart; struct symbol *sym; int res; int s_scroll = 0; if (menu != &rootmenu) stpart.text = menu_get_prompt(menu); else stpart.text = NULL; list_add_tail(&stpart.entries, &trail); while (1) { item_reset(); current_menu = menu; build_conf(menu); if (!child_count) break; set_subtitle(); dialog_clear(); res = dialog_menu(prompt ? prompt : "Main Menu", menu_instructions, active_menu, &s_scroll); if (res == 1 || res == KEY_ESC || res == -ERRDISPLAYTOOSMALL) break; if (item_count() != 0) { if (!item_activate_selected()) continue; if (!item_tag()) continue; } submenu = item_data(); active_menu = item_data(); if (submenu) sym = submenu->sym; else sym = NULL; switch (res) { case 0: switch (item_tag()) { case 'm': if (single_menu_mode) submenu->data = (void *) (long) !submenu->data; else conf(submenu, NULL); break; case 't': if (sym_is_choice(sym) && sym_get_tristate_value(sym) == yes) conf_choice(submenu); else if (submenu->prompt->type == P_MENU) conf(submenu, NULL); break; case 's': conf_string(submenu); break; } break; case 2: if (sym) show_help(submenu); else { reset_subtitle(); show_helptext("README", mconf_readme); } break; case 3: reset_subtitle(); conf_save(); break; case 4: reset_subtitle(); conf_load(); break; case 5: if (item_is_tag('t')) { if (sym_set_tristate_value(sym, yes)) break; if (sym_set_tristate_value(sym, mod)) show_textbox(NULL, setmod_text, 6, 74); } break; case 6: if (item_is_tag('t')) sym_set_tristate_value(sym, no); break; case 7: if (item_is_tag('t')) sym_set_tristate_value(sym, mod); break; case 8: if (item_is_tag('t')) sym_toggle_tristate_value(sym); else if (item_is_tag('m')) conf(submenu, NULL); break; case 9: search_conf(); break; case 10: show_all_options = !show_all_options; break; } } list_del(trail.prev); } static void conf_message_callback(const char *s) { if (save_and_exit) { if (!silent) printf("%s", s); } else { show_textbox(NULL, s, 6, 60); } } static int handle_exit(void) { int res; save_and_exit = 1; reset_subtitle(); dialog_clear(); if (conf_get_changed()) res = dialog_yesno(NULL, "Do you wish to save your new configuration?\n" "(Press <ESC><ESC> to continue kernel configuration.)", 6, 60); else res = -1; end_dialog(saved_x, saved_y); switch (res) { case 0: if (conf_write(filename)) { fprintf(stderr, "\n\n" "Error while writing of the configuration.\n" "Your configuration changes were NOT saved." "\n\n"); return 1; } conf_write_autoconf(0); /* fall through */ case -1: if (!silent) printf("\n\n" "*** End of the configuration.\n" "*** Execute 'make' to start the build or try 'make help'." "\n\n"); res = 0; break; default: if (!silent) fprintf(stderr, "\n\n" "Your configuration changes were NOT saved." "\n\n"); if (res != KEY_ESC) res = 0; } return res; } static void sig_handler(int signo) { exit(handle_exit()); } int main(int ac, char **av) { char *mode; int res; signal(SIGINT, sig_handler); if (ac > 1 && strcmp(av[1], "-s") == 0) { silent = 1; /* Silence conf_read() until the real callback is set up */ conf_set_message_callback(NULL); av++; } conf_parse(av[1]); conf_read(NULL); mode = getenv("MENUCONFIG_MODE"); if (mode) { if (!strcasecmp(mode, "single_menu")) single_menu_mode = 1; } if (init_dialog(NULL)) { fprintf(stderr, "Your display is too small to run Menuconfig!\n"); fprintf(stderr, "It must be at least 19 lines by 80 columns.\n"); return 1; } set_config_filename(conf_get_configname()); conf_set_message_callback(conf_message_callback); do { conf(&rootmenu, NULL); res = handle_exit(); } while (res == KEY_ESC); return res; }
linux-master
scripts/kconfig/mconf.c
// SPDX-License-Identifier: GPL-2.0 // // Copyright (C) 2018 Masahiro Yamada <[email protected]> #include <ctype.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "list.h" #include "lkc.h" #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) static char *expand_string_with_args(const char *in, int argc, char *argv[]); static char *expand_string(const char *in); static void __attribute__((noreturn)) pperror(const char *format, ...) { va_list ap; fprintf(stderr, "%s:%d: ", current_file->name, yylineno); va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); fprintf(stderr, "\n"); exit(1); } /* * Environment variables */ static LIST_HEAD(env_list); struct env { char *name; char *value; struct list_head node; }; static void env_add(const char *name, const char *value) { struct env *e; e = xmalloc(sizeof(*e)); e->name = xstrdup(name); e->value = xstrdup(value); list_add_tail(&e->node, &env_list); } static void env_del(struct env *e) { list_del(&e->node); free(e->name); free(e->value); free(e); } /* The returned pointer must be freed when done */ static char *env_expand(const char *name) { struct env *e; const char *value; if (!*name) return NULL; list_for_each_entry(e, &env_list, node) { if (!strcmp(name, e->name)) return xstrdup(e->value); } value = getenv(name); if (!value) return NULL; /* * We need to remember all referenced environment variables. * They will be written out to include/config/auto.conf.cmd */ env_add(name, value); return xstrdup(value); } void env_write_dep(FILE *f, const char *autoconfig_name) { struct env *e, *tmp; list_for_each_entry_safe(e, tmp, &env_list, node) { fprintf(f, "ifneq \"$(%s)\" \"%s\"\n", e->name, e->value); fprintf(f, "%s: FORCE\n", autoconfig_name); fprintf(f, "endif\n"); env_del(e); } } /* * Built-in functions */ struct function { const char *name; unsigned int min_args; unsigned int max_args; char *(*func)(int argc, char *argv[]); }; static char *do_error_if(int argc, char *argv[]) { if (!strcmp(argv[0], "y")) pperror("%s", argv[1]); return xstrdup(""); } static char *do_filename(int argc, char *argv[]) { return xstrdup(current_file->name); } static char *do_info(int argc, char *argv[]) { printf("%s\n", argv[0]); return xstrdup(""); } static char *do_lineno(int argc, char *argv[]) { char buf[16]; sprintf(buf, "%d", yylineno); return xstrdup(buf); } static char *do_shell(int argc, char *argv[]) { FILE *p; char buf[4096]; char *cmd; size_t nread; int i; cmd = argv[0]; p = popen(cmd, "r"); if (!p) { perror(cmd); exit(1); } nread = fread(buf, 1, sizeof(buf), p); if (nread == sizeof(buf)) nread--; /* remove trailing new lines */ while (nread > 0 && buf[nread - 1] == '\n') nread--; buf[nread] = 0; /* replace a new line with a space */ for (i = 0; i < nread; i++) { if (buf[i] == '\n') buf[i] = ' '; } if (pclose(p) == -1) { perror(cmd); exit(1); } return xstrdup(buf); } static char *do_warning_if(int argc, char *argv[]) { if (!strcmp(argv[0], "y")) fprintf(stderr, "%s:%d: %s\n", current_file->name, yylineno, argv[1]); return xstrdup(""); } static const struct function function_table[] = { /* Name MIN MAX Function */ { "error-if", 2, 2, do_error_if }, { "filename", 0, 0, do_filename }, { "info", 1, 1, do_info }, { "lineno", 0, 0, do_lineno }, { "shell", 1, 1, do_shell }, { "warning-if", 2, 2, do_warning_if }, }; #define FUNCTION_MAX_ARGS 16 static char *function_expand(const char *name, int argc, char *argv[]) { const struct function *f; int i; for (i = 0; i < ARRAY_SIZE(function_table); i++) { f = &function_table[i]; if (strcmp(f->name, name)) continue; if (argc < f->min_args) pperror("too few function arguments passed to '%s'", name); if (argc > f->max_args) pperror("too many function arguments passed to '%s'", name); return f->func(argc, argv); } return NULL; } /* * Variables (and user-defined functions) */ static LIST_HEAD(variable_list); struct variable { char *name; char *value; enum variable_flavor flavor; int exp_count; struct list_head node; }; static struct variable *variable_lookup(const char *name) { struct variable *v; list_for_each_entry(v, &variable_list, node) { if (!strcmp(name, v->name)) return v; } return NULL; } static char *variable_expand(const char *name, int argc, char *argv[]) { struct variable *v; char *res; v = variable_lookup(name); if (!v) return NULL; if (argc == 0 && v->exp_count) pperror("Recursive variable '%s' references itself (eventually)", name); if (v->exp_count > 1000) pperror("Too deep recursive expansion"); v->exp_count++; if (v->flavor == VAR_RECURSIVE) res = expand_string_with_args(v->value, argc, argv); else res = xstrdup(v->value); v->exp_count--; return res; } void variable_add(const char *name, const char *value, enum variable_flavor flavor) { struct variable *v; char *new_value; bool append = false; v = variable_lookup(name); if (v) { /* For defined variables, += inherits the existing flavor */ if (flavor == VAR_APPEND) { flavor = v->flavor; append = true; } else { free(v->value); } } else { /* For undefined variables, += assumes the recursive flavor */ if (flavor == VAR_APPEND) flavor = VAR_RECURSIVE; v = xmalloc(sizeof(*v)); v->name = xstrdup(name); v->exp_count = 0; list_add_tail(&v->node, &variable_list); } v->flavor = flavor; if (flavor == VAR_SIMPLE) new_value = expand_string(value); else new_value = xstrdup(value); if (append) { v->value = xrealloc(v->value, strlen(v->value) + strlen(new_value) + 2); strcat(v->value, " "); strcat(v->value, new_value); free(new_value); } else { v->value = new_value; } } static void variable_del(struct variable *v) { list_del(&v->node); free(v->name); free(v->value); free(v); } void variable_all_del(void) { struct variable *v, *tmp; list_for_each_entry_safe(v, tmp, &variable_list, node) variable_del(v); } /* * Evaluate a clause with arguments. argc/argv are arguments from the upper * function call. * * Returned string must be freed when done */ static char *eval_clause(const char *str, size_t len, int argc, char *argv[]) { char *tmp, *name, *res, *endptr, *prev, *p; int new_argc = 0; char *new_argv[FUNCTION_MAX_ARGS]; int nest = 0; int i; unsigned long n; tmp = xstrndup(str, len); /* * If variable name is '1', '2', etc. It is generally an argument * from a user-function call (i.e. local-scope variable). If not * available, then look-up global-scope variables. */ n = strtoul(tmp, &endptr, 10); if (!*endptr && n > 0 && n <= argc) { res = xstrdup(argv[n - 1]); goto free_tmp; } prev = p = tmp; /* * Split into tokens * The function name and arguments are separated by a comma. * For example, if the function call is like this: * $(foo,$(x),$(y)) * * The input string for this helper should be: * foo,$(x),$(y) * * and split into: * new_argv[0] = 'foo' * new_argv[1] = '$(x)' * new_argv[2] = '$(y)' */ while (*p) { if (nest == 0 && *p == ',') { *p = 0; if (new_argc >= FUNCTION_MAX_ARGS) pperror("too many function arguments"); new_argv[new_argc++] = prev; prev = p + 1; } else if (*p == '(') { nest++; } else if (*p == ')') { nest--; } p++; } if (new_argc >= FUNCTION_MAX_ARGS) pperror("too many function arguments"); new_argv[new_argc++] = prev; /* * Shift arguments * new_argv[0] represents a function name or a variable name. Put it * into 'name', then shift the rest of the arguments. This simplifies * 'const' handling. */ name = expand_string_with_args(new_argv[0], argc, argv); new_argc--; for (i = 0; i < new_argc; i++) new_argv[i] = expand_string_with_args(new_argv[i + 1], argc, argv); /* Search for variables */ res = variable_expand(name, new_argc, new_argv); if (res) goto free; /* Look for built-in functions */ res = function_expand(name, new_argc, new_argv); if (res) goto free; /* Last, try environment variable */ if (new_argc == 0) { res = env_expand(name); if (res) goto free; } res = xstrdup(""); free: for (i = 0; i < new_argc; i++) free(new_argv[i]); free(name); free_tmp: free(tmp); return res; } /* * Expand a string that follows '$' * * For example, if the input string is * ($(FOO)$($(BAR)))$(BAZ) * this helper evaluates * $($(FOO)$($(BAR))) * and returns a new string containing the expansion (note that the string is * recursively expanded), also advancing 'str' to point to the next character * after the corresponding closing parenthesis, in this case, *str will be * $(BAR) */ static char *expand_dollar_with_args(const char **str, int argc, char *argv[]) { const char *p = *str; const char *q; int nest = 0; /* * In Kconfig, variable/function references always start with "$(". * Neither single-letter variables as in $A nor curly braces as in ${CC} * are supported. '$' not followed by '(' loses its special meaning. */ if (*p != '(') { *str = p; return xstrdup("$"); } p++; q = p; while (*q) { if (*q == '(') { nest++; } else if (*q == ')') { if (nest-- == 0) break; } q++; } if (!*q) pperror("unterminated reference to '%s': missing ')'", p); /* Advance 'str' to after the expanded initial portion of the string */ *str = q + 1; return eval_clause(p, q - p, argc, argv); } char *expand_dollar(const char **str) { return expand_dollar_with_args(str, 0, NULL); } static char *__expand_string(const char **str, bool (*is_end)(char c), int argc, char *argv[]) { const char *in, *p; char *expansion, *out; size_t in_len, out_len; out = xmalloc(1); *out = 0; out_len = 1; p = in = *str; while (1) { if (*p == '$') { in_len = p - in; p++; expansion = expand_dollar_with_args(&p, argc, argv); out_len += in_len + strlen(expansion); out = xrealloc(out, out_len); strncat(out, in, in_len); strcat(out, expansion); free(expansion); in = p; continue; } if (is_end(*p)) break; p++; } in_len = p - in; out_len += in_len; out = xrealloc(out, out_len); strncat(out, in, in_len); /* Advance 'str' to the end character */ *str = p; return out; } static bool is_end_of_str(char c) { return !c; } /* * Expand variables and functions in the given string. Undefined variables * expand to an empty string. * The returned string must be freed when done. */ static char *expand_string_with_args(const char *in, int argc, char *argv[]) { return __expand_string(&in, is_end_of_str, argc, argv); } static char *expand_string(const char *in) { return expand_string_with_args(in, 0, NULL); } static bool is_end_of_token(char c) { return !(isalnum(c) || c == '_' || c == '-'); } /* * Expand variables in a token. The parsing stops when a token separater * (in most cases, it is a whitespace) is encountered. 'str' is updated to * point to the next character. * * The returned string must be freed when done. */ char *expand_one_token(const char **str) { return __expand_string(str, is_end_of_token, 0, NULL); }
linux-master
scripts/kconfig/preprocess.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include <sys/types.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <regex.h> #include "lkc.h" struct symbol symbol_yes = { .name = "y", .curr = { "y", yes }, .flags = SYMBOL_CONST|SYMBOL_VALID, }; struct symbol symbol_mod = { .name = "m", .curr = { "m", mod }, .flags = SYMBOL_CONST|SYMBOL_VALID, }; struct symbol symbol_no = { .name = "n", .curr = { "n", no }, .flags = SYMBOL_CONST|SYMBOL_VALID, }; static struct symbol symbol_empty = { .name = "", .curr = { "", no }, .flags = SYMBOL_VALID, }; struct symbol *modules_sym; static tristate modules_val; enum symbol_type sym_get_type(struct symbol *sym) { enum symbol_type type = sym->type; if (type == S_TRISTATE) { if (sym_is_choice_value(sym) && sym->visible == yes) type = S_BOOLEAN; else if (modules_val == no) type = S_BOOLEAN; } return type; } const char *sym_type_name(enum symbol_type type) { switch (type) { case S_BOOLEAN: return "bool"; case S_TRISTATE: return "tristate"; case S_INT: return "integer"; case S_HEX: return "hex"; case S_STRING: return "string"; case S_UNKNOWN: return "unknown"; } return "???"; } struct property *sym_get_choice_prop(struct symbol *sym) { struct property *prop; for_all_choices(sym, prop) return prop; return NULL; } static struct property *sym_get_default_prop(struct symbol *sym) { struct property *prop; for_all_defaults(sym, prop) { prop->visible.tri = expr_calc_value(prop->visible.expr); if (prop->visible.tri != no) return prop; } return NULL; } struct property *sym_get_range_prop(struct symbol *sym) { struct property *prop; for_all_properties(sym, prop, P_RANGE) { prop->visible.tri = expr_calc_value(prop->visible.expr); if (prop->visible.tri != no) return prop; } return NULL; } static long long sym_get_range_val(struct symbol *sym, int base) { sym_calc_value(sym); switch (sym->type) { case S_INT: base = 10; break; case S_HEX: base = 16; break; default: break; } return strtoll(sym->curr.val, NULL, base); } static void sym_validate_range(struct symbol *sym) { struct property *prop; int base; long long val, val2; char str[64]; switch (sym->type) { case S_INT: base = 10; break; case S_HEX: base = 16; break; default: return; } prop = sym_get_range_prop(sym); if (!prop) return; val = strtoll(sym->curr.val, NULL, base); val2 = sym_get_range_val(prop->expr->left.sym, base); if (val >= val2) { val2 = sym_get_range_val(prop->expr->right.sym, base); if (val <= val2) return; } if (sym->type == S_INT) sprintf(str, "%lld", val2); else sprintf(str, "0x%llx", val2); sym->curr.val = xstrdup(str); } static void sym_set_changed(struct symbol *sym) { struct property *prop; sym->flags |= SYMBOL_CHANGED; for (prop = sym->prop; prop; prop = prop->next) { if (prop->menu) prop->menu->flags |= MENU_CHANGED; } } static void sym_set_all_changed(void) { struct symbol *sym; int i; for_all_symbols(i, sym) sym_set_changed(sym); } static void sym_calc_visibility(struct symbol *sym) { struct property *prop; struct symbol *choice_sym = NULL; tristate tri; /* any prompt visible? */ tri = no; if (sym_is_choice_value(sym)) choice_sym = prop_get_symbol(sym_get_choice_prop(sym)); for_all_prompts(sym, prop) { prop->visible.tri = expr_calc_value(prop->visible.expr); /* * Tristate choice_values with visibility 'mod' are * not visible if the corresponding choice's value is * 'yes'. */ if (choice_sym && sym->type == S_TRISTATE && prop->visible.tri == mod && choice_sym->curr.tri == yes) prop->visible.tri = no; tri = EXPR_OR(tri, prop->visible.tri); } if (tri == mod && (sym->type != S_TRISTATE || modules_val == no)) tri = yes; if (sym->visible != tri) { sym->visible = tri; sym_set_changed(sym); } if (sym_is_choice_value(sym)) return; /* defaulting to "yes" if no explicit "depends on" are given */ tri = yes; if (sym->dir_dep.expr) tri = expr_calc_value(sym->dir_dep.expr); if (tri == mod && sym_get_type(sym) == S_BOOLEAN) tri = yes; if (sym->dir_dep.tri != tri) { sym->dir_dep.tri = tri; sym_set_changed(sym); } tri = no; if (sym->rev_dep.expr) tri = expr_calc_value(sym->rev_dep.expr); if (tri == mod && sym_get_type(sym) == S_BOOLEAN) tri = yes; if (sym->rev_dep.tri != tri) { sym->rev_dep.tri = tri; sym_set_changed(sym); } tri = no; if (sym->implied.expr) tri = expr_calc_value(sym->implied.expr); if (tri == mod && sym_get_type(sym) == S_BOOLEAN) tri = yes; if (sym->implied.tri != tri) { sym->implied.tri = tri; sym_set_changed(sym); } } /* * Find the default symbol for a choice. * First try the default values for the choice symbol * Next locate the first visible choice value * Return NULL if none was found */ struct symbol *sym_choice_default(struct symbol *sym) { struct symbol *def_sym; struct property *prop; struct expr *e; /* any of the defaults visible? */ for_all_defaults(sym, prop) { prop->visible.tri = expr_calc_value(prop->visible.expr); if (prop->visible.tri == no) continue; def_sym = prop_get_symbol(prop); if (def_sym->visible != no) return def_sym; } /* just get the first visible value */ prop = sym_get_choice_prop(sym); expr_list_for_each_sym(prop->expr, e, def_sym) if (def_sym->visible != no) return def_sym; /* failed to locate any defaults */ return NULL; } static struct symbol *sym_calc_choice(struct symbol *sym) { struct symbol *def_sym; struct property *prop; struct expr *e; int flags; /* first calculate all choice values' visibilities */ flags = sym->flags; prop = sym_get_choice_prop(sym); expr_list_for_each_sym(prop->expr, e, def_sym) { sym_calc_visibility(def_sym); if (def_sym->visible != no) flags &= def_sym->flags; } sym->flags &= flags | ~SYMBOL_DEF_USER; /* is the user choice visible? */ def_sym = sym->def[S_DEF_USER].val; if (def_sym && def_sym->visible != no) return def_sym; def_sym = sym_choice_default(sym); if (def_sym == NULL) /* no choice? reset tristate value */ sym->curr.tri = no; return def_sym; } static void sym_warn_unmet_dep(struct symbol *sym) { struct gstr gs = str_new(); str_printf(&gs, "\nWARNING: unmet direct dependencies detected for %s\n", sym->name); str_printf(&gs, " Depends on [%c]: ", sym->dir_dep.tri == mod ? 'm' : 'n'); expr_gstr_print(sym->dir_dep.expr, &gs); str_printf(&gs, "\n"); expr_gstr_print_revdep(sym->rev_dep.expr, &gs, yes, " Selected by [y]:\n"); expr_gstr_print_revdep(sym->rev_dep.expr, &gs, mod, " Selected by [m]:\n"); fputs(str_get(&gs), stderr); } void sym_calc_value(struct symbol *sym) { struct symbol_value newval, oldval; struct property *prop; struct expr *e; if (!sym) return; if (sym->flags & SYMBOL_VALID) return; if (sym_is_choice_value(sym) && sym->flags & SYMBOL_NEED_SET_CHOICE_VALUES) { sym->flags &= ~SYMBOL_NEED_SET_CHOICE_VALUES; prop = sym_get_choice_prop(sym); sym_calc_value(prop_get_symbol(prop)); } sym->flags |= SYMBOL_VALID; oldval = sym->curr; switch (sym->type) { case S_INT: case S_HEX: case S_STRING: newval = symbol_empty.curr; break; case S_BOOLEAN: case S_TRISTATE: newval = symbol_no.curr; break; default: sym->curr.val = sym->name; sym->curr.tri = no; return; } sym->flags &= ~SYMBOL_WRITE; sym_calc_visibility(sym); if (sym->visible != no) sym->flags |= SYMBOL_WRITE; /* set default if recursively called */ sym->curr = newval; switch (sym_get_type(sym)) { case S_BOOLEAN: case S_TRISTATE: if (sym_is_choice_value(sym) && sym->visible == yes) { prop = sym_get_choice_prop(sym); newval.tri = (prop_get_symbol(prop)->curr.val == sym) ? yes : no; } else { if (sym->visible != no) { /* if the symbol is visible use the user value * if available, otherwise try the default value */ if (sym_has_value(sym)) { newval.tri = EXPR_AND(sym->def[S_DEF_USER].tri, sym->visible); goto calc_newval; } } if (sym->rev_dep.tri != no) sym->flags |= SYMBOL_WRITE; if (!sym_is_choice(sym)) { prop = sym_get_default_prop(sym); if (prop) { newval.tri = EXPR_AND(expr_calc_value(prop->expr), prop->visible.tri); if (newval.tri != no) sym->flags |= SYMBOL_WRITE; } if (sym->implied.tri != no) { sym->flags |= SYMBOL_WRITE; newval.tri = EXPR_OR(newval.tri, sym->implied.tri); newval.tri = EXPR_AND(newval.tri, sym->dir_dep.tri); } } calc_newval: if (sym->dir_dep.tri < sym->rev_dep.tri) sym_warn_unmet_dep(sym); newval.tri = EXPR_OR(newval.tri, sym->rev_dep.tri); } if (newval.tri == mod && sym_get_type(sym) == S_BOOLEAN) newval.tri = yes; break; case S_STRING: case S_HEX: case S_INT: if (sym->visible != no && sym_has_value(sym)) { newval.val = sym->def[S_DEF_USER].val; break; } prop = sym_get_default_prop(sym); if (prop) { struct symbol *ds = prop_get_symbol(prop); if (ds) { sym->flags |= SYMBOL_WRITE; sym_calc_value(ds); newval.val = ds->curr.val; } } break; default: ; } sym->curr = newval; if (sym_is_choice(sym) && newval.tri == yes) sym->curr.val = sym_calc_choice(sym); sym_validate_range(sym); if (memcmp(&oldval, &sym->curr, sizeof(oldval))) { sym_set_changed(sym); if (modules_sym == sym) { sym_set_all_changed(); modules_val = modules_sym->curr.tri; } } if (sym_is_choice(sym)) { struct symbol *choice_sym; prop = sym_get_choice_prop(sym); expr_list_for_each_sym(prop->expr, e, choice_sym) { if ((sym->flags & SYMBOL_WRITE) && choice_sym->visible != no) choice_sym->flags |= SYMBOL_WRITE; if (sym->flags & SYMBOL_CHANGED) sym_set_changed(choice_sym); } } if (sym->flags & SYMBOL_NO_WRITE) sym->flags &= ~SYMBOL_WRITE; if (sym->flags & SYMBOL_NEED_SET_CHOICE_VALUES) set_all_choice_values(sym); } void sym_clear_all_valid(void) { struct symbol *sym; int i; for_all_symbols(i, sym) sym->flags &= ~SYMBOL_VALID; conf_set_changed(true); sym_calc_value(modules_sym); } bool sym_tristate_within_range(struct symbol *sym, tristate val) { int type = sym_get_type(sym); if (sym->visible == no) return false; if (type != S_BOOLEAN && type != S_TRISTATE) return false; if (type == S_BOOLEAN && val == mod) return false; if (sym->visible <= sym->rev_dep.tri) return false; if (sym_is_choice_value(sym) && sym->visible == yes) return val == yes; return val >= sym->rev_dep.tri && val <= sym->visible; } bool sym_set_tristate_value(struct symbol *sym, tristate val) { tristate oldval = sym_get_tristate_value(sym); if (oldval != val && !sym_tristate_within_range(sym, val)) return false; if (!(sym->flags & SYMBOL_DEF_USER)) { sym->flags |= SYMBOL_DEF_USER; sym_set_changed(sym); } /* * setting a choice value also resets the new flag of the choice * symbol and all other choice values. */ if (sym_is_choice_value(sym) && val == yes) { struct symbol *cs = prop_get_symbol(sym_get_choice_prop(sym)); struct property *prop; struct expr *e; cs->def[S_DEF_USER].val = sym; cs->flags |= SYMBOL_DEF_USER; prop = sym_get_choice_prop(cs); for (e = prop->expr; e; e = e->left.expr) { if (e->right.sym->visible != no) e->right.sym->flags |= SYMBOL_DEF_USER; } } sym->def[S_DEF_USER].tri = val; if (oldval != val) sym_clear_all_valid(); return true; } tristate sym_toggle_tristate_value(struct symbol *sym) { tristate oldval, newval; oldval = newval = sym_get_tristate_value(sym); do { switch (newval) { case no: newval = mod; break; case mod: newval = yes; break; case yes: newval = no; break; } if (sym_set_tristate_value(sym, newval)) break; } while (oldval != newval); return newval; } bool sym_string_valid(struct symbol *sym, const char *str) { signed char ch; switch (sym->type) { case S_STRING: return true; case S_INT: ch = *str++; if (ch == '-') ch = *str++; if (!isdigit(ch)) return false; if (ch == '0' && *str != 0) return false; while ((ch = *str++)) { if (!isdigit(ch)) return false; } return true; case S_HEX: if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) str += 2; ch = *str++; do { if (!isxdigit(ch)) return false; } while ((ch = *str++)); return true; case S_BOOLEAN: case S_TRISTATE: switch (str[0]) { case 'y': case 'Y': case 'm': case 'M': case 'n': case 'N': return true; } return false; default: return false; } } bool sym_string_within_range(struct symbol *sym, const char *str) { struct property *prop; long long val; switch (sym->type) { case S_STRING: return sym_string_valid(sym, str); case S_INT: if (!sym_string_valid(sym, str)) return false; prop = sym_get_range_prop(sym); if (!prop) return true; val = strtoll(str, NULL, 10); return val >= sym_get_range_val(prop->expr->left.sym, 10) && val <= sym_get_range_val(prop->expr->right.sym, 10); case S_HEX: if (!sym_string_valid(sym, str)) return false; prop = sym_get_range_prop(sym); if (!prop) return true; val = strtoll(str, NULL, 16); return val >= sym_get_range_val(prop->expr->left.sym, 16) && val <= sym_get_range_val(prop->expr->right.sym, 16); case S_BOOLEAN: case S_TRISTATE: switch (str[0]) { case 'y': case 'Y': return sym_tristate_within_range(sym, yes); case 'm': case 'M': return sym_tristate_within_range(sym, mod); case 'n': case 'N': return sym_tristate_within_range(sym, no); } return false; default: return false; } } bool sym_set_string_value(struct symbol *sym, const char *newval) { const char *oldval; char *val; int size; switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: switch (newval[0]) { case 'y': case 'Y': return sym_set_tristate_value(sym, yes); case 'm': case 'M': return sym_set_tristate_value(sym, mod); case 'n': case 'N': return sym_set_tristate_value(sym, no); } return false; default: ; } if (!sym_string_within_range(sym, newval)) return false; if (!(sym->flags & SYMBOL_DEF_USER)) { sym->flags |= SYMBOL_DEF_USER; sym_set_changed(sym); } oldval = sym->def[S_DEF_USER].val; size = strlen(newval) + 1; if (sym->type == S_HEX && (newval[0] != '0' || (newval[1] != 'x' && newval[1] != 'X'))) { size += 2; sym->def[S_DEF_USER].val = val = xmalloc(size); *val++ = '0'; *val++ = 'x'; } else if (!oldval || strcmp(oldval, newval)) sym->def[S_DEF_USER].val = val = xmalloc(size); else return true; strcpy(val, newval); free((void *)oldval); sym_clear_all_valid(); return true; } /* * Find the default value associated to a symbol. * For tristate symbol handle the modules=n case * in which case "m" becomes "y". * If the symbol does not have any default then fallback * to the fixed default values. */ const char *sym_get_string_default(struct symbol *sym) { struct property *prop; struct symbol *ds; const char *str; tristate val; sym_calc_visibility(sym); sym_calc_value(modules_sym); val = symbol_no.curr.tri; str = symbol_empty.curr.val; /* If symbol has a default value look it up */ prop = sym_get_default_prop(sym); if (prop != NULL) { switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: /* The visibility may limit the value from yes => mod */ val = EXPR_AND(expr_calc_value(prop->expr), prop->visible.tri); break; default: /* * The following fails to handle the situation * where a default value is further limited by * the valid range. */ ds = prop_get_symbol(prop); if (ds != NULL) { sym_calc_value(ds); str = (const char *)ds->curr.val; } } } /* Handle select statements */ val = EXPR_OR(val, sym->rev_dep.tri); /* transpose mod to yes if modules are not enabled */ if (val == mod) if (!sym_is_choice_value(sym) && modules_sym->curr.tri == no) val = yes; /* transpose mod to yes if type is bool */ if (sym->type == S_BOOLEAN && val == mod) val = yes; /* adjust the default value if this symbol is implied by another */ if (val < sym->implied.tri) val = sym->implied.tri; switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: switch (val) { case no: return "n"; case mod: return "m"; case yes: return "y"; } case S_INT: case S_HEX: return str; case S_STRING: return str; case S_UNKNOWN: break; } return ""; } const char *sym_get_string_value(struct symbol *sym) { tristate val; switch (sym->type) { case S_BOOLEAN: case S_TRISTATE: val = sym_get_tristate_value(sym); switch (val) { case no: return "n"; case mod: sym_calc_value(modules_sym); return (modules_sym->curr.tri == no) ? "n" : "m"; case yes: return "y"; } break; default: ; } return (const char *)sym->curr.val; } bool sym_is_changeable(struct symbol *sym) { return sym->visible > sym->rev_dep.tri; } static unsigned strhash(const char *s) { /* fnv32 hash */ unsigned hash = 2166136261U; for (; *s; s++) hash = (hash ^ *s) * 0x01000193; return hash; } struct symbol *sym_lookup(const char *name, int flags) { struct symbol *symbol; char *new_name; int hash; if (name) { if (name[0] && !name[1]) { switch (name[0]) { case 'y': return &symbol_yes; case 'm': return &symbol_mod; case 'n': return &symbol_no; } } hash = strhash(name) % SYMBOL_HASHSIZE; for (symbol = symbol_hash[hash]; symbol; symbol = symbol->next) { if (symbol->name && !strcmp(symbol->name, name) && (flags ? symbol->flags & flags : !(symbol->flags & (SYMBOL_CONST|SYMBOL_CHOICE)))) return symbol; } new_name = xstrdup(name); } else { new_name = NULL; hash = 0; } symbol = xmalloc(sizeof(*symbol)); memset(symbol, 0, sizeof(*symbol)); symbol->name = new_name; symbol->type = S_UNKNOWN; symbol->flags = flags; symbol->next = symbol_hash[hash]; symbol_hash[hash] = symbol; return symbol; } struct symbol *sym_find(const char *name) { struct symbol *symbol = NULL; int hash = 0; if (!name) return NULL; if (name[0] && !name[1]) { switch (name[0]) { case 'y': return &symbol_yes; case 'm': return &symbol_mod; case 'n': return &symbol_no; } } hash = strhash(name) % SYMBOL_HASHSIZE; for (symbol = symbol_hash[hash]; symbol; symbol = symbol->next) { if (symbol->name && !strcmp(symbol->name, name) && !(symbol->flags & SYMBOL_CONST)) break; } return symbol; } struct sym_match { struct symbol *sym; off_t so, eo; }; /* Compare matched symbols as thus: * - first, symbols that match exactly * - then, alphabetical sort */ static int sym_rel_comp(const void *sym1, const void *sym2) { const struct sym_match *s1 = sym1; const struct sym_match *s2 = sym2; int exact1, exact2; /* Exact match: * - if matched length on symbol s1 is the length of that symbol, * then this symbol should come first; * - if matched length on symbol s2 is the length of that symbol, * then this symbol should come first. * Note: since the search can be a regexp, both symbols may match * exactly; if this is the case, we can't decide which comes first, * and we fallback to sorting alphabetically. */ exact1 = (s1->eo - s1->so) == strlen(s1->sym->name); exact2 = (s2->eo - s2->so) == strlen(s2->sym->name); if (exact1 && !exact2) return -1; if (!exact1 && exact2) return 1; /* As a fallback, sort symbols alphabetically */ return strcmp(s1->sym->name, s2->sym->name); } struct symbol **sym_re_search(const char *pattern) { struct symbol *sym, **sym_arr = NULL; struct sym_match *sym_match_arr = NULL; int i, cnt, size; regex_t re; regmatch_t match[1]; cnt = size = 0; /* Skip if empty */ if (strlen(pattern) == 0) return NULL; if (regcomp(&re, pattern, REG_EXTENDED|REG_ICASE)) return NULL; for_all_symbols(i, sym) { if (sym->flags & SYMBOL_CONST || !sym->name) continue; if (regexec(&re, sym->name, 1, match, 0)) continue; if (cnt >= size) { void *tmp; size += 16; tmp = realloc(sym_match_arr, size * sizeof(struct sym_match)); if (!tmp) goto sym_re_search_free; sym_match_arr = tmp; } sym_calc_value(sym); /* As regexec returned 0, we know we have a match, so * we can use match[0].rm_[se]o without further checks */ sym_match_arr[cnt].so = match[0].rm_so; sym_match_arr[cnt].eo = match[0].rm_eo; sym_match_arr[cnt++].sym = sym; } if (sym_match_arr) { qsort(sym_match_arr, cnt, sizeof(struct sym_match), sym_rel_comp); sym_arr = malloc((cnt+1) * sizeof(struct symbol *)); if (!sym_arr) goto sym_re_search_free; for (i = 0; i < cnt; i++) sym_arr[i] = sym_match_arr[i].sym; sym_arr[cnt] = NULL; } sym_re_search_free: /* sym_match_arr can be NULL if no match, but free(NULL) is OK */ free(sym_match_arr); regfree(&re); return sym_arr; } /* * When we check for recursive dependencies we use a stack to save * current state so we can print out relevant info to user. * The entries are located on the call stack so no need to free memory. * Note insert() remove() must always match to properly clear the stack. */ static struct dep_stack { struct dep_stack *prev, *next; struct symbol *sym; struct property *prop; struct expr **expr; } *check_top; static void dep_stack_insert(struct dep_stack *stack, struct symbol *sym) { memset(stack, 0, sizeof(*stack)); if (check_top) check_top->next = stack; stack->prev = check_top; stack->sym = sym; check_top = stack; } static void dep_stack_remove(void) { check_top = check_top->prev; if (check_top) check_top->next = NULL; } /* * Called when we have detected a recursive dependency. * check_top point to the top of the stact so we use * the ->prev pointer to locate the bottom of the stack. */ static void sym_check_print_recursive(struct symbol *last_sym) { struct dep_stack *stack; struct symbol *sym, *next_sym; struct menu *menu = NULL; struct property *prop; struct dep_stack cv_stack; if (sym_is_choice_value(last_sym)) { dep_stack_insert(&cv_stack, last_sym); last_sym = prop_get_symbol(sym_get_choice_prop(last_sym)); } for (stack = check_top; stack != NULL; stack = stack->prev) if (stack->sym == last_sym) break; if (!stack) { fprintf(stderr, "unexpected recursive dependency error\n"); return; } for (; stack; stack = stack->next) { sym = stack->sym; next_sym = stack->next ? stack->next->sym : last_sym; prop = stack->prop; if (prop == NULL) prop = stack->sym->prop; /* for choice values find the menu entry (used below) */ if (sym_is_choice(sym) || sym_is_choice_value(sym)) { for (prop = sym->prop; prop; prop = prop->next) { menu = prop->menu; if (prop->menu) break; } } if (stack->sym == last_sym) fprintf(stderr, "%s:%d:error: recursive dependency detected!\n", prop->file->name, prop->lineno); if (sym_is_choice(sym)) { fprintf(stderr, "%s:%d:\tchoice %s contains symbol %s\n", menu->file->name, menu->lineno, sym->name ? sym->name : "<choice>", next_sym->name ? next_sym->name : "<choice>"); } else if (sym_is_choice_value(sym)) { fprintf(stderr, "%s:%d:\tsymbol %s is part of choice %s\n", menu->file->name, menu->lineno, sym->name ? sym->name : "<choice>", next_sym->name ? next_sym->name : "<choice>"); } else if (stack->expr == &sym->dir_dep.expr) { fprintf(stderr, "%s:%d:\tsymbol %s depends on %s\n", prop->file->name, prop->lineno, sym->name ? sym->name : "<choice>", next_sym->name ? next_sym->name : "<choice>"); } else if (stack->expr == &sym->rev_dep.expr) { fprintf(stderr, "%s:%d:\tsymbol %s is selected by %s\n", prop->file->name, prop->lineno, sym->name ? sym->name : "<choice>", next_sym->name ? next_sym->name : "<choice>"); } else if (stack->expr == &sym->implied.expr) { fprintf(stderr, "%s:%d:\tsymbol %s is implied by %s\n", prop->file->name, prop->lineno, sym->name ? sym->name : "<choice>", next_sym->name ? next_sym->name : "<choice>"); } else if (stack->expr) { fprintf(stderr, "%s:%d:\tsymbol %s %s value contains %s\n", prop->file->name, prop->lineno, sym->name ? sym->name : "<choice>", prop_get_type_name(prop->type), next_sym->name ? next_sym->name : "<choice>"); } else { fprintf(stderr, "%s:%d:\tsymbol %s %s is visible depending on %s\n", prop->file->name, prop->lineno, sym->name ? sym->name : "<choice>", prop_get_type_name(prop->type), next_sym->name ? next_sym->name : "<choice>"); } } fprintf(stderr, "For a resolution refer to Documentation/kbuild/kconfig-language.rst\n" "subsection \"Kconfig recursive dependency limitations\"\n" "\n"); if (check_top == &cv_stack) dep_stack_remove(); } static struct symbol *sym_check_expr_deps(struct expr *e) { struct symbol *sym; if (!e) return NULL; switch (e->type) { case E_OR: case E_AND: sym = sym_check_expr_deps(e->left.expr); if (sym) return sym; return sym_check_expr_deps(e->right.expr); case E_NOT: return sym_check_expr_deps(e->left.expr); case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: sym = sym_check_deps(e->left.sym); if (sym) return sym; return sym_check_deps(e->right.sym); case E_SYMBOL: return sym_check_deps(e->left.sym); default: break; } fprintf(stderr, "Oops! How to check %d?\n", e->type); return NULL; } /* return NULL when dependencies are OK */ static struct symbol *sym_check_sym_deps(struct symbol *sym) { struct symbol *sym2; struct property *prop; struct dep_stack stack; dep_stack_insert(&stack, sym); stack.expr = &sym->dir_dep.expr; sym2 = sym_check_expr_deps(sym->dir_dep.expr); if (sym2) goto out; stack.expr = &sym->rev_dep.expr; sym2 = sym_check_expr_deps(sym->rev_dep.expr); if (sym2) goto out; stack.expr = &sym->implied.expr; sym2 = sym_check_expr_deps(sym->implied.expr); if (sym2) goto out; stack.expr = NULL; for (prop = sym->prop; prop; prop = prop->next) { if (prop->type == P_CHOICE || prop->type == P_SELECT || prop->type == P_IMPLY) continue; stack.prop = prop; sym2 = sym_check_expr_deps(prop->visible.expr); if (sym2) break; if (prop->type != P_DEFAULT || sym_is_choice(sym)) continue; stack.expr = &prop->expr; sym2 = sym_check_expr_deps(prop->expr); if (sym2) break; stack.expr = NULL; } out: dep_stack_remove(); return sym2; } static struct symbol *sym_check_choice_deps(struct symbol *choice) { struct symbol *sym, *sym2; struct property *prop; struct expr *e; struct dep_stack stack; dep_stack_insert(&stack, choice); prop = sym_get_choice_prop(choice); expr_list_for_each_sym(prop->expr, e, sym) sym->flags |= (SYMBOL_CHECK | SYMBOL_CHECKED); choice->flags |= (SYMBOL_CHECK | SYMBOL_CHECKED); sym2 = sym_check_sym_deps(choice); choice->flags &= ~SYMBOL_CHECK; if (sym2) goto out; expr_list_for_each_sym(prop->expr, e, sym) { sym2 = sym_check_sym_deps(sym); if (sym2) break; } out: expr_list_for_each_sym(prop->expr, e, sym) sym->flags &= ~SYMBOL_CHECK; if (sym2 && sym_is_choice_value(sym2) && prop_get_symbol(sym_get_choice_prop(sym2)) == choice) sym2 = choice; dep_stack_remove(); return sym2; } struct symbol *sym_check_deps(struct symbol *sym) { struct symbol *sym2; struct property *prop; if (sym->flags & SYMBOL_CHECK) { sym_check_print_recursive(sym); return sym; } if (sym->flags & SYMBOL_CHECKED) return NULL; if (sym_is_choice_value(sym)) { struct dep_stack stack; /* for choice groups start the check with main choice symbol */ dep_stack_insert(&stack, sym); prop = sym_get_choice_prop(sym); sym2 = sym_check_deps(prop_get_symbol(prop)); dep_stack_remove(); } else if (sym_is_choice(sym)) { sym2 = sym_check_choice_deps(sym); } else { sym->flags |= (SYMBOL_CHECK | SYMBOL_CHECKED); sym2 = sym_check_sym_deps(sym); sym->flags &= ~SYMBOL_CHECK; } return sym2; } struct symbol *prop_get_symbol(struct property *prop) { if (prop->expr && (prop->expr->type == E_SYMBOL || prop->expr->type == E_LIST)) return prop->expr->left.sym; return NULL; } const char *prop_get_type_name(enum prop_type type) { switch (type) { case P_PROMPT: return "prompt"; case P_COMMENT: return "comment"; case P_MENU: return "menu"; case P_DEFAULT: return "default"; case P_CHOICE: return "choice"; case P_SELECT: return "select"; case P_IMPLY: return "imply"; case P_RANGE: return "range"; case P_SYMBOL: return "symbol"; case P_UNKNOWN: break; } return "unknown"; }
linux-master
scripts/kconfig/symbol.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include <ctype.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <sys/time.h> #include <errno.h> #include "lkc.h" static void conf(struct menu *menu); static void check_conf(struct menu *menu); enum input_mode { oldaskconfig, syncconfig, oldconfig, allnoconfig, allyesconfig, allmodconfig, alldefconfig, randconfig, defconfig, savedefconfig, listnewconfig, helpnewconfig, olddefconfig, yes2modconfig, mod2yesconfig, mod2noconfig, }; static enum input_mode input_mode = oldaskconfig; static int input_mode_opt; static int indent = 1; static int tty_stdio; static int sync_kconfig; static int conf_cnt; static char line[PATH_MAX]; static struct menu *rootEntry; static void print_help(struct menu *menu) { struct gstr help = str_new(); menu_get_ext_help(menu, &help); printf("\n%s\n", str_get(&help)); str_free(&help); } static void strip(char *str) { char *p = str; int l; while ((isspace(*p))) p++; l = strlen(p); if (p != str) memmove(str, p, l + 1); if (!l) return; p = str + l - 1; while ((isspace(*p))) *p-- = 0; } /* Helper function to facilitate fgets() by Jean Sacren. */ static void xfgets(char *str, int size, FILE *in) { if (!fgets(str, size, in)) fprintf(stderr, "\nError in reading or end of file.\n"); if (!tty_stdio) printf("%s", str); } static void set_randconfig_seed(void) { unsigned int seed; char *env; bool seed_set = false; env = getenv("KCONFIG_SEED"); if (env && *env) { char *endp; seed = strtol(env, &endp, 0); if (*endp == '\0') seed_set = true; } if (!seed_set) { struct timeval now; /* * Use microseconds derived seed, compensate for systems where it may * be zero. */ gettimeofday(&now, NULL); seed = (now.tv_sec + 1) * (now.tv_usec + 1); } printf("KCONFIG_SEED=0x%X\n", seed); srand(seed); } static bool randomize_choice_values(struct symbol *csym) { struct property *prop; struct symbol *sym; struct expr *e; int cnt, def; /* * If choice is mod then we may have more items selected * and if no then no-one. * In both cases stop. */ if (csym->curr.tri != yes) return false; prop = sym_get_choice_prop(csym); /* count entries in choice block */ cnt = 0; expr_list_for_each_sym(prop->expr, e, sym) cnt++; /* * find a random value and set it to yes, * set the rest to no so we have only one set */ def = rand() % cnt; cnt = 0; expr_list_for_each_sym(prop->expr, e, sym) { if (def == cnt++) { sym->def[S_DEF_USER].tri = yes; csym->def[S_DEF_USER].val = sym; } else { sym->def[S_DEF_USER].tri = no; } sym->flags |= SYMBOL_DEF_USER; /* clear VALID to get value calculated */ sym->flags &= ~SYMBOL_VALID; } csym->flags |= SYMBOL_DEF_USER; /* clear VALID to get value calculated */ csym->flags &= ~SYMBOL_VALID; return true; } enum conf_def_mode { def_default, def_yes, def_mod, def_no, def_random }; static bool conf_set_all_new_symbols(enum conf_def_mode mode) { struct symbol *sym, *csym; int i, cnt; /* * can't go as the default in switch-case below, otherwise gcc whines * about -Wmaybe-uninitialized */ int pby = 50; /* probability of bool = y */ int pty = 33; /* probability of tristate = y */ int ptm = 33; /* probability of tristate = m */ bool has_changed = false; if (mode == def_random) { int n, p[3]; char *env = getenv("KCONFIG_PROBABILITY"); n = 0; while (env && *env) { char *endp; int tmp = strtol(env, &endp, 10); if (tmp >= 0 && tmp <= 100) { p[n++] = tmp; } else { errno = ERANGE; perror("KCONFIG_PROBABILITY"); exit(1); } env = (*endp == ':') ? endp + 1 : endp; if (n >= 3) break; } switch (n) { case 1: pby = p[0]; ptm = pby / 2; pty = pby - ptm; break; case 2: pty = p[0]; ptm = p[1]; pby = pty + ptm; break; case 3: pby = p[0]; pty = p[1]; ptm = p[2]; break; } if (pty + ptm > 100) { errno = ERANGE; perror("KCONFIG_PROBABILITY"); exit(1); } } for_all_symbols(i, sym) { if (sym_has_value(sym) || sym->flags & SYMBOL_VALID) continue; switch (sym_get_type(sym)) { case S_BOOLEAN: case S_TRISTATE: has_changed = true; switch (mode) { case def_yes: sym->def[S_DEF_USER].tri = yes; break; case def_mod: sym->def[S_DEF_USER].tri = mod; break; case def_no: sym->def[S_DEF_USER].tri = no; break; case def_random: sym->def[S_DEF_USER].tri = no; cnt = rand() % 100; if (sym->type == S_TRISTATE) { if (cnt < pty) sym->def[S_DEF_USER].tri = yes; else if (cnt < pty + ptm) sym->def[S_DEF_USER].tri = mod; } else if (cnt < pby) sym->def[S_DEF_USER].tri = yes; break; default: continue; } if (!(sym_is_choice(sym) && mode == def_random)) sym->flags |= SYMBOL_DEF_USER; break; default: break; } } sym_clear_all_valid(); /* * We have different type of choice blocks. * If curr.tri equals to mod then we can select several * choice symbols in one block. * In this case we do nothing. * If curr.tri equals yes then only one symbol can be * selected in a choice block and we set it to yes, * and the rest to no. */ if (mode != def_random) { for_all_symbols(i, csym) { if ((sym_is_choice(csym) && !sym_has_value(csym)) || sym_is_choice_value(csym)) csym->flags |= SYMBOL_NEED_SET_CHOICE_VALUES; } } for_all_symbols(i, csym) { if (sym_has_value(csym) || !sym_is_choice(csym)) continue; sym_calc_value(csym); if (mode == def_random) has_changed |= randomize_choice_values(csym); else { set_all_choice_values(csym); has_changed = true; } } return has_changed; } static void conf_rewrite_tristates(tristate old_val, tristate new_val) { struct symbol *sym; int i; for_all_symbols(i, sym) { if (sym_get_type(sym) == S_TRISTATE && sym->def[S_DEF_USER].tri == old_val) sym->def[S_DEF_USER].tri = new_val; } sym_clear_all_valid(); } static int conf_askvalue(struct symbol *sym, const char *def) { if (!sym_has_value(sym)) printf("(NEW) "); line[0] = '\n'; line[1] = 0; if (!sym_is_changeable(sym)) { printf("%s\n", def); line[0] = '\n'; line[1] = 0; return 0; } switch (input_mode) { case oldconfig: case syncconfig: if (sym_has_value(sym)) { printf("%s\n", def); return 0; } /* fall through */ default: fflush(stdout); xfgets(line, sizeof(line), stdin); break; } return 1; } static int conf_string(struct menu *menu) { struct symbol *sym = menu->sym; const char *def; while (1) { printf("%*s%s ", indent - 1, "", menu->prompt->text); printf("(%s) ", sym->name); def = sym_get_string_value(sym); if (def) printf("[%s] ", def); if (!conf_askvalue(sym, def)) return 0; switch (line[0]) { case '\n': break; case '?': /* print help */ if (line[1] == '\n') { print_help(menu); def = NULL; break; } /* fall through */ default: line[strlen(line)-1] = 0; def = line; } if (def && sym_set_string_value(sym, def)) return 0; } } static int conf_sym(struct menu *menu) { struct symbol *sym = menu->sym; tristate oldval, newval; while (1) { printf("%*s%s ", indent - 1, "", menu->prompt->text); if (sym->name) printf("(%s) ", sym->name); putchar('['); oldval = sym_get_tristate_value(sym); switch (oldval) { case no: putchar('N'); break; case mod: putchar('M'); break; case yes: putchar('Y'); break; } if (oldval != no && sym_tristate_within_range(sym, no)) printf("/n"); if (oldval != mod && sym_tristate_within_range(sym, mod)) printf("/m"); if (oldval != yes && sym_tristate_within_range(sym, yes)) printf("/y"); printf("/?] "); if (!conf_askvalue(sym, sym_get_string_value(sym))) return 0; strip(line); switch (line[0]) { case 'n': case 'N': newval = no; if (!line[1] || !strcmp(&line[1], "o")) break; continue; case 'm': case 'M': newval = mod; if (!line[1]) break; continue; case 'y': case 'Y': newval = yes; if (!line[1] || !strcmp(&line[1], "es")) break; continue; case 0: newval = oldval; break; case '?': goto help; default: continue; } if (sym_set_tristate_value(sym, newval)) return 0; help: print_help(menu); } } static int conf_choice(struct menu *menu) { struct symbol *sym, *def_sym; struct menu *child; bool is_new; sym = menu->sym; is_new = !sym_has_value(sym); if (sym_is_changeable(sym)) { conf_sym(menu); sym_calc_value(sym); switch (sym_get_tristate_value(sym)) { case no: return 1; case mod: return 0; case yes: break; } } else { switch (sym_get_tristate_value(sym)) { case no: return 1; case mod: printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu)); return 0; case yes: break; } } while (1) { int cnt, def; printf("%*s%s\n", indent - 1, "", menu_get_prompt(menu)); def_sym = sym_get_choice_value(sym); cnt = def = 0; line[0] = 0; for (child = menu->list; child; child = child->next) { if (!menu_is_visible(child)) continue; if (!child->sym) { printf("%*c %s\n", indent, '*', menu_get_prompt(child)); continue; } cnt++; if (child->sym == def_sym) { def = cnt; printf("%*c", indent, '>'); } else printf("%*c", indent, ' '); printf(" %d. %s", cnt, menu_get_prompt(child)); if (child->sym->name) printf(" (%s)", child->sym->name); if (!sym_has_value(child->sym)) printf(" (NEW)"); printf("\n"); } printf("%*schoice", indent - 1, ""); if (cnt == 1) { printf("[1]: 1\n"); goto conf_childs; } printf("[1-%d?]: ", cnt); switch (input_mode) { case oldconfig: case syncconfig: if (!is_new) { cnt = def; printf("%d\n", cnt); break; } /* fall through */ case oldaskconfig: fflush(stdout); xfgets(line, sizeof(line), stdin); strip(line); if (line[0] == '?') { print_help(menu); continue; } if (!line[0]) cnt = def; else if (isdigit(line[0])) cnt = atoi(line); else continue; break; default: break; } conf_childs: for (child = menu->list; child; child = child->next) { if (!child->sym || !menu_is_visible(child)) continue; if (!--cnt) break; } if (!child) continue; if (line[0] && line[strlen(line) - 1] == '?') { print_help(child); continue; } sym_set_tristate_value(child->sym, yes); for (child = child->list; child; child = child->next) { indent += 2; conf(child); indent -= 2; } return 1; } } static void conf(struct menu *menu) { struct symbol *sym; struct property *prop; struct menu *child; if (!menu_is_visible(menu)) return; sym = menu->sym; prop = menu->prompt; if (prop) { const char *prompt; switch (prop->type) { case P_MENU: /* * Except in oldaskconfig mode, we show only menus that * contain new symbols. */ if (input_mode != oldaskconfig && rootEntry != menu) { check_conf(menu); return; } /* fall through */ case P_COMMENT: prompt = menu_get_prompt(menu); if (prompt) printf("%*c\n%*c %s\n%*c\n", indent, '*', indent, '*', prompt, indent, '*'); default: ; } } if (!sym) goto conf_childs; if (sym_is_choice(sym)) { conf_choice(menu); if (sym->curr.tri != mod) return; goto conf_childs; } switch (sym->type) { case S_INT: case S_HEX: case S_STRING: conf_string(menu); break; default: conf_sym(menu); break; } conf_childs: if (sym) indent += 2; for (child = menu->list; child; child = child->next) conf(child); if (sym) indent -= 2; } static void check_conf(struct menu *menu) { struct symbol *sym; struct menu *child; if (!menu_is_visible(menu)) return; sym = menu->sym; if (sym && !sym_has_value(sym) && (sym_is_changeable(sym) || (sym_is_choice(sym) && sym_get_tristate_value(sym) == yes))) { switch (input_mode) { case listnewconfig: if (sym->name) print_symbol_for_listconfig(sym); break; case helpnewconfig: printf("-----\n"); print_help(menu); printf("-----\n"); break; default: if (!conf_cnt++) printf("*\n* Restart config...\n*\n"); rootEntry = menu_get_parent_menu(menu); conf(rootEntry); break; } } for (child = menu->list; child; child = child->next) check_conf(child); } static const struct option long_opts[] = { {"help", no_argument, NULL, 'h'}, {"silent", no_argument, NULL, 's'}, {"oldaskconfig", no_argument, &input_mode_opt, oldaskconfig}, {"oldconfig", no_argument, &input_mode_opt, oldconfig}, {"syncconfig", no_argument, &input_mode_opt, syncconfig}, {"defconfig", required_argument, &input_mode_opt, defconfig}, {"savedefconfig", required_argument, &input_mode_opt, savedefconfig}, {"allnoconfig", no_argument, &input_mode_opt, allnoconfig}, {"allyesconfig", no_argument, &input_mode_opt, allyesconfig}, {"allmodconfig", no_argument, &input_mode_opt, allmodconfig}, {"alldefconfig", no_argument, &input_mode_opt, alldefconfig}, {"randconfig", no_argument, &input_mode_opt, randconfig}, {"listnewconfig", no_argument, &input_mode_opt, listnewconfig}, {"helpnewconfig", no_argument, &input_mode_opt, helpnewconfig}, {"olddefconfig", no_argument, &input_mode_opt, olddefconfig}, {"yes2modconfig", no_argument, &input_mode_opt, yes2modconfig}, {"mod2yesconfig", no_argument, &input_mode_opt, mod2yesconfig}, {"mod2noconfig", no_argument, &input_mode_opt, mod2noconfig}, {NULL, 0, NULL, 0} }; static void conf_usage(const char *progname) { printf("Usage: %s [options] <kconfig-file>\n", progname); printf("\n"); printf("Generic options:\n"); printf(" -h, --help Print this message and exit.\n"); printf(" -s, --silent Do not print log.\n"); printf("\n"); printf("Mode options:\n"); printf(" --listnewconfig List new options\n"); printf(" --helpnewconfig List new options and help text\n"); printf(" --oldaskconfig Start a new configuration using a line-oriented program\n"); printf(" --oldconfig Update a configuration using a provided .config as base\n"); printf(" --syncconfig Similar to oldconfig but generates configuration in\n" " include/{generated/,config/}\n"); printf(" --olddefconfig Same as oldconfig but sets new symbols to their default value\n"); printf(" --defconfig <file> New config with default defined in <file>\n"); printf(" --savedefconfig <file> Save the minimal current configuration to <file>\n"); printf(" --allnoconfig New config where all options are answered with no\n"); printf(" --allyesconfig New config where all options are answered with yes\n"); printf(" --allmodconfig New config where all options are answered with mod\n"); printf(" --alldefconfig New config with all symbols set to default\n"); printf(" --randconfig New config with random answer to all options\n"); printf(" --yes2modconfig Change answers from yes to mod if possible\n"); printf(" --mod2yesconfig Change answers from mod to yes if possible\n"); printf(" --mod2noconfig Change answers from mod to no if possible\n"); printf(" (If none of the above is given, --oldaskconfig is the default)\n"); } int main(int ac, char **av) { const char *progname = av[0]; int opt; const char *name, *defconfig_file = NULL /* gcc uninit */; int no_conf_write = 0; tty_stdio = isatty(0) && isatty(1); while ((opt = getopt_long(ac, av, "hs", long_opts, NULL)) != -1) { switch (opt) { case 'h': conf_usage(progname); exit(1); break; case 's': conf_set_message_callback(NULL); break; case 0: input_mode = input_mode_opt; switch (input_mode) { case syncconfig: /* * syncconfig is invoked during the build stage. * Suppress distracting * "configuration written to ..." */ conf_set_message_callback(NULL); sync_kconfig = 1; break; case defconfig: case savedefconfig: defconfig_file = optarg; break; case randconfig: set_randconfig_seed(); break; default: break; } default: break; } } if (ac == optind) { fprintf(stderr, "%s: Kconfig file missing\n", av[0]); conf_usage(progname); exit(1); } conf_parse(av[optind]); //zconfdump(stdout); switch (input_mode) { case defconfig: if (conf_read(defconfig_file)) { fprintf(stderr, "***\n" "*** Can't find default configuration \"%s\"!\n" "***\n", defconfig_file); exit(1); } break; case savedefconfig: case syncconfig: case oldaskconfig: case oldconfig: case listnewconfig: case helpnewconfig: case olddefconfig: case yes2modconfig: case mod2yesconfig: case mod2noconfig: conf_read(NULL); break; case allnoconfig: case allyesconfig: case allmodconfig: case alldefconfig: case randconfig: name = getenv("KCONFIG_ALLCONFIG"); if (!name) break; if ((strcmp(name, "") != 0) && (strcmp(name, "1") != 0)) { if (conf_read_simple(name, S_DEF_USER)) { fprintf(stderr, "*** Can't read seed configuration \"%s\"!\n", name); exit(1); } break; } switch (input_mode) { case allnoconfig: name = "allno.config"; break; case allyesconfig: name = "allyes.config"; break; case allmodconfig: name = "allmod.config"; break; case alldefconfig: name = "alldef.config"; break; case randconfig: name = "allrandom.config"; break; default: break; } if (conf_read_simple(name, S_DEF_USER) && conf_read_simple("all.config", S_DEF_USER)) { fprintf(stderr, "*** KCONFIG_ALLCONFIG set, but no \"%s\" or \"all.config\" file found\n", name); exit(1); } break; default: break; } if (sync_kconfig) { name = getenv("KCONFIG_NOSILENTUPDATE"); if (name && *name) { if (conf_get_changed()) { fprintf(stderr, "\n*** The configuration requires explicit update.\n\n"); return 1; } no_conf_write = 1; } } switch (input_mode) { case allnoconfig: conf_set_all_new_symbols(def_no); break; case allyesconfig: conf_set_all_new_symbols(def_yes); break; case allmodconfig: conf_set_all_new_symbols(def_mod); break; case alldefconfig: conf_set_all_new_symbols(def_default); break; case randconfig: /* Really nothing to do in this loop */ while (conf_set_all_new_symbols(def_random)) ; break; case defconfig: conf_set_all_new_symbols(def_default); break; case savedefconfig: break; case yes2modconfig: conf_rewrite_tristates(yes, mod); break; case mod2yesconfig: conf_rewrite_tristates(mod, yes); break; case mod2noconfig: conf_rewrite_tristates(mod, no); break; case oldaskconfig: rootEntry = &rootmenu; conf(&rootmenu); input_mode = oldconfig; /* fall through */ case oldconfig: case listnewconfig: case helpnewconfig: case syncconfig: /* Update until a loop caused no more changes */ do { conf_cnt = 0; check_conf(&rootmenu); } while (conf_cnt); break; case olddefconfig: default: break; } if (input_mode == savedefconfig) { if (conf_write_defconfig(defconfig_file)) { fprintf(stderr, "n*** Error while saving defconfig to: %s\n\n", defconfig_file); return 1; } } else if (input_mode != listnewconfig && input_mode != helpnewconfig) { if (!no_conf_write && conf_write(NULL)) { fprintf(stderr, "\n*** Error during writing of the configuration.\n\n"); exit(1); } /* * Create auto.conf if it does not exist. * This prevents GNU Make 4.1 or older from emitting * "include/config/auto.conf: No such file or directory" * in the top-level Makefile * * syncconfig always creates or updates auto.conf because it is * used during the build. */ if (conf_write_autoconf(sync_kconfig) && sync_kconfig) { fprintf(stderr, "\n*** Error during sync of the configuration.\n\n"); return 1; } } return 0; }
linux-master
scripts/kconfig/conf.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2008 Nir Tzachar <[email protected]> * * Derived from menuconfig. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <string.h> #include <strings.h> #include <stdlib.h> #include "lkc.h" #include "nconf.h" #include <ctype.h> static const char nconf_global_help[] = "Help windows\n" "------------\n" "o Global help: Unless in a data entry window, pressing <F1> will give \n" " you the global help window, which you are just reading.\n" "\n" "o A short version of the global help is available by pressing <F3>.\n" "\n" "o Local help: To get help related to the current menu entry, use any\n" " of <?> <h>, or if in a data entry window then press <F1>.\n" "\n" "\n" "Menu entries\n" "------------\n" "This interface lets you select features and parameters for the kernel\n" "build. Kernel features can either be built-in, modularized, or removed.\n" "Parameters must be entered as text or decimal or hexadecimal numbers.\n" "\n" "Menu entries beginning with following braces represent features that\n" " [ ] can be built in or removed\n" " < > can be built in, modularized or removed\n" " { } can be built in or modularized, are selected by another feature\n" " - - are selected by another feature\n" " XXX cannot be selected. Symbol Info <F2> tells you why.\n" "*, M or whitespace inside braces means to build in, build as a module\n" "or to exclude the feature respectively.\n" "\n" "To change any of these features, highlight it with the movement keys\n" "listed below and press <y> to build it in, <m> to make it a module or\n" "<n> to remove it. You may press the <Space> key to cycle through the\n" "available options.\n" "\n" "A trailing \"--->\" designates a submenu, a trailing \"----\" an\n" "empty submenu.\n" "\n" "Menu navigation keys\n" "----------------------------------------------------------------------\n" "Linewise up <Up> <k>\n" "Linewise down <Down> <j>\n" "Pagewise up <Page Up>\n" "Pagewise down <Page Down>\n" "First entry <Home>\n" "Last entry <End>\n" "Enter a submenu <Right> <Enter>\n" "Go back to parent menu <Left> <Esc> <F5>\n" "Close a help window <Enter> <Esc> <F5>\n" "Close entry window, apply <Enter>\n" "Close entry window, forget <Esc> <F5>\n" "Start incremental, case-insensitive search for STRING in menu entries,\n" " no regex support, STRING is displayed in upper left corner\n" " </>STRING\n" " Remove last character <Backspace>\n" " Jump to next hit <Down>\n" " Jump to previous hit <Up>\n" "Exit menu search mode </> <Esc>\n" "Search for configuration variables with or without leading CONFIG_\n" " <F8>RegExpr<Enter>\n" "Verbose search help <F8><F1>\n" "----------------------------------------------------------------------\n" "\n" "Unless in a data entry window, key <1> may be used instead of <F1>,\n" "<2> instead of <F2>, etc.\n" "\n" "\n" "Radiolist (Choice list)\n" "-----------------------\n" "Use the movement keys listed above to select the option you wish to set\n" "and press <Space>.\n" "\n" "\n" "Data entry\n" "----------\n" "Enter the requested information and press <Enter>. Hexadecimal values\n" "may be entered without the \"0x\" prefix.\n" "\n" "\n" "Text Box (Help Window)\n" "----------------------\n" "Use movement keys as listed in table above.\n" "\n" "Press any of <Enter> <Esc> <q> <F5> <F9> to exit.\n" "\n" "\n" "Alternate configuration files\n" "-----------------------------\n" "nconfig supports switching between different configurations.\n" "Press <F6> to save your current configuration. Press <F7> and enter\n" "a file name to load a previously saved configuration.\n" "\n" "\n" "Terminal configuration\n" "----------------------\n" "If you use nconfig in a xterm window, make sure your TERM environment\n" "variable specifies a terminal configuration which supports at least\n" "16 colors. Otherwise nconfig will look rather bad.\n" "\n" "If the \"stty size\" command reports the current terminalsize correctly,\n" "nconfig will adapt to sizes larger than the traditional 80x25 \"standard\"\n" "and display longer menus properly.\n" "\n" "\n" "Single menu mode\n" "----------------\n" "If you prefer to have all of the menu entries listed in a single menu,\n" "rather than the default multimenu hierarchy, run nconfig with\n" "NCONFIG_MODE environment variable set to single_menu. Example:\n" "\n" "make NCONFIG_MODE=single_menu nconfig\n" "\n" "<Enter> will then unfold the appropriate category, or fold it if it\n" "is already unfolded. Folded menu entries will be designated by a\n" "leading \"++>\" and unfolded entries by a leading \"-->\".\n" "\n" "Note that this mode can eventually be a little more CPU expensive than\n" "the default mode, especially with a larger number of unfolded submenus.\n" "\n", menu_no_f_instructions[] = "Legend: [*] built-in [ ] excluded <M> module < > module capable.\n" "Submenus are designated by a trailing \"--->\", empty ones by \"----\".\n" "\n" "Use the following keys to navigate the menus:\n" "Move up or down with <Up> and <Down>.\n" "Enter a submenu with <Enter> or <Right>.\n" "Exit a submenu to its parent menu with <Esc> or <Left>.\n" "Pressing <y> includes, <n> excludes, <m> modularizes features.\n" "Pressing <Space> cycles through the available options.\n" "To search for menu entries press </>.\n" "<Esc> always leaves the current window.\n" "\n" "You do not have function keys support.\n" "Press <1> instead of <F1>, <2> instead of <F2>, etc.\n" "For verbose global help use key <1>.\n" "For help related to the current menu entry press <?> or <h>.\n", menu_instructions[] = "Legend: [*] built-in [ ] excluded <M> module < > module capable.\n" "Submenus are designated by a trailing \"--->\", empty ones by \"----\".\n" "\n" "Use the following keys to navigate the menus:\n" "Move up or down with <Up> or <Down>.\n" "Enter a submenu with <Enter> or <Right>.\n" "Exit a submenu to its parent menu with <Esc> or <Left>.\n" "Pressing <y> includes, <n> excludes, <m> modularizes features.\n" "Pressing <Space> cycles through the available options.\n" "To search for menu entries press </>.\n" "<Esc> always leaves the current window.\n" "\n" "Pressing <1> may be used instead of <F1>, <2> instead of <F2>, etc.\n" "For verbose global help press <F1>.\n" "For help related to the current menu entry press <?> or <h>.\n", radiolist_instructions[] = "Press <Up>, <Down>, <Home> or <End> to navigate a radiolist, select\n" "with <Space>.\n" "For help related to the current entry press <?> or <h>.\n" "For global help press <F1>.\n", inputbox_instructions_int[] = "Please enter a decimal value.\n" "Fractions will not be accepted.\n" "Press <Enter> to apply, <Esc> to cancel.", inputbox_instructions_hex[] = "Please enter a hexadecimal value.\n" "Press <Enter> to apply, <Esc> to cancel.", inputbox_instructions_string[] = "Please enter a string value.\n" "Press <Enter> to apply, <Esc> to cancel.", setmod_text[] = "This feature depends on another feature which has been configured as a\n" "module. As a result, the current feature will be built as a module too.", load_config_text[] = "Enter the name of the configuration file you wish to load.\n" "Accept the name shown to restore the configuration you last\n" "retrieved. Leave empty to abort.", load_config_help[] = "For various reasons, one may wish to keep several different\n" "configurations available on a single machine.\n" "\n" "If you have saved a previous configuration in a file other than the\n" "default one, entering its name here will allow you to load and modify\n" "that configuration.\n" "\n" "Leave empty to abort.\n", save_config_text[] = "Enter a filename to which this configuration should be saved\n" "as an alternate. Leave empty to abort.", save_config_help[] = "For various reasons, one may wish to keep several different\n" "configurations available on a single machine.\n" "\n" "Entering a file name here will allow you to later retrieve, modify\n" "and use the current configuration as an alternate to whatever\n" "configuration options you have selected at that time.\n" "\n" "Leave empty to abort.\n", search_help[] = "Search for symbols (configuration variable names CONFIG_*) and display\n" "their relations. Regular expressions are supported.\n" "Example: Search for \"^FOO\".\n" "Result:\n" "-----------------------------------------------------------------\n" "Symbol: FOO [ = m]\n" "Prompt: Foo bus is used to drive the bar HW\n" "Defined at drivers/pci/Kconfig:47\n" "Depends on: X86_LOCAL_APIC && X86_IO_APIC || IA64\n" "Location:\n" " -> Bus options (PCI, PCMCIA, EISA, ISA)\n" " -> PCI support (PCI [ = y])\n" "(1) -> PCI access mode (<choice> [ = y])\n" "Selects: LIBCRC32\n" "Selected by: BAR\n" "-----------------------------------------------------------------\n" "o The line 'Prompt:' shows the text displayed for this symbol in\n" " the menu hierarchy.\n" "o The 'Defined at' line tells at what file / line number the symbol is\n" " defined.\n" "o The 'Depends on:' line lists symbols that need to be defined for\n" " this symbol to be visible and selectable in the menu.\n" "o The 'Location:' lines tell, where in the menu structure this symbol\n" " is located.\n" " A location followed by a [ = y] indicates that this is\n" " a selectable menu item, and the current value is displayed inside\n" " brackets.\n" " Press the key in the (#) prefix to jump directly to that\n" " location. You will be returned to the current search results\n" " after exiting this new menu.\n" "o The 'Selects:' line tells, what symbol will be automatically selected\n" " if this symbol is selected (y or m).\n" "o The 'Selected by' line tells what symbol has selected this symbol.\n" "\n" "Only relevant lines are shown.\n" "\n\n" "Search examples:\n" "USB => find all symbols containing USB\n" "^USB => find all symbols starting with USB\n" "USB$ => find all symbols ending with USB\n" "\n"; struct mitem { char str[256]; char tag; void *usrptr; int is_visible; }; #define MAX_MENU_ITEMS 4096 static int show_all_items; static int indent; static struct menu *current_menu; static int child_count; static int single_menu_mode; /* the window in which all information appears */ static WINDOW *main_window; /* the largest size of the menu window */ static int mwin_max_lines; static int mwin_max_cols; /* the window in which we show option buttons */ static MENU *curses_menu; static ITEM *curses_menu_items[MAX_MENU_ITEMS]; static struct mitem k_menu_items[MAX_MENU_ITEMS]; static unsigned int items_num; static int global_exit; /* the currently selected button */ static const char *current_instructions = menu_instructions; static char *dialog_input_result; static int dialog_input_result_len; static int jump_key_char; static void selected_conf(struct menu *menu, struct menu *active_menu); static void conf(struct menu *menu); static void conf_choice(struct menu *menu); static void conf_string(struct menu *menu); static void conf_load(void); static void conf_save(void); static void show_help(struct menu *menu); static int do_exit(void); static void setup_windows(void); static void search_conf(void); typedef void (*function_key_handler_t)(int *key, struct menu *menu); static void handle_f1(int *key, struct menu *current_item); static void handle_f2(int *key, struct menu *current_item); static void handle_f3(int *key, struct menu *current_item); static void handle_f4(int *key, struct menu *current_item); static void handle_f5(int *key, struct menu *current_item); static void handle_f6(int *key, struct menu *current_item); static void handle_f7(int *key, struct menu *current_item); static void handle_f8(int *key, struct menu *current_item); static void handle_f9(int *key, struct menu *current_item); struct function_keys { const char *key_str; const char *func; function_key key; function_key_handler_t handler; }; static const int function_keys_num = 9; static struct function_keys function_keys[] = { { .key_str = "F1", .func = "Help", .key = F_HELP, .handler = handle_f1, }, { .key_str = "F2", .func = "SymInfo", .key = F_SYMBOL, .handler = handle_f2, }, { .key_str = "F3", .func = "Help 2", .key = F_INSTS, .handler = handle_f3, }, { .key_str = "F4", .func = "ShowAll", .key = F_CONF, .handler = handle_f4, }, { .key_str = "F5", .func = "Back", .key = F_BACK, .handler = handle_f5, }, { .key_str = "F6", .func = "Save", .key = F_SAVE, .handler = handle_f6, }, { .key_str = "F7", .func = "Load", .key = F_LOAD, .handler = handle_f7, }, { .key_str = "F8", .func = "SymSearch", .key = F_SEARCH, .handler = handle_f8, }, { .key_str = "F9", .func = "Exit", .key = F_EXIT, .handler = handle_f9, }, }; static void print_function_line(void) { int i; int offset = 1; const int skip = 1; int lines = getmaxy(stdscr); for (i = 0; i < function_keys_num; i++) { wattrset(main_window, attr_function_highlight); mvwprintw(main_window, lines-3, offset, "%s", function_keys[i].key_str); wattrset(main_window, attr_function_text); offset += strlen(function_keys[i].key_str); mvwprintw(main_window, lines-3, offset, "%s", function_keys[i].func); offset += strlen(function_keys[i].func) + skip; } wattrset(main_window, attr_normal); } /* help */ static void handle_f1(int *key, struct menu *current_item) { show_scroll_win(main_window, "Global help", nconf_global_help); return; } /* symbole help */ static void handle_f2(int *key, struct menu *current_item) { show_help(current_item); return; } /* instructions */ static void handle_f3(int *key, struct menu *current_item) { show_scroll_win(main_window, "Short help", current_instructions); return; } /* config */ static void handle_f4(int *key, struct menu *current_item) { int res = btn_dialog(main_window, "Show all symbols?", 2, " <Show All> ", "<Don't show all>"); if (res == 0) show_all_items = 1; else if (res == 1) show_all_items = 0; return; } /* back */ static void handle_f5(int *key, struct menu *current_item) { *key = KEY_LEFT; return; } /* save */ static void handle_f6(int *key, struct menu *current_item) { conf_save(); return; } /* load */ static void handle_f7(int *key, struct menu *current_item) { conf_load(); return; } /* search */ static void handle_f8(int *key, struct menu *current_item) { search_conf(); return; } /* exit */ static void handle_f9(int *key, struct menu *current_item) { do_exit(); return; } /* return != 0 to indicate the key was handles */ static int process_special_keys(int *key, struct menu *menu) { int i; if (*key == KEY_RESIZE) { setup_windows(); return 1; } for (i = 0; i < function_keys_num; i++) { if (*key == KEY_F(function_keys[i].key) || *key == '0' + function_keys[i].key){ function_keys[i].handler(key, menu); return 1; } } return 0; } static void clean_items(void) { int i; for (i = 0; curses_menu_items[i]; i++) free_item(curses_menu_items[i]); bzero(curses_menu_items, sizeof(curses_menu_items)); bzero(k_menu_items, sizeof(k_menu_items)); items_num = 0; } typedef enum {MATCH_TINKER_PATTERN_UP, MATCH_TINKER_PATTERN_DOWN, FIND_NEXT_MATCH_DOWN, FIND_NEXT_MATCH_UP} match_f; /* return the index of the matched item, or -1 if no such item exists */ static int get_mext_match(const char *match_str, match_f flag) { int match_start, index; /* Do not search if the menu is empty (i.e. items_num == 0) */ match_start = item_index(current_item(curses_menu)); if (match_start == ERR) return -1; if (flag == FIND_NEXT_MATCH_DOWN) ++match_start; else if (flag == FIND_NEXT_MATCH_UP) --match_start; match_start = (match_start + items_num) % items_num; index = match_start; while (true) { char *str = k_menu_items[index].str; if (strcasestr(str, match_str) != NULL) return index; if (flag == FIND_NEXT_MATCH_UP || flag == MATCH_TINKER_PATTERN_UP) --index; else ++index; index = (index + items_num) % items_num; if (index == match_start) return -1; } } /* Make a new item. */ static void item_make(struct menu *menu, char tag, const char *fmt, ...) { va_list ap; if (items_num > MAX_MENU_ITEMS-1) return; bzero(&k_menu_items[items_num], sizeof(k_menu_items[0])); k_menu_items[items_num].tag = tag; k_menu_items[items_num].usrptr = menu; if (menu != NULL) k_menu_items[items_num].is_visible = menu_is_visible(menu); else k_menu_items[items_num].is_visible = 1; va_start(ap, fmt); vsnprintf(k_menu_items[items_num].str, sizeof(k_menu_items[items_num].str), fmt, ap); va_end(ap); if (!k_menu_items[items_num].is_visible) memcpy(k_menu_items[items_num].str, "XXX", 3); curses_menu_items[items_num] = new_item( k_menu_items[items_num].str, k_menu_items[items_num].str); set_item_userptr(curses_menu_items[items_num], &k_menu_items[items_num]); /* if (!k_menu_items[items_num].is_visible) item_opts_off(curses_menu_items[items_num], O_SELECTABLE); */ items_num++; curses_menu_items[items_num] = NULL; } /* very hackish. adds a string to the last item added */ static void item_add_str(const char *fmt, ...) { va_list ap; int index = items_num-1; char new_str[256]; char tmp_str[256]; if (index < 0) return; va_start(ap, fmt); vsnprintf(new_str, sizeof(new_str), fmt, ap); va_end(ap); snprintf(tmp_str, sizeof(tmp_str), "%s%s", k_menu_items[index].str, new_str); strncpy(k_menu_items[index].str, tmp_str, sizeof(k_menu_items[index].str)); free_item(curses_menu_items[index]); curses_menu_items[index] = new_item( k_menu_items[index].str, k_menu_items[index].str); set_item_userptr(curses_menu_items[index], &k_menu_items[index]); } /* get the tag of the currently selected item */ static char item_tag(void) { ITEM *cur; struct mitem *mcur; cur = current_item(curses_menu); if (cur == NULL) return 0; mcur = (struct mitem *) item_userptr(cur); return mcur->tag; } static int curses_item_index(void) { return item_index(current_item(curses_menu)); } static void *item_data(void) { ITEM *cur; struct mitem *mcur; cur = current_item(curses_menu); if (!cur) return NULL; mcur = (struct mitem *) item_userptr(cur); return mcur->usrptr; } static int item_is_tag(char tag) { return item_tag() == tag; } static char filename[PATH_MAX+1]; static char menu_backtitle[PATH_MAX+128]; static void set_config_filename(const char *config_filename) { snprintf(menu_backtitle, sizeof(menu_backtitle), "%s - %s", config_filename, rootmenu.prompt->text); snprintf(filename, sizeof(filename), "%s", config_filename); } /* return = 0 means we are successful. * -1 means go on doing what you were doing */ static int do_exit(void) { int res; if (!conf_get_changed()) { global_exit = 1; return 0; } res = btn_dialog(main_window, "Do you wish to save your new configuration?\n" "<ESC> to cancel and resume nconfig.", 2, " <save> ", "<don't save>"); if (res == KEY_EXIT) { global_exit = 0; return -1; } /* if we got here, the user really wants to exit */ switch (res) { case 0: res = conf_write(filename); if (res) btn_dialog( main_window, "Error during writing of configuration.\n" "Your configuration changes were NOT saved.", 1, "<OK>"); conf_write_autoconf(0); break; default: btn_dialog( main_window, "Your configuration changes were NOT saved.", 1, "<OK>"); break; } global_exit = 1; return 0; } struct search_data { struct list_head *head; struct menu *target; }; static int next_jump_key(int key) { if (key < '1' || key > '9') return '1'; key++; if (key > '9') key = '1'; return key; } static int handle_search_keys(int key, size_t start, size_t end, void *_data) { struct search_data *data = _data; struct jump_key *pos; int index = 0; if (key < '1' || key > '9') return 0; list_for_each_entry(pos, data->head, entries) { index = next_jump_key(index); if (pos->offset < start) continue; if (pos->offset >= end) break; if (key == index) { data->target = pos->target; return 1; } } return 0; } int get_jump_key_char(void) { jump_key_char = next_jump_key(jump_key_char); return jump_key_char; } static void search_conf(void) { struct symbol **sym_arr; struct gstr res; struct gstr title; char *dialog_input; int dres, vscroll = 0, hscroll = 0; bool again; title = str_new(); str_printf( &title, "Enter (sub)string or regexp to search for " "(with or without \"%s\")", CONFIG_); again: dres = dialog_inputbox(main_window, "Search Configuration Parameter", str_get(&title), "", &dialog_input_result, &dialog_input_result_len); switch (dres) { case 0: break; case 1: show_scroll_win(main_window, "Search Configuration", search_help); goto again; default: str_free(&title); return; } /* strip the prefix if necessary */ dialog_input = dialog_input_result; if (strncasecmp(dialog_input_result, CONFIG_, strlen(CONFIG_)) == 0) dialog_input += strlen(CONFIG_); sym_arr = sym_re_search(dialog_input); do { LIST_HEAD(head); struct search_data data = { .head = &head, .target = NULL, }; jump_key_char = 0; res = get_relations_str(sym_arr, &head); dres = show_scroll_win_ext(main_window, "Search Results", str_get(&res), &vscroll, &hscroll, handle_search_keys, &data); again = false; if (dres >= '1' && dres <= '9') { assert(data.target != NULL); selected_conf(data.target->parent, data.target); again = true; } str_free(&res); } while (again); free(sym_arr); str_free(&title); } static void build_conf(struct menu *menu) { struct symbol *sym; struct property *prop; struct menu *child; int type, tmp, doint = 2; tristate val; char ch; if (!menu || (!show_all_items && !menu_is_visible(menu))) return; sym = menu->sym; prop = menu->prompt; if (!sym) { if (prop && menu != current_menu) { const char *prompt = menu_get_prompt(menu); enum prop_type ptype; ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN; switch (ptype) { case P_MENU: child_count++; if (single_menu_mode) { item_make(menu, 'm', "%s%*c%s", menu->data ? "-->" : "++>", indent + 1, ' ', prompt); } else item_make(menu, 'm', " %*c%s %s", indent + 1, ' ', prompt, menu_is_empty(menu) ? "----" : "--->"); if (single_menu_mode && menu->data) goto conf_childs; return; case P_COMMENT: if (prompt) { child_count++; item_make(menu, ':', " %*c*** %s ***", indent + 1, ' ', prompt); } break; default: if (prompt) { child_count++; item_make(menu, ':', "---%*c%s", indent + 1, ' ', prompt); } } } else doint = 0; goto conf_childs; } type = sym_get_type(sym); if (sym_is_choice(sym)) { struct symbol *def_sym = sym_get_choice_value(sym); struct menu *def_menu = NULL; child_count++; for (child = menu->list; child; child = child->next) { if (menu_is_visible(child) && child->sym == def_sym) def_menu = child; } val = sym_get_tristate_value(sym); if (sym_is_changeable(sym)) { switch (type) { case S_BOOLEAN: item_make(menu, 't', "[%c]", val == no ? ' ' : '*'); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } item_make(menu, 't', "<%c>", ch); break; } } else { item_make(menu, def_menu ? 't' : ':', " "); } item_add_str("%*c%s", indent + 1, ' ', menu_get_prompt(menu)); if (val == yes) { if (def_menu) { item_add_str(" (%s)", menu_get_prompt(def_menu)); item_add_str(" --->"); if (def_menu->list) { indent += 2; build_conf(def_menu); indent -= 2; } } return; } } else { if (menu == current_menu) { item_make(menu, ':', "---%*c%s", indent + 1, ' ', menu_get_prompt(menu)); goto conf_childs; } child_count++; val = sym_get_tristate_value(sym); if (sym_is_choice_value(sym) && val == yes) { item_make(menu, ':', " "); } else { switch (type) { case S_BOOLEAN: if (sym_is_changeable(sym)) item_make(menu, 't', "[%c]", val == no ? ' ' : '*'); else item_make(menu, 't', "-%c-", val == no ? ' ' : '*'); break; case S_TRISTATE: switch (val) { case yes: ch = '*'; break; case mod: ch = 'M'; break; default: ch = ' '; break; } if (sym_is_changeable(sym)) { if (sym->rev_dep.tri == mod) item_make(menu, 't', "{%c}", ch); else item_make(menu, 't', "<%c>", ch); } else item_make(menu, 't', "-%c-", ch); break; default: tmp = 2 + strlen(sym_get_string_value(sym)); item_make(menu, 's', " (%s)", sym_get_string_value(sym)); tmp = indent - tmp + 4; if (tmp < 0) tmp = 0; item_add_str("%*c%s%s", tmp, ' ', menu_get_prompt(menu), (sym_has_value(sym) || !sym_is_changeable(sym)) ? "" : " (NEW)"); goto conf_childs; } } item_add_str("%*c%s%s", indent + 1, ' ', menu_get_prompt(menu), (sym_has_value(sym) || !sym_is_changeable(sym)) ? "" : " (NEW)"); if (menu->prompt && menu->prompt->type == P_MENU) { item_add_str(" %s", menu_is_empty(menu) ? "----" : "--->"); return; } } conf_childs: indent += doint; for (child = menu->list; child; child = child->next) build_conf(child); indent -= doint; } static void reset_menu(void) { unpost_menu(curses_menu); clean_items(); } /* adjust the menu to show this item. * prefer not to scroll the menu if possible*/ static void center_item(int selected_index, int *last_top_row) { int toprow; set_top_row(curses_menu, *last_top_row); toprow = top_row(curses_menu); if (selected_index < toprow || selected_index >= toprow+mwin_max_lines) { toprow = max(selected_index-mwin_max_lines/2, 0); if (toprow >= item_count(curses_menu)-mwin_max_lines) toprow = item_count(curses_menu)-mwin_max_lines; set_top_row(curses_menu, toprow); } set_current_item(curses_menu, curses_menu_items[selected_index]); *last_top_row = toprow; post_menu(curses_menu); refresh_all_windows(main_window); } /* this function assumes reset_menu has been called before */ static void show_menu(const char *prompt, const char *instructions, int selected_index, int *last_top_row) { int maxx, maxy; WINDOW *menu_window; current_instructions = instructions; clear(); print_in_middle(stdscr, 1, getmaxx(stdscr), menu_backtitle, attr_main_heading); wattrset(main_window, attr_main_menu_box); box(main_window, 0, 0); wattrset(main_window, attr_main_menu_heading); mvwprintw(main_window, 0, 3, " %s ", prompt); wattrset(main_window, attr_normal); set_menu_items(curses_menu, curses_menu_items); /* position the menu at the middle of the screen */ scale_menu(curses_menu, &maxy, &maxx); maxx = min(maxx, mwin_max_cols-2); maxy = mwin_max_lines; menu_window = derwin(main_window, maxy, maxx, 2, (mwin_max_cols-maxx)/2); keypad(menu_window, TRUE); set_menu_win(curses_menu, menu_window); set_menu_sub(curses_menu, menu_window); /* must reassert this after changing items, otherwise returns to a * default of 16 */ set_menu_format(curses_menu, maxy, 1); center_item(selected_index, last_top_row); set_menu_format(curses_menu, maxy, 1); print_function_line(); /* Post the menu */ post_menu(curses_menu); refresh_all_windows(main_window); } static void adj_match_dir(match_f *match_direction) { if (*match_direction == FIND_NEXT_MATCH_DOWN) *match_direction = MATCH_TINKER_PATTERN_DOWN; else if (*match_direction == FIND_NEXT_MATCH_UP) *match_direction = MATCH_TINKER_PATTERN_UP; /* else, do no change.. */ } struct match_state { int in_search; match_f match_direction; char pattern[256]; }; /* Return 0 means I have handled the key. In such a case, ans should hold the * item to center, or -1 otherwise. * Else return -1 . */ static int do_match(int key, struct match_state *state, int *ans) { char c = (char) key; int terminate_search = 0; *ans = -1; if (key == '/' || (state->in_search && key == 27)) { move(0, 0); refresh(); clrtoeol(); state->in_search = 1-state->in_search; bzero(state->pattern, sizeof(state->pattern)); state->match_direction = MATCH_TINKER_PATTERN_DOWN; return 0; } else if (!state->in_search) return 1; if (isalnum(c) || isgraph(c) || c == ' ') { state->pattern[strlen(state->pattern)] = c; state->pattern[strlen(state->pattern)] = '\0'; adj_match_dir(&state->match_direction); *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_DOWN) { state->match_direction = FIND_NEXT_MATCH_DOWN; *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_UP) { state->match_direction = FIND_NEXT_MATCH_UP; *ans = get_mext_match(state->pattern, state->match_direction); } else if (key == KEY_BACKSPACE || key == 8 || key == 127) { state->pattern[strlen(state->pattern)-1] = '\0'; adj_match_dir(&state->match_direction); } else terminate_search = 1; if (terminate_search) { state->in_search = 0; bzero(state->pattern, sizeof(state->pattern)); move(0, 0); refresh(); clrtoeol(); return -1; } return 0; } static void conf(struct menu *menu) { selected_conf(menu, NULL); } static void selected_conf(struct menu *menu, struct menu *active_menu) { struct menu *submenu = NULL; struct symbol *sym; int i, res; int current_index = 0; int last_top_row = 0; struct match_state match_state = { .in_search = 0, .match_direction = MATCH_TINKER_PATTERN_DOWN, .pattern = "", }; while (!global_exit) { reset_menu(); current_menu = menu; build_conf(menu); if (!child_count) break; if (active_menu != NULL) { for (i = 0; i < items_num; i++) { struct mitem *mcur; mcur = (struct mitem *) item_userptr(curses_menu_items[i]); if ((struct menu *) mcur->usrptr == active_menu) { current_index = i; break; } } active_menu = NULL; } show_menu(menu_get_prompt(menu), menu_instructions, current_index, &last_top_row); keypad((menu_win(curses_menu)), TRUE); while (!global_exit) { if (match_state.in_search) { mvprintw(0, 0, "searching: %s", match_state.pattern); clrtoeol(); } refresh_all_windows(main_window); res = wgetch(menu_win(curses_menu)); if (!res) break; if (do_match(res, &match_state, &current_index) == 0) { if (current_index != -1) center_item(current_index, &last_top_row); continue; } if (process_special_keys(&res, (struct menu *) item_data())) break; switch (res) { case KEY_DOWN: case 'j': menu_driver(curses_menu, REQ_DOWN_ITEM); break; case KEY_UP: case 'k': menu_driver(curses_menu, REQ_UP_ITEM); break; case KEY_NPAGE: menu_driver(curses_menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: menu_driver(curses_menu, REQ_SCR_UPAGE); break; case KEY_HOME: menu_driver(curses_menu, REQ_FIRST_ITEM); break; case KEY_END: menu_driver(curses_menu, REQ_LAST_ITEM); break; case 'h': case '?': show_help((struct menu *) item_data()); break; } if (res == 10 || res == 27 || res == 32 || res == 'n' || res == 'y' || res == KEY_LEFT || res == KEY_RIGHT || res == 'm') break; refresh_all_windows(main_window); } refresh_all_windows(main_window); /* if ESC or left*/ if (res == 27 || (menu != &rootmenu && res == KEY_LEFT)) break; /* remember location in the menu */ last_top_row = top_row(curses_menu); current_index = curses_item_index(); if (!item_tag()) continue; submenu = (struct menu *) item_data(); if (!submenu || !menu_is_visible(submenu)) continue; sym = submenu->sym; switch (res) { case ' ': if (item_is_tag('t')) sym_toggle_tristate_value(sym); else if (item_is_tag('m')) conf(submenu); break; case KEY_RIGHT: case 10: /* ENTER WAS PRESSED */ switch (item_tag()) { case 'm': if (single_menu_mode) submenu->data = (void *) (long) !submenu->data; else conf(submenu); break; case 't': if (sym_is_choice(sym) && sym_get_tristate_value(sym) == yes) conf_choice(submenu); else if (submenu->prompt && submenu->prompt->type == P_MENU) conf(submenu); else if (res == 10) sym_toggle_tristate_value(sym); break; case 's': conf_string(submenu); break; } break; case 'y': if (item_is_tag('t')) { if (sym_set_tristate_value(sym, yes)) break; if (sym_set_tristate_value(sym, mod)) btn_dialog(main_window, setmod_text, 0); } break; case 'n': if (item_is_tag('t')) sym_set_tristate_value(sym, no); break; case 'm': if (item_is_tag('t')) sym_set_tristate_value(sym, mod); break; } } } static void conf_message_callback(const char *s) { btn_dialog(main_window, s, 1, "<OK>"); } static void show_help(struct menu *menu) { struct gstr help; if (!menu) return; help = str_new(); menu_get_ext_help(menu, &help); show_scroll_win(main_window, menu_get_prompt(menu), str_get(&help)); str_free(&help); } static void conf_choice(struct menu *menu) { const char *prompt = menu_get_prompt(menu); struct menu *child = NULL; struct symbol *active; int selected_index = 0; int last_top_row = 0; int res, i = 0; struct match_state match_state = { .in_search = 0, .match_direction = MATCH_TINKER_PATTERN_DOWN, .pattern = "", }; active = sym_get_choice_value(menu->sym); /* this is mostly duplicated from the conf() function. */ while (!global_exit) { reset_menu(); for (i = 0, child = menu->list; child; child = child->next) { if (!show_all_items && !menu_is_visible(child)) continue; if (child->sym == sym_get_choice_value(menu->sym)) item_make(child, ':', "<X> %s", menu_get_prompt(child)); else if (child->sym) item_make(child, ':', " %s", menu_get_prompt(child)); else item_make(child, ':', "*** %s ***", menu_get_prompt(child)); if (child->sym == active){ last_top_row = top_row(curses_menu); selected_index = i; } i++; } show_menu(prompt ? prompt : "Choice Menu", radiolist_instructions, selected_index, &last_top_row); while (!global_exit) { if (match_state.in_search) { mvprintw(0, 0, "searching: %s", match_state.pattern); clrtoeol(); } refresh_all_windows(main_window); res = wgetch(menu_win(curses_menu)); if (!res) break; if (do_match(res, &match_state, &selected_index) == 0) { if (selected_index != -1) center_item(selected_index, &last_top_row); continue; } if (process_special_keys( &res, (struct menu *) item_data())) break; switch (res) { case KEY_DOWN: case 'j': menu_driver(curses_menu, REQ_DOWN_ITEM); break; case KEY_UP: case 'k': menu_driver(curses_menu, REQ_UP_ITEM); break; case KEY_NPAGE: menu_driver(curses_menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: menu_driver(curses_menu, REQ_SCR_UPAGE); break; case KEY_HOME: menu_driver(curses_menu, REQ_FIRST_ITEM); break; case KEY_END: menu_driver(curses_menu, REQ_LAST_ITEM); break; case 'h': case '?': show_help((struct menu *) item_data()); break; } if (res == 10 || res == 27 || res == ' ' || res == KEY_LEFT){ break; } refresh_all_windows(main_window); } /* if ESC or left */ if (res == 27 || res == KEY_LEFT) break; child = item_data(); if (!child || !menu_is_visible(child) || !child->sym) continue; switch (res) { case ' ': case 10: case KEY_RIGHT: sym_set_tristate_value(child->sym, yes); return; case 'h': case '?': show_help(child); active = child->sym; break; case KEY_EXIT: return; } } } static void conf_string(struct menu *menu) { const char *prompt = menu_get_prompt(menu); while (1) { int res; const char *heading; switch (sym_get_type(menu->sym)) { case S_INT: heading = inputbox_instructions_int; break; case S_HEX: heading = inputbox_instructions_hex; break; case S_STRING: heading = inputbox_instructions_string; break; default: heading = "Internal nconf error!"; } res = dialog_inputbox(main_window, prompt ? prompt : "Main Menu", heading, sym_get_string_value(menu->sym), &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (sym_set_string_value(menu->sym, dialog_input_result)) return; btn_dialog(main_window, "You have made an invalid entry.", 0); break; case 1: show_help(menu); break; case KEY_EXIT: return; } } } static void conf_load(void) { while (1) { int res; res = dialog_inputbox(main_window, NULL, load_config_text, filename, &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (!dialog_input_result[0]) return; if (!conf_read(dialog_input_result)) { set_config_filename(dialog_input_result); conf_set_changed(true); return; } btn_dialog(main_window, "File does not exist!", 0); break; case 1: show_scroll_win(main_window, "Load Alternate Configuration", load_config_help); break; case KEY_EXIT: return; } } } static void conf_save(void) { while (1) { int res; res = dialog_inputbox(main_window, NULL, save_config_text, filename, &dialog_input_result, &dialog_input_result_len); switch (res) { case 0: if (!dialog_input_result[0]) return; res = conf_write(dialog_input_result); if (!res) { set_config_filename(dialog_input_result); return; } btn_dialog(main_window, "Can't create file!", 1, "<OK>"); break; case 1: show_scroll_win(main_window, "Save Alternate Configuration", save_config_help); break; case KEY_EXIT: return; } } } static void setup_windows(void) { int lines, columns; getmaxyx(stdscr, lines, columns); if (main_window != NULL) delwin(main_window); /* set up the menu and menu window */ main_window = newwin(lines-2, columns-2, 2, 1); keypad(main_window, TRUE); mwin_max_lines = lines-7; mwin_max_cols = columns-6; /* panels order is from bottom to top */ new_panel(main_window); } int main(int ac, char **av) { int lines, columns; char *mode; if (ac > 1 && strcmp(av[1], "-s") == 0) { /* Silence conf_read() until the real callback is set up */ conf_set_message_callback(NULL); av++; } conf_parse(av[1]); conf_read(NULL); mode = getenv("NCONFIG_MODE"); if (mode) { if (!strcasecmp(mode, "single_menu")) single_menu_mode = 1; } /* Initialize curses */ initscr(); /* set color theme */ set_colors(); cbreak(); noecho(); keypad(stdscr, TRUE); curs_set(0); getmaxyx(stdscr, lines, columns); if (columns < 75 || lines < 20) { endwin(); printf("Your terminal should have at " "least 20 lines and 75 columns\n"); return 1; } notimeout(stdscr, FALSE); #if NCURSES_REENTRANT set_escdelay(1); #else ESCDELAY = 1; #endif /* set btns menu */ curses_menu = new_menu(curses_menu_items); menu_opts_off(curses_menu, O_SHOWDESC); menu_opts_on(curses_menu, O_SHOWMATCH); menu_opts_on(curses_menu, O_ONEVALUE); menu_opts_on(curses_menu, O_NONCYCLIC); menu_opts_on(curses_menu, O_IGNORECASE); set_menu_mark(curses_menu, " "); set_menu_fore(curses_menu, attr_main_menu_fore); set_menu_back(curses_menu, attr_main_menu_back); set_menu_grey(curses_menu, attr_main_menu_grey); set_config_filename(conf_get_configname()); setup_windows(); /* check for KEY_FUNC(1) */ if (has_key(KEY_F(1)) == FALSE) { show_scroll_win(main_window, "Instructions", menu_no_f_instructions); } conf_set_message_callback(conf_message_callback); /* do the work */ while (!global_exit) { conf(&rootmenu); if (!global_exit && do_exit() == 0) break; } /* ok, we are done */ unpost_menu(curses_menu); free_menu(curses_menu); delwin(main_window); clear(); refresh(); endwin(); return 0; }
linux-master
scripts/kconfig/nconf.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2002 Roman Zippel <[email protected]> */ #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lkc.h" #define DEBUG_EXPR 0 static struct expr *expr_eliminate_yn(struct expr *e); struct expr *expr_alloc_symbol(struct symbol *sym) { struct expr *e = xcalloc(1, sizeof(*e)); e->type = E_SYMBOL; e->left.sym = sym; return e; } struct expr *expr_alloc_one(enum expr_type type, struct expr *ce) { struct expr *e = xcalloc(1, sizeof(*e)); e->type = type; e->left.expr = ce; return e; } struct expr *expr_alloc_two(enum expr_type type, struct expr *e1, struct expr *e2) { struct expr *e = xcalloc(1, sizeof(*e)); e->type = type; e->left.expr = e1; e->right.expr = e2; return e; } struct expr *expr_alloc_comp(enum expr_type type, struct symbol *s1, struct symbol *s2) { struct expr *e = xcalloc(1, sizeof(*e)); e->type = type; e->left.sym = s1; e->right.sym = s2; return e; } struct expr *expr_alloc_and(struct expr *e1, struct expr *e2) { if (!e1) return e2; return e2 ? expr_alloc_two(E_AND, e1, e2) : e1; } struct expr *expr_alloc_or(struct expr *e1, struct expr *e2) { if (!e1) return e2; return e2 ? expr_alloc_two(E_OR, e1, e2) : e1; } struct expr *expr_copy(const struct expr *org) { struct expr *e; if (!org) return NULL; e = xmalloc(sizeof(*org)); memcpy(e, org, sizeof(*org)); switch (org->type) { case E_SYMBOL: e->left = org->left; break; case E_NOT: e->left.expr = expr_copy(org->left.expr); break; case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: e->left.sym = org->left.sym; e->right.sym = org->right.sym; break; case E_AND: case E_OR: case E_LIST: e->left.expr = expr_copy(org->left.expr); e->right.expr = expr_copy(org->right.expr); break; default: fprintf(stderr, "can't copy type %d\n", e->type); free(e); e = NULL; break; } return e; } void expr_free(struct expr *e) { if (!e) return; switch (e->type) { case E_SYMBOL: break; case E_NOT: expr_free(e->left.expr); break; case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: break; case E_OR: case E_AND: expr_free(e->left.expr); expr_free(e->right.expr); break; default: fprintf(stderr, "how to free type %d?\n", e->type); break; } free(e); } static int trans_count; #define e1 (*ep1) #define e2 (*ep2) /* * expr_eliminate_eq() helper. * * Walks the two expression trees given in 'ep1' and 'ep2'. Any node that does * not have type 'type' (E_OR/E_AND) is considered a leaf, and is compared * against all other leaves. Two equal leaves are both replaced with either 'y' * or 'n' as appropriate for 'type', to be eliminated later. */ static void __expr_eliminate_eq(enum expr_type type, struct expr **ep1, struct expr **ep2) { /* Recurse down to leaves */ if (e1->type == type) { __expr_eliminate_eq(type, &e1->left.expr, &e2); __expr_eliminate_eq(type, &e1->right.expr, &e2); return; } if (e2->type == type) { __expr_eliminate_eq(type, &e1, &e2->left.expr); __expr_eliminate_eq(type, &e1, &e2->right.expr); return; } /* e1 and e2 are leaves. Compare them. */ if (e1->type == E_SYMBOL && e2->type == E_SYMBOL && e1->left.sym == e2->left.sym && (e1->left.sym == &symbol_yes || e1->left.sym == &symbol_no)) return; if (!expr_eq(e1, e2)) return; /* e1 and e2 are equal leaves. Prepare them for elimination. */ trans_count++; expr_free(e1); expr_free(e2); switch (type) { case E_OR: e1 = expr_alloc_symbol(&symbol_no); e2 = expr_alloc_symbol(&symbol_no); break; case E_AND: e1 = expr_alloc_symbol(&symbol_yes); e2 = expr_alloc_symbol(&symbol_yes); break; default: ; } } /* * Rewrites the expressions 'ep1' and 'ep2' to remove operands common to both. * Example reductions: * * ep1: A && B -> ep1: y * ep2: A && B && C -> ep2: C * * ep1: A || B -> ep1: n * ep2: A || B || C -> ep2: C * * ep1: A && (B && FOO) -> ep1: FOO * ep2: (BAR && B) && A -> ep2: BAR * * ep1: A && (B || C) -> ep1: y * ep2: (C || B) && A -> ep2: y * * Comparisons are done between all operands at the same "level" of && or ||. * For example, in the expression 'e1 && (e2 || e3) && (e4 || e5)', the * following operands will be compared: * * - 'e1', 'e2 || e3', and 'e4 || e5', against each other * - e2 against e3 * - e4 against e5 * * Parentheses are irrelevant within a single level. 'e1 && (e2 && e3)' and * '(e1 && e2) && e3' are both a single level. * * See __expr_eliminate_eq() as well. */ void expr_eliminate_eq(struct expr **ep1, struct expr **ep2) { if (!e1 || !e2) return; switch (e1->type) { case E_OR: case E_AND: __expr_eliminate_eq(e1->type, ep1, ep2); default: ; } if (e1->type != e2->type) switch (e2->type) { case E_OR: case E_AND: __expr_eliminate_eq(e2->type, ep1, ep2); default: ; } e1 = expr_eliminate_yn(e1); e2 = expr_eliminate_yn(e2); } #undef e1 #undef e2 /* * Returns true if 'e1' and 'e2' are equal, after minor simplification. Two * &&/|| expressions are considered equal if every operand in one expression * equals some operand in the other (operands do not need to appear in the same * order), recursively. */ int expr_eq(struct expr *e1, struct expr *e2) { int res, old_count; /* * A NULL expr is taken to be yes, but there's also a different way to * represent yes. expr_is_yes() checks for either representation. */ if (!e1 || !e2) return expr_is_yes(e1) && expr_is_yes(e2); if (e1->type != e2->type) return 0; switch (e1->type) { case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: return e1->left.sym == e2->left.sym && e1->right.sym == e2->right.sym; case E_SYMBOL: return e1->left.sym == e2->left.sym; case E_NOT: return expr_eq(e1->left.expr, e2->left.expr); case E_AND: case E_OR: e1 = expr_copy(e1); e2 = expr_copy(e2); old_count = trans_count; expr_eliminate_eq(&e1, &e2); res = (e1->type == E_SYMBOL && e2->type == E_SYMBOL && e1->left.sym == e2->left.sym); expr_free(e1); expr_free(e2); trans_count = old_count; return res; case E_LIST: case E_RANGE: case E_NONE: /* panic */; } if (DEBUG_EXPR) { expr_fprint(e1, stdout); printf(" = "); expr_fprint(e2, stdout); printf(" ?\n"); } return 0; } /* * Recursively performs the following simplifications in-place (as well as the * corresponding simplifications with swapped operands): * * expr && n -> n * expr && y -> expr * expr || n -> expr * expr || y -> y * * Returns the optimized expression. */ static struct expr *expr_eliminate_yn(struct expr *e) { struct expr *tmp; if (e) switch (e->type) { case E_AND: e->left.expr = expr_eliminate_yn(e->left.expr); e->right.expr = expr_eliminate_yn(e->right.expr); if (e->left.expr->type == E_SYMBOL) { if (e->left.expr->left.sym == &symbol_no) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.expr = NULL; return e; } else if (e->left.expr->left.sym == &symbol_yes) { free(e->left.expr); tmp = e->right.expr; *e = *(e->right.expr); free(tmp); return e; } } if (e->right.expr->type == E_SYMBOL) { if (e->right.expr->left.sym == &symbol_no) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.expr = NULL; return e; } else if (e->right.expr->left.sym == &symbol_yes) { free(e->right.expr); tmp = e->left.expr; *e = *(e->left.expr); free(tmp); return e; } } break; case E_OR: e->left.expr = expr_eliminate_yn(e->left.expr); e->right.expr = expr_eliminate_yn(e->right.expr); if (e->left.expr->type == E_SYMBOL) { if (e->left.expr->left.sym == &symbol_no) { free(e->left.expr); tmp = e->right.expr; *e = *(e->right.expr); free(tmp); return e; } else if (e->left.expr->left.sym == &symbol_yes) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.expr = NULL; return e; } } if (e->right.expr->type == E_SYMBOL) { if (e->right.expr->left.sym == &symbol_no) { free(e->right.expr); tmp = e->left.expr; *e = *(e->left.expr); free(tmp); return e; } else if (e->right.expr->left.sym == &symbol_yes) { expr_free(e->left.expr); expr_free(e->right.expr); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.expr = NULL; return e; } } break; default: ; } return e; } /* * bool FOO!=n => FOO */ struct expr *expr_trans_bool(struct expr *e) { if (!e) return NULL; switch (e->type) { case E_AND: case E_OR: case E_NOT: e->left.expr = expr_trans_bool(e->left.expr); e->right.expr = expr_trans_bool(e->right.expr); break; case E_UNEQUAL: // FOO!=n -> FOO if (e->left.sym->type == S_TRISTATE) { if (e->right.sym == &symbol_no) { e->type = E_SYMBOL; e->right.sym = NULL; } } break; default: ; } return e; } /* * e1 || e2 -> ? */ static struct expr *expr_join_or(struct expr *e1, struct expr *e2) { struct expr *tmp; struct symbol *sym1, *sym2; if (expr_eq(e1, e2)) return expr_copy(e1); if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT) return NULL; if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT) return NULL; if (e1->type == E_NOT) { tmp = e1->left.expr; if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL) return NULL; sym1 = tmp->left.sym; } else sym1 = e1->left.sym; if (e2->type == E_NOT) { if (e2->left.expr->type != E_SYMBOL) return NULL; sym2 = e2->left.expr->left.sym; } else sym2 = e2->left.sym; if (sym1 != sym2) return NULL; if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE) return NULL; if (sym1->type == S_TRISTATE) { if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) || (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) { // (a='y') || (a='m') -> (a!='n') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_no); } if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) { // (a='y') || (a='n') -> (a!='m') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_mod); } if (e1->type == E_EQUAL && e2->type == E_EQUAL && ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) { // (a='m') || (a='n') -> (a!='y') return expr_alloc_comp(E_UNEQUAL, sym1, &symbol_yes); } } if (sym1->type == S_BOOLEAN && sym1 == sym2) { if ((e1->type == E_NOT && e1->left.expr->type == E_SYMBOL && e2->type == E_SYMBOL) || (e2->type == E_NOT && e2->left.expr->type == E_SYMBOL && e1->type == E_SYMBOL)) return expr_alloc_symbol(&symbol_yes); } if (DEBUG_EXPR) { printf("optimize ("); expr_fprint(e1, stdout); printf(") || ("); expr_fprint(e2, stdout); printf(")?\n"); } return NULL; } static struct expr *expr_join_and(struct expr *e1, struct expr *e2) { struct expr *tmp; struct symbol *sym1, *sym2; if (expr_eq(e1, e2)) return expr_copy(e1); if (e1->type != E_EQUAL && e1->type != E_UNEQUAL && e1->type != E_SYMBOL && e1->type != E_NOT) return NULL; if (e2->type != E_EQUAL && e2->type != E_UNEQUAL && e2->type != E_SYMBOL && e2->type != E_NOT) return NULL; if (e1->type == E_NOT) { tmp = e1->left.expr; if (tmp->type != E_EQUAL && tmp->type != E_UNEQUAL && tmp->type != E_SYMBOL) return NULL; sym1 = tmp->left.sym; } else sym1 = e1->left.sym; if (e2->type == E_NOT) { if (e2->left.expr->type != E_SYMBOL) return NULL; sym2 = e2->left.expr->left.sym; } else sym2 = e2->left.sym; if (sym1 != sym2) return NULL; if (sym1->type != S_BOOLEAN && sym1->type != S_TRISTATE) return NULL; if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_yes) || (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_yes)) // (a) && (a='y') -> (a='y') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_no) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_no)) // (a) && (a!='n') -> (a) return expr_alloc_symbol(sym1); if ((e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_mod) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_mod)) // (a) && (a!='m') -> (a='y') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if (sym1->type == S_TRISTATE) { if (e1->type == E_EQUAL && e2->type == E_UNEQUAL) { // (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b' sym2 = e1->right.sym; if ((e2->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST)) return sym2 != e2->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2) : expr_alloc_symbol(&symbol_no); } if (e1->type == E_UNEQUAL && e2->type == E_EQUAL) { // (a='b') && (a!='c') -> 'b'='c' ? 'n' : a='b' sym2 = e2->right.sym; if ((e1->right.sym->flags & SYMBOL_CONST) && (sym2->flags & SYMBOL_CONST)) return sym2 != e1->right.sym ? expr_alloc_comp(E_EQUAL, sym1, sym2) : expr_alloc_symbol(&symbol_no); } if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_yes))) // (a!='y') && (a!='n') -> (a='m') return expr_alloc_comp(E_EQUAL, sym1, &symbol_mod); if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_yes && e2->right.sym == &symbol_mod) || (e1->right.sym == &symbol_mod && e2->right.sym == &symbol_yes))) // (a!='y') && (a!='m') -> (a='n') return expr_alloc_comp(E_EQUAL, sym1, &symbol_no); if (e1->type == E_UNEQUAL && e2->type == E_UNEQUAL && ((e1->right.sym == &symbol_mod && e2->right.sym == &symbol_no) || (e1->right.sym == &symbol_no && e2->right.sym == &symbol_mod))) // (a!='m') && (a!='n') -> (a='m') return expr_alloc_comp(E_EQUAL, sym1, &symbol_yes); if ((e1->type == E_SYMBOL && e2->type == E_EQUAL && e2->right.sym == &symbol_mod) || (e2->type == E_SYMBOL && e1->type == E_EQUAL && e1->right.sym == &symbol_mod) || (e1->type == E_SYMBOL && e2->type == E_UNEQUAL && e2->right.sym == &symbol_yes) || (e2->type == E_SYMBOL && e1->type == E_UNEQUAL && e1->right.sym == &symbol_yes)) return NULL; } if (DEBUG_EXPR) { printf("optimize ("); expr_fprint(e1, stdout); printf(") && ("); expr_fprint(e2, stdout); printf(")?\n"); } return NULL; } /* * expr_eliminate_dups() helper. * * Walks the two expression trees given in 'ep1' and 'ep2'. Any node that does * not have type 'type' (E_OR/E_AND) is considered a leaf, and is compared * against all other leaves to look for simplifications. */ static void expr_eliminate_dups1(enum expr_type type, struct expr **ep1, struct expr **ep2) { #define e1 (*ep1) #define e2 (*ep2) struct expr *tmp; /* Recurse down to leaves */ if (e1->type == type) { expr_eliminate_dups1(type, &e1->left.expr, &e2); expr_eliminate_dups1(type, &e1->right.expr, &e2); return; } if (e2->type == type) { expr_eliminate_dups1(type, &e1, &e2->left.expr); expr_eliminate_dups1(type, &e1, &e2->right.expr); return; } /* e1 and e2 are leaves. Compare and process them. */ if (e1 == e2) return; switch (e1->type) { case E_OR: case E_AND: expr_eliminate_dups1(e1->type, &e1, &e1); default: ; } switch (type) { case E_OR: tmp = expr_join_or(e1, e2); if (tmp) { expr_free(e1); expr_free(e2); e1 = expr_alloc_symbol(&symbol_no); e2 = tmp; trans_count++; } break; case E_AND: tmp = expr_join_and(e1, e2); if (tmp) { expr_free(e1); expr_free(e2); e1 = expr_alloc_symbol(&symbol_yes); e2 = tmp; trans_count++; } break; default: ; } #undef e1 #undef e2 } /* * Rewrites 'e' in-place to remove ("join") duplicate and other redundant * operands. * * Example simplifications: * * A || B || A -> A || B * A && B && A=y -> A=y && B * * Returns the deduplicated expression. */ struct expr *expr_eliminate_dups(struct expr *e) { int oldcount; if (!e) return e; oldcount = trans_count; while (1) { trans_count = 0; switch (e->type) { case E_OR: case E_AND: expr_eliminate_dups1(e->type, &e, &e); default: ; } if (!trans_count) /* No simplifications done in this pass. We're done */ break; e = expr_eliminate_yn(e); } trans_count = oldcount; return e; } /* * Performs various simplifications involving logical operators and * comparisons. * * Allocates and returns a new expression. */ struct expr *expr_transform(struct expr *e) { struct expr *tmp; if (!e) return NULL; switch (e->type) { case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: case E_SYMBOL: case E_LIST: break; default: e->left.expr = expr_transform(e->left.expr); e->right.expr = expr_transform(e->right.expr); } switch (e->type) { case E_EQUAL: if (e->left.sym->type != S_BOOLEAN) break; if (e->right.sym == &symbol_no) { e->type = E_NOT; e->left.expr = expr_alloc_symbol(e->left.sym); e->right.sym = NULL; break; } if (e->right.sym == &symbol_mod) { printf("boolean symbol %s tested for 'm'? test forced to 'n'\n", e->left.sym->name); e->type = E_SYMBOL; e->left.sym = &symbol_no; e->right.sym = NULL; break; } if (e->right.sym == &symbol_yes) { e->type = E_SYMBOL; e->right.sym = NULL; break; } break; case E_UNEQUAL: if (e->left.sym->type != S_BOOLEAN) break; if (e->right.sym == &symbol_no) { e->type = E_SYMBOL; e->right.sym = NULL; break; } if (e->right.sym == &symbol_mod) { printf("boolean symbol %s tested for 'm'? test forced to 'y'\n", e->left.sym->name); e->type = E_SYMBOL; e->left.sym = &symbol_yes; e->right.sym = NULL; break; } if (e->right.sym == &symbol_yes) { e->type = E_NOT; e->left.expr = expr_alloc_symbol(e->left.sym); e->right.sym = NULL; break; } break; case E_NOT: switch (e->left.expr->type) { case E_NOT: // !!a -> a tmp = e->left.expr->left.expr; free(e->left.expr); free(e); e = tmp; e = expr_transform(e); break; case E_EQUAL: case E_UNEQUAL: // !a='x' -> a!='x' tmp = e->left.expr; free(e); e = tmp; e->type = e->type == E_EQUAL ? E_UNEQUAL : E_EQUAL; break; case E_LEQ: case E_GEQ: // !a<='x' -> a>'x' tmp = e->left.expr; free(e); e = tmp; e->type = e->type == E_LEQ ? E_GTH : E_LTH; break; case E_LTH: case E_GTH: // !a<'x' -> a>='x' tmp = e->left.expr; free(e); e = tmp; e->type = e->type == E_LTH ? E_GEQ : E_LEQ; break; case E_OR: // !(a || b) -> !a && !b tmp = e->left.expr; e->type = E_AND; e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr); tmp->type = E_NOT; tmp->right.expr = NULL; e = expr_transform(e); break; case E_AND: // !(a && b) -> !a || !b tmp = e->left.expr; e->type = E_OR; e->right.expr = expr_alloc_one(E_NOT, tmp->right.expr); tmp->type = E_NOT; tmp->right.expr = NULL; e = expr_transform(e); break; case E_SYMBOL: if (e->left.expr->left.sym == &symbol_yes) { // !'y' -> 'n' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_no; break; } if (e->left.expr->left.sym == &symbol_mod) { // !'m' -> 'm' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_mod; break; } if (e->left.expr->left.sym == &symbol_no) { // !'n' -> 'y' tmp = e->left.expr; free(e); e = tmp; e->type = E_SYMBOL; e->left.sym = &symbol_yes; break; } break; default: ; } break; default: ; } return e; } int expr_contains_symbol(struct expr *dep, struct symbol *sym) { if (!dep) return 0; switch (dep->type) { case E_AND: case E_OR: return expr_contains_symbol(dep->left.expr, sym) || expr_contains_symbol(dep->right.expr, sym); case E_SYMBOL: return dep->left.sym == sym; case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: return dep->left.sym == sym || dep->right.sym == sym; case E_NOT: return expr_contains_symbol(dep->left.expr, sym); default: ; } return 0; } bool expr_depends_symbol(struct expr *dep, struct symbol *sym) { if (!dep) return false; switch (dep->type) { case E_AND: return expr_depends_symbol(dep->left.expr, sym) || expr_depends_symbol(dep->right.expr, sym); case E_SYMBOL: return dep->left.sym == sym; case E_EQUAL: if (dep->left.sym == sym) { if (dep->right.sym == &symbol_yes || dep->right.sym == &symbol_mod) return true; } break; case E_UNEQUAL: if (dep->left.sym == sym) { if (dep->right.sym == &symbol_no) return true; } break; default: ; } return false; } /* * Inserts explicit comparisons of type 'type' to symbol 'sym' into the * expression 'e'. * * Examples transformations for type == E_UNEQUAL, sym == &symbol_no: * * A -> A!=n * !A -> A=n * A && B -> !(A=n || B=n) * A || B -> !(A=n && B=n) * A && (B || C) -> !(A=n || (B=n && C=n)) * * Allocates and returns a new expression. */ struct expr *expr_trans_compare(struct expr *e, enum expr_type type, struct symbol *sym) { struct expr *e1, *e2; if (!e) { e = expr_alloc_symbol(sym); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; } switch (e->type) { case E_AND: e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym); e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym); if (sym == &symbol_yes) e = expr_alloc_two(E_AND, e1, e2); if (sym == &symbol_no) e = expr_alloc_two(E_OR, e1, e2); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; case E_OR: e1 = expr_trans_compare(e->left.expr, E_EQUAL, sym); e2 = expr_trans_compare(e->right.expr, E_EQUAL, sym); if (sym == &symbol_yes) e = expr_alloc_two(E_OR, e1, e2); if (sym == &symbol_no) e = expr_alloc_two(E_AND, e1, e2); if (type == E_UNEQUAL) e = expr_alloc_one(E_NOT, e); return e; case E_NOT: return expr_trans_compare(e->left.expr, type == E_EQUAL ? E_UNEQUAL : E_EQUAL, sym); case E_UNEQUAL: case E_LTH: case E_LEQ: case E_GTH: case E_GEQ: case E_EQUAL: if (type == E_EQUAL) { if (sym == &symbol_yes) return expr_copy(e); if (sym == &symbol_mod) return expr_alloc_symbol(&symbol_no); if (sym == &symbol_no) return expr_alloc_one(E_NOT, expr_copy(e)); } else { if (sym == &symbol_yes) return expr_alloc_one(E_NOT, expr_copy(e)); if (sym == &symbol_mod) return expr_alloc_symbol(&symbol_yes); if (sym == &symbol_no) return expr_copy(e); } break; case E_SYMBOL: return expr_alloc_comp(type, e->left.sym, sym); case E_LIST: case E_RANGE: case E_NONE: /* panic */; } return NULL; } enum string_value_kind { k_string, k_signed, k_unsigned, }; union string_value { unsigned long long u; signed long long s; }; static enum string_value_kind expr_parse_string(const char *str, enum symbol_type type, union string_value *val) { char *tail; enum string_value_kind kind; errno = 0; switch (type) { case S_BOOLEAN: case S_TRISTATE: val->s = !strcmp(str, "n") ? 0 : !strcmp(str, "m") ? 1 : !strcmp(str, "y") ? 2 : -1; return k_signed; case S_INT: val->s = strtoll(str, &tail, 10); kind = k_signed; break; case S_HEX: val->u = strtoull(str, &tail, 16); kind = k_unsigned; break; default: val->s = strtoll(str, &tail, 0); kind = k_signed; break; } return !errno && !*tail && tail > str && isxdigit(tail[-1]) ? kind : k_string; } tristate expr_calc_value(struct expr *e) { tristate val1, val2; const char *str1, *str2; enum string_value_kind k1 = k_string, k2 = k_string; union string_value lval = {}, rval = {}; int res; if (!e) return yes; switch (e->type) { case E_SYMBOL: sym_calc_value(e->left.sym); return e->left.sym->curr.tri; case E_AND: val1 = expr_calc_value(e->left.expr); val2 = expr_calc_value(e->right.expr); return EXPR_AND(val1, val2); case E_OR: val1 = expr_calc_value(e->left.expr); val2 = expr_calc_value(e->right.expr); return EXPR_OR(val1, val2); case E_NOT: val1 = expr_calc_value(e->left.expr); return EXPR_NOT(val1); case E_EQUAL: case E_GEQ: case E_GTH: case E_LEQ: case E_LTH: case E_UNEQUAL: break; default: printf("expr_calc_value: %d?\n", e->type); return no; } sym_calc_value(e->left.sym); sym_calc_value(e->right.sym); str1 = sym_get_string_value(e->left.sym); str2 = sym_get_string_value(e->right.sym); if (e->left.sym->type != S_STRING || e->right.sym->type != S_STRING) { k1 = expr_parse_string(str1, e->left.sym->type, &lval); k2 = expr_parse_string(str2, e->right.sym->type, &rval); } if (k1 == k_string || k2 == k_string) res = strcmp(str1, str2); else if (k1 == k_unsigned || k2 == k_unsigned) res = (lval.u > rval.u) - (lval.u < rval.u); else /* if (k1 == k_signed && k2 == k_signed) */ res = (lval.s > rval.s) - (lval.s < rval.s); switch(e->type) { case E_EQUAL: return res ? no : yes; case E_GEQ: return res >= 0 ? yes : no; case E_GTH: return res > 0 ? yes : no; case E_LEQ: return res <= 0 ? yes : no; case E_LTH: return res < 0 ? yes : no; case E_UNEQUAL: return res ? yes : no; default: printf("expr_calc_value: relation %d?\n", e->type); return no; } } static int expr_compare_type(enum expr_type t1, enum expr_type t2) { if (t1 == t2) return 0; switch (t1) { case E_LEQ: case E_LTH: case E_GEQ: case E_GTH: if (t2 == E_EQUAL || t2 == E_UNEQUAL) return 1; case E_EQUAL: case E_UNEQUAL: if (t2 == E_NOT) return 1; case E_NOT: if (t2 == E_AND) return 1; case E_AND: if (t2 == E_OR) return 1; case E_OR: if (t2 == E_LIST) return 1; case E_LIST: if (t2 == 0) return 1; default: return -1; } printf("[%dgt%d?]", t1, t2); return 0; } void expr_print(struct expr *e, void (*fn)(void *, struct symbol *, const char *), void *data, int prevtoken) { if (!e) { fn(data, NULL, "y"); return; } if (expr_compare_type(prevtoken, e->type) > 0) fn(data, NULL, "("); switch (e->type) { case E_SYMBOL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); break; case E_NOT: fn(data, NULL, "!"); expr_print(e->left.expr, fn, data, E_NOT); break; case E_EQUAL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, "="); fn(data, e->right.sym, e->right.sym->name); break; case E_LEQ: case E_LTH: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, e->type == E_LEQ ? "<=" : "<"); fn(data, e->right.sym, e->right.sym->name); break; case E_GEQ: case E_GTH: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, e->type == E_GEQ ? ">=" : ">"); fn(data, e->right.sym, e->right.sym->name); break; case E_UNEQUAL: if (e->left.sym->name) fn(data, e->left.sym, e->left.sym->name); else fn(data, NULL, "<choice>"); fn(data, NULL, "!="); fn(data, e->right.sym, e->right.sym->name); break; case E_OR: expr_print(e->left.expr, fn, data, E_OR); fn(data, NULL, " || "); expr_print(e->right.expr, fn, data, E_OR); break; case E_AND: expr_print(e->left.expr, fn, data, E_AND); fn(data, NULL, " && "); expr_print(e->right.expr, fn, data, E_AND); break; case E_LIST: fn(data, e->right.sym, e->right.sym->name); if (e->left.expr) { fn(data, NULL, " ^ "); expr_print(e->left.expr, fn, data, E_LIST); } break; case E_RANGE: fn(data, NULL, "["); fn(data, e->left.sym, e->left.sym->name); fn(data, NULL, " "); fn(data, e->right.sym, e->right.sym->name); fn(data, NULL, "]"); break; default: { char buf[32]; sprintf(buf, "<unknown type %d>", e->type); fn(data, NULL, buf); break; } } if (expr_compare_type(prevtoken, e->type) > 0) fn(data, NULL, ")"); } static void expr_print_file_helper(void *data, struct symbol *sym, const char *str) { xfwrite(str, strlen(str), 1, data); } void expr_fprint(struct expr *e, FILE *out) { expr_print(e, expr_print_file_helper, out, E_NONE); } static void expr_print_gstr_helper(void *data, struct symbol *sym, const char *str) { struct gstr *gs = (struct gstr*)data; const char *sym_str = NULL; if (sym) sym_str = sym_get_string_value(sym); if (gs->max_width) { unsigned extra_length = strlen(str); const char *last_cr = strrchr(gs->s, '\n'); unsigned last_line_length; if (sym_str) extra_length += 4 + strlen(sym_str); if (!last_cr) last_cr = gs->s; last_line_length = strlen(gs->s) - (last_cr - gs->s); if ((last_line_length + extra_length) > gs->max_width) str_append(gs, "\\\n"); } str_append(gs, str); if (sym && sym->type != S_UNKNOWN) str_printf(gs, " [=%s]", sym_str); } void expr_gstr_print(struct expr *e, struct gstr *gs) { expr_print(e, expr_print_gstr_helper, gs, E_NONE); } /* * Transform the top level "||" tokens into newlines and prepend each * line with a minus. This makes expressions much easier to read. * Suitable for reverse dependency expressions. */ static void expr_print_revdep(struct expr *e, void (*fn)(void *, struct symbol *, const char *), void *data, tristate pr_type, const char **title) { if (e->type == E_OR) { expr_print_revdep(e->left.expr, fn, data, pr_type, title); expr_print_revdep(e->right.expr, fn, data, pr_type, title); } else if (expr_calc_value(e) == pr_type) { if (*title) { fn(data, NULL, *title); *title = NULL; } fn(data, NULL, " - "); expr_print(e, fn, data, E_NONE); fn(data, NULL, "\n"); } } void expr_gstr_print_revdep(struct expr *e, struct gstr *gs, tristate pr_type, const char *title) { expr_print_revdep(e, expr_print_gstr_helper, gs, pr_type, &title); }
linux-master
scripts/kconfig/expr.c
// SPDX-License-Identifier: GPL-2.0+ /* * inputbox.c -- implements the input box * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ #include "dialog.h" char dialog_input_result[MAX_LEN + 1]; /* * Print the termination buttons */ static void print_buttons(WINDOW * dialog, int height, int width, int selected) { int x = width / 2 - 11; int y = height - 2; print_button(dialog, " Ok ", y, x, selected == 0); print_button(dialog, " Help ", y, x + 14, selected == 1); wmove(dialog, y, x + 1 + 14 * selected); wrefresh(dialog); } /* * Display a dialog box for inputing a string */ int dialog_inputbox(const char *title, const char *prompt, int height, int width, const char *init) { int i, x, y, box_y, box_x, box_width; int input_x = 0, key = 0, button = -1; int show_x, len, pos; char *instr = dialog_input_result; WINDOW *dialog; if (!init) instr[0] = '\0'; else strcpy(instr, init); do_resize: if (getmaxy(stdscr) <= (height - INPUTBOX_HEIGTH_MIN)) return -ERRDISPLAYTOOSMALL; if (getmaxx(stdscr) <= (width - INPUTBOX_WIDTH_MIN)) return -ERRDISPLAYTOOSMALL; /* center dialog box on screen */ x = (getmaxx(stdscr) - width) / 2; y = (getmaxy(stdscr) - height) / 2; draw_shadow(stdscr, y, x, height, width); dialog = newwin(height, width, y, x); keypad(dialog, TRUE); draw_box(dialog, 0, 0, height, width, dlg.dialog.atr, dlg.border.atr); wattrset(dialog, dlg.border.atr); mvwaddch(dialog, height - 3, 0, ACS_LTEE); for (i = 0; i < width - 2; i++) waddch(dialog, ACS_HLINE); wattrset(dialog, dlg.dialog.atr); waddch(dialog, ACS_RTEE); print_title(dialog, title, width); wattrset(dialog, dlg.dialog.atr); print_autowrap(dialog, prompt, width - 2, 1, 3); /* Draw the input field box */ box_width = width - 6; getyx(dialog, y, x); box_y = y + 2; box_x = (width - box_width) / 2; draw_box(dialog, y + 1, box_x - 1, 3, box_width + 2, dlg.dialog.atr, dlg.border.atr); print_buttons(dialog, height, width, 0); /* Set up the initial value */ wmove(dialog, box_y, box_x); wattrset(dialog, dlg.inputbox.atr); len = strlen(instr); pos = len; if (len >= box_width) { show_x = len - box_width + 1; input_x = box_width - 1; for (i = 0; i < box_width - 1; i++) waddch(dialog, instr[show_x + i]); } else { show_x = 0; input_x = len; waddstr(dialog, instr); } wmove(dialog, box_y, box_x + input_x); wrefresh(dialog); while (key != KEY_ESC) { key = wgetch(dialog); if (button == -1) { /* Input box selected */ switch (key) { case TAB: case KEY_UP: case KEY_DOWN: break; case KEY_BACKSPACE: case 8: /* ^H */ case 127: /* ^? */ if (pos) { wattrset(dialog, dlg.inputbox.atr); if (input_x == 0) { show_x--; } else input_x--; if (pos < len) { for (i = pos - 1; i < len; i++) { instr[i] = instr[i+1]; } } pos--; len--; instr[len] = '\0'; wmove(dialog, box_y, box_x); for (i = 0; i < box_width; i++) { if (!instr[show_x + i]) { waddch(dialog, ' '); break; } waddch(dialog, instr[show_x + i]); } wmove(dialog, box_y, input_x + box_x); wrefresh(dialog); } continue; case KEY_LEFT: if (pos > 0) { if (input_x > 0) { wmove(dialog, box_y, --input_x + box_x); } else if (input_x == 0) { show_x--; wmove(dialog, box_y, box_x); for (i = 0; i < box_width; i++) { if (!instr[show_x + i]) { waddch(dialog, ' '); break; } waddch(dialog, instr[show_x + i]); } wmove(dialog, box_y, box_x); } pos--; } continue; case KEY_RIGHT: if (pos < len) { if (input_x < box_width - 1) { wmove(dialog, box_y, ++input_x + box_x); } else if (input_x == box_width - 1) { show_x++; wmove(dialog, box_y, box_x); for (i = 0; i < box_width; i++) { if (!instr[show_x + i]) { waddch(dialog, ' '); break; } waddch(dialog, instr[show_x + i]); } wmove(dialog, box_y, input_x + box_x); } pos++; } continue; default: if (key < 0x100 && isprint(key)) { if (len < MAX_LEN) { wattrset(dialog, dlg.inputbox.atr); if (pos < len) { for (i = len; i > pos; i--) instr[i] = instr[i-1]; instr[pos] = key; } else { instr[len] = key; } pos++; len++; instr[len] = '\0'; if (input_x == box_width - 1) { show_x++; } else { input_x++; } wmove(dialog, box_y, box_x); for (i = 0; i < box_width; i++) { if (!instr[show_x + i]) { waddch(dialog, ' '); break; } waddch(dialog, instr[show_x + i]); } wmove(dialog, box_y, input_x + box_x); wrefresh(dialog); } else flash(); /* Alarm user about overflow */ continue; } } } switch (key) { case 'O': case 'o': delwin(dialog); return 0; case 'H': case 'h': delwin(dialog); return 1; case KEY_UP: case KEY_LEFT: switch (button) { case -1: button = 1; /* Indicates "Help" button is selected */ print_buttons(dialog, height, width, 1); break; case 0: button = -1; /* Indicates input box is selected */ print_buttons(dialog, height, width, 0); wmove(dialog, box_y, box_x + input_x); wrefresh(dialog); break; case 1: button = 0; /* Indicates "OK" button is selected */ print_buttons(dialog, height, width, 0); break; } break; case TAB: case KEY_DOWN: case KEY_RIGHT: switch (button) { case -1: button = 0; /* Indicates "OK" button is selected */ print_buttons(dialog, height, width, 0); break; case 0: button = 1; /* Indicates "Help" button is selected */ print_buttons(dialog, height, width, 1); break; case 1: button = -1; /* Indicates input box is selected */ print_buttons(dialog, height, width, 0); wmove(dialog, box_y, box_x + input_x); wrefresh(dialog); break; } break; case ' ': case '\n': delwin(dialog); return (button == -1 ? 0 : button); case 'X': case 'x': key = KEY_ESC; break; case KEY_ESC: key = on_key_esc(dialog); break; case KEY_RESIZE: delwin(dialog); on_key_resize(); goto do_resize; } } delwin(dialog); return KEY_ESC; /* ESC pressed */ }
linux-master
scripts/kconfig/lxdialog/inputbox.c
// SPDX-License-Identifier: GPL-2.0+ /* * util.c * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ #include <stdarg.h> #include "dialog.h" /* Needed in signal handler in mconf.c */ int saved_x, saved_y; struct dialog_info dlg; static void set_mono_theme(void) { dlg.screen.atr = A_NORMAL; dlg.shadow.atr = A_NORMAL; dlg.dialog.atr = A_NORMAL; dlg.title.atr = A_BOLD; dlg.border.atr = A_NORMAL; dlg.button_active.atr = A_REVERSE; dlg.button_inactive.atr = A_DIM; dlg.button_key_active.atr = A_REVERSE; dlg.button_key_inactive.atr = A_BOLD; dlg.button_label_active.atr = A_REVERSE; dlg.button_label_inactive.atr = A_NORMAL; dlg.inputbox.atr = A_NORMAL; dlg.inputbox_border.atr = A_NORMAL; dlg.searchbox.atr = A_NORMAL; dlg.searchbox_title.atr = A_BOLD; dlg.searchbox_border.atr = A_NORMAL; dlg.position_indicator.atr = A_BOLD; dlg.menubox.atr = A_NORMAL; dlg.menubox_border.atr = A_NORMAL; dlg.item.atr = A_NORMAL; dlg.item_selected.atr = A_REVERSE; dlg.tag.atr = A_BOLD; dlg.tag_selected.atr = A_REVERSE; dlg.tag_key.atr = A_BOLD; dlg.tag_key_selected.atr = A_REVERSE; dlg.check.atr = A_BOLD; dlg.check_selected.atr = A_REVERSE; dlg.uarrow.atr = A_BOLD; dlg.darrow.atr = A_BOLD; } #define DLG_COLOR(dialog, f, b, h) \ do { \ dlg.dialog.fg = (f); \ dlg.dialog.bg = (b); \ dlg.dialog.hl = (h); \ } while (0) static void set_classic_theme(void) { DLG_COLOR(screen, COLOR_CYAN, COLOR_BLUE, true); DLG_COLOR(shadow, COLOR_BLACK, COLOR_BLACK, true); DLG_COLOR(dialog, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(title, COLOR_YELLOW, COLOR_WHITE, true); DLG_COLOR(border, COLOR_WHITE, COLOR_WHITE, true); DLG_COLOR(button_active, COLOR_WHITE, COLOR_BLUE, true); DLG_COLOR(button_inactive, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(button_key_active, COLOR_WHITE, COLOR_BLUE, true); DLG_COLOR(button_key_inactive, COLOR_RED, COLOR_WHITE, false); DLG_COLOR(button_label_active, COLOR_YELLOW, COLOR_BLUE, true); DLG_COLOR(button_label_inactive, COLOR_BLACK, COLOR_WHITE, true); DLG_COLOR(inputbox, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(inputbox_border, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(searchbox, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(searchbox_title, COLOR_YELLOW, COLOR_WHITE, true); DLG_COLOR(searchbox_border, COLOR_WHITE, COLOR_WHITE, true); DLG_COLOR(position_indicator, COLOR_YELLOW, COLOR_WHITE, true); DLG_COLOR(menubox, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(menubox_border, COLOR_WHITE, COLOR_WHITE, true); DLG_COLOR(item, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(item_selected, COLOR_WHITE, COLOR_BLUE, true); DLG_COLOR(tag, COLOR_YELLOW, COLOR_WHITE, true); DLG_COLOR(tag_selected, COLOR_YELLOW, COLOR_BLUE, true); DLG_COLOR(tag_key, COLOR_YELLOW, COLOR_WHITE, true); DLG_COLOR(tag_key_selected, COLOR_YELLOW, COLOR_BLUE, true); DLG_COLOR(check, COLOR_BLACK, COLOR_WHITE, false); DLG_COLOR(check_selected, COLOR_WHITE, COLOR_BLUE, true); DLG_COLOR(uarrow, COLOR_GREEN, COLOR_WHITE, true); DLG_COLOR(darrow, COLOR_GREEN, COLOR_WHITE, true); } static void set_blackbg_theme(void) { DLG_COLOR(screen, COLOR_RED, COLOR_BLACK, true); DLG_COLOR(shadow, COLOR_BLACK, COLOR_BLACK, false); DLG_COLOR(dialog, COLOR_WHITE, COLOR_BLACK, false); DLG_COLOR(title, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(border, COLOR_BLACK, COLOR_BLACK, true); DLG_COLOR(button_active, COLOR_YELLOW, COLOR_RED, false); DLG_COLOR(button_inactive, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(button_key_active, COLOR_YELLOW, COLOR_RED, true); DLG_COLOR(button_key_inactive, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(button_label_active, COLOR_WHITE, COLOR_RED, false); DLG_COLOR(button_label_inactive, COLOR_BLACK, COLOR_BLACK, true); DLG_COLOR(inputbox, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(inputbox_border, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(searchbox, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(searchbox_title, COLOR_YELLOW, COLOR_BLACK, true); DLG_COLOR(searchbox_border, COLOR_BLACK, COLOR_BLACK, true); DLG_COLOR(position_indicator, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(menubox, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(menubox_border, COLOR_BLACK, COLOR_BLACK, true); DLG_COLOR(item, COLOR_WHITE, COLOR_BLACK, false); DLG_COLOR(item_selected, COLOR_WHITE, COLOR_RED, false); DLG_COLOR(tag, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(tag_selected, COLOR_YELLOW, COLOR_RED, true); DLG_COLOR(tag_key, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(tag_key_selected, COLOR_YELLOW, COLOR_RED, true); DLG_COLOR(check, COLOR_YELLOW, COLOR_BLACK, false); DLG_COLOR(check_selected, COLOR_YELLOW, COLOR_RED, true); DLG_COLOR(uarrow, COLOR_RED, COLOR_BLACK, false); DLG_COLOR(darrow, COLOR_RED, COLOR_BLACK, false); } static void set_bluetitle_theme(void) { set_classic_theme(); DLG_COLOR(title, COLOR_BLUE, COLOR_WHITE, true); DLG_COLOR(button_key_active, COLOR_YELLOW, COLOR_BLUE, true); DLG_COLOR(button_label_active, COLOR_WHITE, COLOR_BLUE, true); DLG_COLOR(searchbox_title, COLOR_BLUE, COLOR_WHITE, true); DLG_COLOR(position_indicator, COLOR_BLUE, COLOR_WHITE, true); DLG_COLOR(tag, COLOR_BLUE, COLOR_WHITE, true); DLG_COLOR(tag_key, COLOR_BLUE, COLOR_WHITE, true); } /* * Select color theme */ static int set_theme(const char *theme) { int use_color = 1; if (!theme) set_bluetitle_theme(); else if (strcmp(theme, "classic") == 0) set_classic_theme(); else if (strcmp(theme, "bluetitle") == 0) set_bluetitle_theme(); else if (strcmp(theme, "blackbg") == 0) set_blackbg_theme(); else if (strcmp(theme, "mono") == 0) use_color = 0; return use_color; } static void init_one_color(struct dialog_color *color) { static int pair = 0; pair++; init_pair(pair, color->fg, color->bg); if (color->hl) color->atr = A_BOLD | COLOR_PAIR(pair); else color->atr = COLOR_PAIR(pair); } static void init_dialog_colors(void) { init_one_color(&dlg.screen); init_one_color(&dlg.shadow); init_one_color(&dlg.dialog); init_one_color(&dlg.title); init_one_color(&dlg.border); init_one_color(&dlg.button_active); init_one_color(&dlg.button_inactive); init_one_color(&dlg.button_key_active); init_one_color(&dlg.button_key_inactive); init_one_color(&dlg.button_label_active); init_one_color(&dlg.button_label_inactive); init_one_color(&dlg.inputbox); init_one_color(&dlg.inputbox_border); init_one_color(&dlg.searchbox); init_one_color(&dlg.searchbox_title); init_one_color(&dlg.searchbox_border); init_one_color(&dlg.position_indicator); init_one_color(&dlg.menubox); init_one_color(&dlg.menubox_border); init_one_color(&dlg.item); init_one_color(&dlg.item_selected); init_one_color(&dlg.tag); init_one_color(&dlg.tag_selected); init_one_color(&dlg.tag_key); init_one_color(&dlg.tag_key_selected); init_one_color(&dlg.check); init_one_color(&dlg.check_selected); init_one_color(&dlg.uarrow); init_one_color(&dlg.darrow); } /* * Setup for color display */ static void color_setup(const char *theme) { int use_color; use_color = set_theme(theme); if (use_color && has_colors()) { start_color(); init_dialog_colors(); } else set_mono_theme(); } /* * Set window to attribute 'attr' */ void attr_clear(WINDOW * win, int height, int width, chtype attr) { int i, j; wattrset(win, attr); for (i = 0; i < height; i++) { wmove(win, i, 0); for (j = 0; j < width; j++) waddch(win, ' '); } touchwin(win); } void dialog_clear(void) { int lines, columns; lines = getmaxy(stdscr); columns = getmaxx(stdscr); attr_clear(stdscr, lines, columns, dlg.screen.atr); /* Display background title if it exists ... - SLH */ if (dlg.backtitle != NULL) { int i, len = 0, skip = 0; struct subtitle_list *pos; wattrset(stdscr, dlg.screen.atr); mvwaddstr(stdscr, 0, 1, (char *)dlg.backtitle); for (pos = dlg.subtitles; pos != NULL; pos = pos->next) { /* 3 is for the arrow and spaces */ len += strlen(pos->text) + 3; } wmove(stdscr, 1, 1); if (len > columns - 2) { const char *ellipsis = "[...] "; waddstr(stdscr, ellipsis); skip = len - (columns - 2 - strlen(ellipsis)); } for (pos = dlg.subtitles; pos != NULL; pos = pos->next) { if (skip == 0) waddch(stdscr, ACS_RARROW); else skip--; if (skip == 0) waddch(stdscr, ' '); else skip--; if (skip < strlen(pos->text)) { waddstr(stdscr, pos->text + skip); skip = 0; } else skip -= strlen(pos->text); if (skip == 0) waddch(stdscr, ' '); else skip--; } for (i = len + 1; i < columns - 1; i++) waddch(stdscr, ACS_HLINE); } wnoutrefresh(stdscr); } /* * Do some initialization for dialog */ int init_dialog(const char *backtitle) { int height, width; initscr(); /* Init curses */ /* Get current cursor position for signal handler in mconf.c */ getyx(stdscr, saved_y, saved_x); getmaxyx(stdscr, height, width); if (height < WINDOW_HEIGTH_MIN || width < WINDOW_WIDTH_MIN) { endwin(); return -ERRDISPLAYTOOSMALL; } dlg.backtitle = backtitle; color_setup(getenv("MENUCONFIG_COLOR")); keypad(stdscr, TRUE); cbreak(); noecho(); dialog_clear(); return 0; } void set_dialog_backtitle(const char *backtitle) { dlg.backtitle = backtitle; } void set_dialog_subtitles(struct subtitle_list *subtitles) { dlg.subtitles = subtitles; } /* * End using dialog functions. */ void end_dialog(int x, int y) { /* move cursor back to original position */ move(y, x); refresh(); endwin(); } /* Print the title of the dialog. Center the title and truncate * tile if wider than dialog (- 2 chars). **/ void print_title(WINDOW *dialog, const char *title, int width) { if (title) { int tlen = MIN(width - 2, strlen(title)); wattrset(dialog, dlg.title.atr); mvwaddch(dialog, 0, (width - tlen) / 2 - 1, ' '); mvwaddnstr(dialog, 0, (width - tlen)/2, title, tlen); waddch(dialog, ' '); } } /* * Print a string of text in a window, automatically wrap around to the * next line if the string is too long to fit on one line. Newline * characters '\n' are properly processed. We start on a new line * if there is no room for at least 4 nonblanks following a double-space. */ void print_autowrap(WINDOW * win, const char *prompt, int width, int y, int x) { int newl, cur_x, cur_y; int prompt_len, room, wlen; char tempstr[MAX_LEN + 1], *word, *sp, *sp2, *newline_separator = 0; strcpy(tempstr, prompt); prompt_len = strlen(tempstr); if (prompt_len <= width - x * 2) { /* If prompt is short */ wmove(win, y, (width - prompt_len) / 2); waddstr(win, tempstr); } else { cur_x = x; cur_y = y; newl = 1; word = tempstr; while (word && *word) { sp = strpbrk(word, "\n "); if (sp && *sp == '\n') newline_separator = sp; if (sp) *sp++ = 0; /* Wrap to next line if either the word does not fit, or it is the first word of a new sentence, and it is short, and the next word does not fit. */ room = width - cur_x; wlen = strlen(word); if (wlen > room || (newl && wlen < 4 && sp && wlen + 1 + strlen(sp) > room && (!(sp2 = strpbrk(sp, "\n ")) || wlen + 1 + (sp2 - sp) > room))) { cur_y++; cur_x = x; } wmove(win, cur_y, cur_x); waddstr(win, word); getyx(win, cur_y, cur_x); /* Move to the next line if the word separator was a newline */ if (newline_separator) { cur_y++; cur_x = x; newline_separator = 0; } else cur_x++; if (sp && *sp == ' ') { cur_x++; /* double space */ while (*++sp == ' ') ; newl = 1; } else newl = 0; word = sp; } } } /* * Print a button */ void print_button(WINDOW * win, const char *label, int y, int x, int selected) { int i, temp; wmove(win, y, x); wattrset(win, selected ? dlg.button_active.atr : dlg.button_inactive.atr); waddstr(win, "<"); temp = strspn(label, " "); label += temp; wattrset(win, selected ? dlg.button_label_active.atr : dlg.button_label_inactive.atr); for (i = 0; i < temp; i++) waddch(win, ' '); wattrset(win, selected ? dlg.button_key_active.atr : dlg.button_key_inactive.atr); waddch(win, label[0]); wattrset(win, selected ? dlg.button_label_active.atr : dlg.button_label_inactive.atr); waddstr(win, (char *)label + 1); wattrset(win, selected ? dlg.button_active.atr : dlg.button_inactive.atr); waddstr(win, ">"); wmove(win, y, x + temp + 1); } /* * Draw a rectangular box with line drawing characters */ void draw_box(WINDOW * win, int y, int x, int height, int width, chtype box, chtype border) { int i, j; wattrset(win, 0); for (i = 0; i < height; i++) { wmove(win, y + i, x); for (j = 0; j < width; j++) if (!i && !j) waddch(win, border | ACS_ULCORNER); else if (i == height - 1 && !j) waddch(win, border | ACS_LLCORNER); else if (!i && j == width - 1) waddch(win, box | ACS_URCORNER); else if (i == height - 1 && j == width - 1) waddch(win, box | ACS_LRCORNER); else if (!i) waddch(win, border | ACS_HLINE); else if (i == height - 1) waddch(win, box | ACS_HLINE); else if (!j) waddch(win, border | ACS_VLINE); else if (j == width - 1) waddch(win, box | ACS_VLINE); else waddch(win, box | ' '); } } /* * Draw shadows along the right and bottom edge to give a more 3D look * to the boxes */ void draw_shadow(WINDOW * win, int y, int x, int height, int width) { int i; if (has_colors()) { /* Whether terminal supports color? */ wattrset(win, dlg.shadow.atr); wmove(win, y + height, x + 2); for (i = 0; i < width; i++) waddch(win, winch(win) & A_CHARTEXT); for (i = y + 1; i < y + height + 1; i++) { wmove(win, i, x + width); waddch(win, winch(win) & A_CHARTEXT); waddch(win, winch(win) & A_CHARTEXT); } wnoutrefresh(win); } } /* * Return the position of the first alphabetic character in a string. */ int first_alpha(const char *string, const char *exempt) { int i, in_paren = 0, c; for (i = 0; i < strlen(string); i++) { c = tolower(string[i]); if (strchr("<[(", c)) ++in_paren; if (strchr(">])", c) && in_paren > 0) --in_paren; if ((!in_paren) && isalpha(c) && strchr(exempt, c) == 0) return i; } return 0; } /* * ncurses uses ESC to detect escaped char sequences. This resutl in * a small timeout before ESC is actually delivered to the application. * lxdialog suggest <ESC> <ESC> which is correctly translated to two * times esc. But then we need to ignore the second esc to avoid stepping * out one menu too much. Filter away all escaped key sequences since * keypad(FALSE) turn off ncurses support for escape sequences - and that's * needed to make notimeout() do as expected. */ int on_key_esc(WINDOW *win) { int key; int key2; int key3; nodelay(win, TRUE); keypad(win, FALSE); key = wgetch(win); key2 = wgetch(win); do { key3 = wgetch(win); } while (key3 != ERR); nodelay(win, FALSE); keypad(win, TRUE); if (key == KEY_ESC && key2 == ERR) return KEY_ESC; else if (key != ERR && key != KEY_ESC && key2 == ERR) ungetch(key); return -1; } /* redraw screen in new size */ int on_key_resize(void) { dialog_clear(); return KEY_RESIZE; } struct dialog_list *item_cur; struct dialog_list item_nil; struct dialog_list *item_head; void item_reset(void) { struct dialog_list *p, *next; for (p = item_head; p; p = next) { next = p->next; free(p); } item_head = NULL; item_cur = &item_nil; } void item_make(const char *fmt, ...) { va_list ap; struct dialog_list *p = malloc(sizeof(*p)); if (item_head) item_cur->next = p; else item_head = p; item_cur = p; memset(p, 0, sizeof(*p)); va_start(ap, fmt); vsnprintf(item_cur->node.str, sizeof(item_cur->node.str), fmt, ap); va_end(ap); } void item_add_str(const char *fmt, ...) { va_list ap; size_t avail; avail = sizeof(item_cur->node.str) - strlen(item_cur->node.str); va_start(ap, fmt); vsnprintf(item_cur->node.str + strlen(item_cur->node.str), avail, fmt, ap); item_cur->node.str[sizeof(item_cur->node.str) - 1] = '\0'; va_end(ap); } void item_set_tag(char tag) { item_cur->node.tag = tag; } void item_set_data(void *ptr) { item_cur->node.data = ptr; } void item_set_selected(int val) { item_cur->node.selected = val; } int item_activate_selected(void) { item_foreach() if (item_is_selected()) return 1; return 0; } void *item_data(void) { return item_cur->node.data; } char item_tag(void) { return item_cur->node.tag; } int item_count(void) { int n = 0; struct dialog_list *p; for (p = item_head; p; p = p->next) n++; return n; } void item_set(int n) { int i = 0; item_foreach() if (i++ == n) return; } int item_n(void) { int n = 0; struct dialog_list *p; for (p = item_head; p; p = p->next) { if (p == item_cur) return n; n++; } return 0; } const char *item_str(void) { return item_cur->node.str; } int item_is_selected(void) { return (item_cur->node.selected != 0); } int item_is_tag(char tag) { return (item_cur->node.tag == tag); }
linux-master
scripts/kconfig/lxdialog/util.c
// SPDX-License-Identifier: GPL-2.0+ /* * textbox.c -- implements the text box * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ #include "dialog.h" static int hscroll; static int begin_reached, end_reached, page_length; static const char *buf, *page; static size_t start, end; /* * Go back 'n' lines in text. Called by dialog_textbox(). * 'page' will be updated to point to the desired line in 'buf'. */ static void back_lines(int n) { int i; begin_reached = 0; /* Go back 'n' lines */ for (i = 0; i < n; i++) { if (*page == '\0') { if (end_reached) { end_reached = 0; continue; } } if (page == buf) { begin_reached = 1; return; } page--; do { if (page == buf) { begin_reached = 1; return; } page--; } while (*page != '\n'); page++; } } /* * Return current line of text. Called by dialog_textbox() and print_line(). * 'page' should point to start of current line before calling, and will be * updated to point to start of next line. */ static char *get_line(void) { int i = 0; static char line[MAX_LEN + 1]; end_reached = 0; while (*page != '\n') { if (*page == '\0') { end_reached = 1; break; } else if (i < MAX_LEN) line[i++] = *(page++); else { /* Truncate lines longer than MAX_LEN characters */ if (i == MAX_LEN) line[i++] = '\0'; page++; } } if (i <= MAX_LEN) line[i] = '\0'; if (!end_reached) page++; /* move past '\n' */ return line; } /* * Print a new line of text. */ static void print_line(WINDOW *win, int row, int width) { char *line; line = get_line(); line += MIN(strlen(line), hscroll); /* Scroll horizontally */ wmove(win, row, 0); /* move cursor to correct line */ waddch(win, ' '); waddnstr(win, line, MIN(strlen(line), width - 2)); /* Clear 'residue' of previous line */ wclrtoeol(win); } /* * Print a new page of text. */ static void print_page(WINDOW *win, int height, int width) { int i, passed_end = 0; page_length = 0; for (i = 0; i < height; i++) { print_line(win, i, width); if (!passed_end) page_length++; if (end_reached && !passed_end) passed_end = 1; } wnoutrefresh(win); } /* * Print current position */ static void print_position(WINDOW *win) { int percent; wattrset(win, dlg.position_indicator.atr); wbkgdset(win, dlg.position_indicator.atr & A_COLOR); percent = (page - buf) * 100 / strlen(buf); wmove(win, getmaxy(win) - 3, getmaxx(win) - 9); wprintw(win, "(%3d%%)", percent); } /* * refresh window content */ static void refresh_text_box(WINDOW *dialog, WINDOW *box, int boxh, int boxw, int cur_y, int cur_x) { start = page - buf; print_page(box, boxh, boxw); print_position(dialog); wmove(dialog, cur_y, cur_x); /* Restore cursor position */ wrefresh(dialog); end = page - buf; } /* * Display text from a file in a dialog box. * * keys is a null-terminated array */ int dialog_textbox(const char *title, const char *tbuf, int initial_height, int initial_width, int *_vscroll, int *_hscroll, int (*extra_key_cb)(int, size_t, size_t, void *), void *data) { int i, x, y, cur_x, cur_y, key = 0; int height, width, boxh, boxw; WINDOW *dialog, *box; bool done = false; begin_reached = 1; end_reached = 0; page_length = 0; hscroll = 0; buf = tbuf; page = buf; /* page is pointer to start of page to be displayed */ if (_vscroll && *_vscroll) { begin_reached = 0; for (i = 0; i < *_vscroll; i++) get_line(); } if (_hscroll) hscroll = *_hscroll; do_resize: getmaxyx(stdscr, height, width); if (height < TEXTBOX_HEIGTH_MIN || width < TEXTBOX_WIDTH_MIN) return -ERRDISPLAYTOOSMALL; if (initial_height != 0) height = initial_height; else if (height > 4) height -= 4; else height = 0; if (initial_width != 0) width = initial_width; else if (width > 5) width -= 5; else width = 0; /* center dialog box on screen */ x = (getmaxx(stdscr) - width) / 2; y = (getmaxy(stdscr) - height) / 2; draw_shadow(stdscr, y, x, height, width); dialog = newwin(height, width, y, x); keypad(dialog, TRUE); /* Create window for box region, used for scrolling text */ boxh = height - 4; boxw = width - 2; box = subwin(dialog, boxh, boxw, y + 1, x + 1); wattrset(box, dlg.dialog.atr); wbkgdset(box, dlg.dialog.atr & A_COLOR); keypad(box, TRUE); /* register the new window, along with its borders */ draw_box(dialog, 0, 0, height, width, dlg.dialog.atr, dlg.border.atr); wattrset(dialog, dlg.border.atr); mvwaddch(dialog, height - 3, 0, ACS_LTEE); for (i = 0; i < width - 2; i++) waddch(dialog, ACS_HLINE); wattrset(dialog, dlg.dialog.atr); wbkgdset(dialog, dlg.dialog.atr & A_COLOR); waddch(dialog, ACS_RTEE); print_title(dialog, title, width); print_button(dialog, " Exit ", height - 2, width / 2 - 4, TRUE); wnoutrefresh(dialog); getyx(dialog, cur_y, cur_x); /* Save cursor position */ /* Print first page of text */ attr_clear(box, boxh, boxw, dlg.dialog.atr); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); while (!done) { key = wgetch(dialog); switch (key) { case 'E': /* Exit */ case 'e': case 'X': case 'x': case 'q': case '\n': done = true; break; case 'g': /* First page */ case KEY_HOME: if (!begin_reached) { begin_reached = 1; page = buf; refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); } break; case 'G': /* Last page */ case KEY_END: end_reached = 1; /* point to last char in buf */ page = buf + strlen(buf); back_lines(boxh); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case 'K': /* Previous line */ case 'k': case KEY_UP: if (begin_reached) break; back_lines(page_length + 1); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case 'B': /* Previous page */ case 'b': case 'u': case KEY_PPAGE: if (begin_reached) break; back_lines(page_length + boxh); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case 'J': /* Next line */ case 'j': case KEY_DOWN: if (end_reached) break; back_lines(page_length - 1); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case KEY_NPAGE: /* Next page */ case ' ': case 'd': if (end_reached) break; begin_reached = 0; refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case '0': /* Beginning of line */ case 'H': /* Scroll left */ case 'h': case KEY_LEFT: if (hscroll <= 0) break; if (key == '0') hscroll = 0; else hscroll--; /* Reprint current page to scroll horizontally */ back_lines(page_length); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case 'L': /* Scroll right */ case 'l': case KEY_RIGHT: if (hscroll >= MAX_LEN) break; hscroll++; /* Reprint current page to scroll horizontally */ back_lines(page_length); refresh_text_box(dialog, box, boxh, boxw, cur_y, cur_x); break; case KEY_ESC: if (on_key_esc(dialog) == KEY_ESC) done = true; break; case KEY_RESIZE: back_lines(height); delwin(box); delwin(dialog); on_key_resize(); goto do_resize; default: if (extra_key_cb && extra_key_cb(key, start, end, data)) { done = true; break; } } } delwin(box); delwin(dialog); if (_vscroll) { const char *s; s = buf; *_vscroll = 0; back_lines(page_length); while (s < page && (s = strchr(s, '\n'))) { (*_vscroll)++; s++; } } if (_hscroll) *_hscroll = hscroll; return key; }
linux-master
scripts/kconfig/lxdialog/textbox.c
// SPDX-License-Identifier: GPL-2.0+ /* * yesno.c -- implements the yes/no box * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ #include "dialog.h" /* * Display termination buttons */ static void print_buttons(WINDOW * dialog, int height, int width, int selected) { int x = width / 2 - 10; int y = height - 2; print_button(dialog, " Yes ", y, x, selected == 0); print_button(dialog, " No ", y, x + 13, selected == 1); wmove(dialog, y, x + 1 + 13 * selected); wrefresh(dialog); } /* * Display a dialog box with two buttons - Yes and No */ int dialog_yesno(const char *title, const char *prompt, int height, int width) { int i, x, y, key = 0, button = 0; WINDOW *dialog; do_resize: if (getmaxy(stdscr) < (height + YESNO_HEIGTH_MIN)) return -ERRDISPLAYTOOSMALL; if (getmaxx(stdscr) < (width + YESNO_WIDTH_MIN)) return -ERRDISPLAYTOOSMALL; /* center dialog box on screen */ x = (getmaxx(stdscr) - width) / 2; y = (getmaxy(stdscr) - height) / 2; draw_shadow(stdscr, y, x, height, width); dialog = newwin(height, width, y, x); keypad(dialog, TRUE); draw_box(dialog, 0, 0, height, width, dlg.dialog.atr, dlg.border.atr); wattrset(dialog, dlg.border.atr); mvwaddch(dialog, height - 3, 0, ACS_LTEE); for (i = 0; i < width - 2; i++) waddch(dialog, ACS_HLINE); wattrset(dialog, dlg.dialog.atr); waddch(dialog, ACS_RTEE); print_title(dialog, title, width); wattrset(dialog, dlg.dialog.atr); print_autowrap(dialog, prompt, width - 2, 1, 3); print_buttons(dialog, height, width, 0); while (key != KEY_ESC) { key = wgetch(dialog); switch (key) { case 'Y': case 'y': delwin(dialog); return 0; case 'N': case 'n': delwin(dialog); return 1; case TAB: case KEY_LEFT: case KEY_RIGHT: button = ((key == KEY_LEFT ? --button : ++button) < 0) ? 1 : (button > 1 ? 0 : button); print_buttons(dialog, height, width, button); wrefresh(dialog); break; case ' ': case '\n': delwin(dialog); return button; case KEY_ESC: key = on_key_esc(dialog); break; case KEY_RESIZE: delwin(dialog); on_key_resize(); goto do_resize; } } delwin(dialog); return key; /* ESC pressed */ }
linux-master
scripts/kconfig/lxdialog/yesno.c
// SPDX-License-Identifier: GPL-2.0+ /* * checklist.c -- implements the checklist box * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * Stuart Herbert - [email protected]: radiolist extension * Alessandro Rubini - [email protected]: merged the two * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ #include "dialog.h" static int list_width, check_x, item_x; /* * Print list item */ static void print_item(WINDOW * win, int choice, int selected) { int i; char *list_item = malloc(list_width + 1); strncpy(list_item, item_str(), list_width - item_x); list_item[list_width - item_x] = '\0'; /* Clear 'residue' of last item */ wattrset(win, dlg.menubox.atr); wmove(win, choice, 0); for (i = 0; i < list_width; i++) waddch(win, ' '); wmove(win, choice, check_x); wattrset(win, selected ? dlg.check_selected.atr : dlg.check.atr); if (!item_is_tag(':')) wprintw(win, "(%c)", item_is_tag('X') ? 'X' : ' '); wattrset(win, selected ? dlg.tag_selected.atr : dlg.tag.atr); mvwaddch(win, choice, item_x, list_item[0]); wattrset(win, selected ? dlg.item_selected.atr : dlg.item.atr); waddstr(win, list_item + 1); if (selected) { wmove(win, choice, check_x + 1); wrefresh(win); } free(list_item); } /* * Print the scroll indicators. */ static void print_arrows(WINDOW * win, int choice, int item_no, int scroll, int y, int x, int height) { wmove(win, y, x); if (scroll > 0) { wattrset(win, dlg.uarrow.atr); waddch(win, ACS_UARROW); waddstr(win, "(-)"); } else { wattrset(win, dlg.menubox.atr); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); } y = y + height + 1; wmove(win, y, x); if ((height < item_no) && (scroll + choice < item_no - 1)) { wattrset(win, dlg.darrow.atr); waddch(win, ACS_DARROW); waddstr(win, "(+)"); } else { wattrset(win, dlg.menubox_border.atr); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); } } /* * Display the termination buttons */ static void print_buttons(WINDOW * dialog, int height, int width, int selected) { int x = width / 2 - 11; int y = height - 2; print_button(dialog, "Select", y, x, selected == 0); print_button(dialog, " Help ", y, x + 14, selected == 1); wmove(dialog, y, x + 1 + 14 * selected); wrefresh(dialog); } /* * Display a dialog box with a list of options that can be turned on or off * in the style of radiolist (only one option turned on at a time). */ int dialog_checklist(const char *title, const char *prompt, int height, int width, int list_height) { int i, x, y, box_x, box_y; int key = 0, button = 0, choice = 0, scroll = 0, max_choice; WINDOW *dialog, *list; /* which item to highlight */ item_foreach() { if (item_is_tag('X')) choice = item_n(); if (item_is_selected()) { choice = item_n(); break; } } do_resize: if (getmaxy(stdscr) < (height + CHECKLIST_HEIGTH_MIN)) return -ERRDISPLAYTOOSMALL; if (getmaxx(stdscr) < (width + CHECKLIST_WIDTH_MIN)) return -ERRDISPLAYTOOSMALL; max_choice = MIN(list_height, item_count()); /* center dialog box on screen */ x = (getmaxx(stdscr) - width) / 2; y = (getmaxy(stdscr) - height) / 2; draw_shadow(stdscr, y, x, height, width); dialog = newwin(height, width, y, x); keypad(dialog, TRUE); draw_box(dialog, 0, 0, height, width, dlg.dialog.atr, dlg.border.atr); wattrset(dialog, dlg.border.atr); mvwaddch(dialog, height - 3, 0, ACS_LTEE); for (i = 0; i < width - 2; i++) waddch(dialog, ACS_HLINE); wattrset(dialog, dlg.dialog.atr); waddch(dialog, ACS_RTEE); print_title(dialog, title, width); wattrset(dialog, dlg.dialog.atr); print_autowrap(dialog, prompt, width - 2, 1, 3); list_width = width - 6; box_y = height - list_height - 5; box_x = (width - list_width) / 2 - 1; /* create new window for the list */ list = subwin(dialog, list_height, list_width, y + box_y + 1, x + box_x + 1); keypad(list, TRUE); /* draw a box around the list items */ draw_box(dialog, box_y, box_x, list_height + 2, list_width + 2, dlg.menubox_border.atr, dlg.menubox.atr); /* Find length of longest item in order to center checklist */ check_x = 0; item_foreach() check_x = MAX(check_x, strlen(item_str()) + 4); check_x = MIN(check_x, list_width); check_x = (list_width - check_x) / 2; item_x = check_x + 4; if (choice >= list_height) { scroll = choice - list_height + 1; choice -= scroll; } /* Print the list */ for (i = 0; i < max_choice; i++) { item_set(scroll + i); print_item(list, i, i == choice); } print_arrows(dialog, choice, item_count(), scroll, box_y, box_x + check_x + 5, list_height); print_buttons(dialog, height, width, 0); wnoutrefresh(dialog); wnoutrefresh(list); doupdate(); while (key != KEY_ESC) { key = wgetch(dialog); for (i = 0; i < max_choice; i++) { item_set(i + scroll); if (toupper(key) == toupper(item_str()[0])) break; } if (i < max_choice || key == KEY_UP || key == KEY_DOWN || key == '+' || key == '-') { if (key == KEY_UP || key == '-') { if (!choice) { if (!scroll) continue; /* Scroll list down */ if (list_height > 1) { /* De-highlight current first item */ item_set(scroll); print_item(list, 0, FALSE); scrollok(list, TRUE); wscrl(list, -1); scrollok(list, FALSE); } scroll--; item_set(scroll); print_item(list, 0, TRUE); print_arrows(dialog, choice, item_count(), scroll, box_y, box_x + check_x + 5, list_height); wnoutrefresh(dialog); wrefresh(list); continue; /* wait for another key press */ } else i = choice - 1; } else if (key == KEY_DOWN || key == '+') { if (choice == max_choice - 1) { if (scroll + choice >= item_count() - 1) continue; /* Scroll list up */ if (list_height > 1) { /* De-highlight current last item before scrolling up */ item_set(scroll + max_choice - 1); print_item(list, max_choice - 1, FALSE); scrollok(list, TRUE); wscrl(list, 1); scrollok(list, FALSE); } scroll++; item_set(scroll + max_choice - 1); print_item(list, max_choice - 1, TRUE); print_arrows(dialog, choice, item_count(), scroll, box_y, box_x + check_x + 5, list_height); wnoutrefresh(dialog); wrefresh(list); continue; /* wait for another key press */ } else i = choice + 1; } if (i != choice) { /* De-highlight current item */ item_set(scroll + choice); print_item(list, choice, FALSE); /* Highlight new item */ choice = i; item_set(scroll + choice); print_item(list, choice, TRUE); wnoutrefresh(dialog); wrefresh(list); } continue; /* wait for another key press */ } switch (key) { case 'H': case 'h': case '?': button = 1; /* fall-through */ case 'S': case 's': case ' ': case '\n': item_foreach() item_set_selected(0); item_set(scroll + choice); item_set_selected(1); delwin(list); delwin(dialog); return button; case TAB: case KEY_LEFT: case KEY_RIGHT: button = ((key == KEY_LEFT ? --button : ++button) < 0) ? 1 : (button > 1 ? 0 : button); print_buttons(dialog, height, width, button); wrefresh(dialog); break; case 'X': case 'x': key = KEY_ESC; break; case KEY_ESC: key = on_key_esc(dialog); break; case KEY_RESIZE: delwin(list); delwin(dialog); on_key_resize(); goto do_resize; } /* Now, update everything... */ doupdate(); } delwin(list); delwin(dialog); return key; /* ESC pressed */ }
linux-master
scripts/kconfig/lxdialog/checklist.c
// SPDX-License-Identifier: GPL-2.0+ /* * menubox.c -- implements the menu box * * ORIGINAL AUTHOR: Savio Lam ([email protected]) * MODIFIED FOR LINUX KERNEL CONFIG BY: William Roadcap ([email protected]) */ /* * Changes by Clifford Wolf ([email protected]) * * [ 1998-06-13 ] * * *) A bugfix for the Page-Down problem * * *) Formerly when I used Page Down and Page Up, the cursor would be set * to the first position in the menu box. Now lxdialog is a bit * smarter and works more like other menu systems (just have a look at * it). * * *) Formerly if I selected something my scrolling would be broken because * lxdialog is re-invoked by the Menuconfig shell script, can't * remember the last scrolling position, and just sets it so that the * cursor is at the bottom of the box. Now it writes the temporary file * lxdialog.scrltmp which contains this information. The file is * deleted by lxdialog if the user leaves a submenu or enters a new * one, but it would be nice if Menuconfig could make another "rm -f" * just to be sure. Just try it out - you will recognise a difference! * * [ 1998-06-14 ] * * *) Now lxdialog is crash-safe against broken "lxdialog.scrltmp" files * and menus change their size on the fly. * * *) If for some reason the last scrolling position is not saved by * lxdialog, it sets the scrolling so that the selected item is in the * middle of the menu box, not at the bottom. * * 02 January 1999, Michael Elizabeth Chastain ([email protected]) * Reset 'scroll' to 0 if the value from lxdialog.scrltmp is bogus. * This fixes a bug in Menuconfig where using ' ' to descend into menus * would leave mis-synchronized lxdialog.scrltmp files lying around, * fscanf would read in 'scroll', and eventually that value would get used. */ #include "dialog.h" static int menu_width, item_x; /* * Print menu item */ static void do_print_item(WINDOW * win, const char *item, int line_y, int selected, int hotkey) { int j; char *menu_item = malloc(menu_width + 1); strncpy(menu_item, item, menu_width - item_x); menu_item[menu_width - item_x] = '\0'; j = first_alpha(menu_item, "YyNnMmHh"); /* Clear 'residue' of last item */ wattrset(win, dlg.menubox.atr); wmove(win, line_y, 0); wclrtoeol(win); wattrset(win, selected ? dlg.item_selected.atr : dlg.item.atr); mvwaddstr(win, line_y, item_x, menu_item); if (hotkey) { wattrset(win, selected ? dlg.tag_key_selected.atr : dlg.tag_key.atr); mvwaddch(win, line_y, item_x + j, menu_item[j]); } if (selected) { wmove(win, line_y, item_x + 1); } free(menu_item); wrefresh(win); } #define print_item(index, choice, selected) \ do { \ item_set(index); \ do_print_item(menu, item_str(), choice, selected, !item_is_tag(':')); \ } while (0) /* * Print the scroll indicators. */ static void print_arrows(WINDOW * win, int item_no, int scroll, int y, int x, int height) { int cur_y, cur_x; getyx(win, cur_y, cur_x); wmove(win, y, x); if (scroll > 0) { wattrset(win, dlg.uarrow.atr); waddch(win, ACS_UARROW); waddstr(win, "(-)"); } else { wattrset(win, dlg.menubox.atr); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); } y = y + height + 1; wmove(win, y, x); wrefresh(win); if ((height < item_no) && (scroll + height < item_no)) { wattrset(win, dlg.darrow.atr); waddch(win, ACS_DARROW); waddstr(win, "(+)"); } else { wattrset(win, dlg.menubox_border.atr); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); waddch(win, ACS_HLINE); } wmove(win, cur_y, cur_x); wrefresh(win); } /* * Display the termination buttons. */ static void print_buttons(WINDOW * win, int height, int width, int selected) { int x = width / 2 - 28; int y = height - 2; print_button(win, "Select", y, x, selected == 0); print_button(win, " Exit ", y, x + 12, selected == 1); print_button(win, " Help ", y, x + 24, selected == 2); print_button(win, " Save ", y, x + 36, selected == 3); print_button(win, " Load ", y, x + 48, selected == 4); wmove(win, y, x + 1 + 12 * selected); wrefresh(win); } /* scroll up n lines (n may be negative) */ static void do_scroll(WINDOW *win, int *scroll, int n) { /* Scroll menu up */ scrollok(win, TRUE); wscrl(win, n); scrollok(win, FALSE); *scroll = *scroll + n; wrefresh(win); } /* * Display a menu for choosing among a number of options */ int dialog_menu(const char *title, const char *prompt, const void *selected, int *s_scroll) { int i, j, x, y, box_x, box_y; int height, width, menu_height; int key = 0, button = 0, scroll = 0, choice = 0; int first_item = 0, max_choice; WINDOW *dialog, *menu; do_resize: height = getmaxy(stdscr); width = getmaxx(stdscr); if (height < MENUBOX_HEIGTH_MIN || width < MENUBOX_WIDTH_MIN) return -ERRDISPLAYTOOSMALL; height -= 4; width -= 5; menu_height = height - 10; max_choice = MIN(menu_height, item_count()); /* center dialog box on screen */ x = (getmaxx(stdscr) - width) / 2; y = (getmaxy(stdscr) - height) / 2; draw_shadow(stdscr, y, x, height, width); dialog = newwin(height, width, y, x); keypad(dialog, TRUE); draw_box(dialog, 0, 0, height, width, dlg.dialog.atr, dlg.border.atr); wattrset(dialog, dlg.border.atr); mvwaddch(dialog, height - 3, 0, ACS_LTEE); for (i = 0; i < width - 2; i++) waddch(dialog, ACS_HLINE); wattrset(dialog, dlg.dialog.atr); wbkgdset(dialog, dlg.dialog.atr & A_COLOR); waddch(dialog, ACS_RTEE); print_title(dialog, title, width); wattrset(dialog, dlg.dialog.atr); print_autowrap(dialog, prompt, width - 2, 1, 3); menu_width = width - 6; box_y = height - menu_height - 5; box_x = (width - menu_width) / 2 - 1; /* create new window for the menu */ menu = subwin(dialog, menu_height, menu_width, y + box_y + 1, x + box_x + 1); keypad(menu, TRUE); /* draw a box around the menu items */ draw_box(dialog, box_y, box_x, menu_height + 2, menu_width + 2, dlg.menubox_border.atr, dlg.menubox.atr); if (menu_width >= 80) item_x = (menu_width - 70) / 2; else item_x = 4; /* Set choice to default item */ item_foreach() if (selected && (selected == item_data())) choice = item_n(); /* get the saved scroll info */ scroll = *s_scroll; if ((scroll <= choice) && (scroll + max_choice > choice) && (scroll >= 0) && (scroll + max_choice <= item_count())) { first_item = scroll; choice = choice - scroll; } else { scroll = 0; } if ((choice >= max_choice)) { if (choice >= item_count() - max_choice / 2) scroll = first_item = item_count() - max_choice; else scroll = first_item = choice - max_choice / 2; choice = choice - scroll; } /* Print the menu */ for (i = 0; i < max_choice; i++) { print_item(first_item + i, i, i == choice); } wnoutrefresh(menu); print_arrows(dialog, item_count(), scroll, box_y, box_x + item_x + 1, menu_height); print_buttons(dialog, height, width, 0); wmove(menu, choice, item_x + 1); wrefresh(menu); while (key != KEY_ESC) { key = wgetch(menu); if (key < 256 && isalpha(key)) key = tolower(key); if (strchr("ynmh", key)) i = max_choice; else { for (i = choice + 1; i < max_choice; i++) { item_set(scroll + i); j = first_alpha(item_str(), "YyNnMmHh"); if (key == tolower(item_str()[j])) break; } if (i == max_choice) for (i = 0; i < max_choice; i++) { item_set(scroll + i); j = first_alpha(item_str(), "YyNnMmHh"); if (key == tolower(item_str()[j])) break; } } if (item_count() != 0 && (i < max_choice || key == KEY_UP || key == KEY_DOWN || key == '-' || key == '+' || key == KEY_PPAGE || key == KEY_NPAGE)) { /* Remove highligt of current item */ print_item(scroll + choice, choice, FALSE); if (key == KEY_UP || key == '-') { if (choice < 2 && scroll) { /* Scroll menu down */ do_scroll(menu, &scroll, -1); print_item(scroll, 0, FALSE); } else choice = MAX(choice - 1, 0); } else if (key == KEY_DOWN || key == '+') { print_item(scroll+choice, choice, FALSE); if ((choice > max_choice - 3) && (scroll + max_choice < item_count())) { /* Scroll menu up */ do_scroll(menu, &scroll, 1); print_item(scroll+max_choice - 1, max_choice - 1, FALSE); } else choice = MIN(choice + 1, max_choice - 1); } else if (key == KEY_PPAGE) { scrollok(menu, TRUE); for (i = 0; (i < max_choice); i++) { if (scroll > 0) { do_scroll(menu, &scroll, -1); print_item(scroll, 0, FALSE); } else { if (choice > 0) choice--; } } } else if (key == KEY_NPAGE) { for (i = 0; (i < max_choice); i++) { if (scroll + max_choice < item_count()) { do_scroll(menu, &scroll, 1); print_item(scroll+max_choice-1, max_choice - 1, FALSE); } else { if (choice + 1 < max_choice) choice++; } } } else choice = i; print_item(scroll + choice, choice, TRUE); print_arrows(dialog, item_count(), scroll, box_y, box_x + item_x + 1, menu_height); wnoutrefresh(dialog); wrefresh(menu); continue; /* wait for another key press */ } switch (key) { case KEY_LEFT: case TAB: case KEY_RIGHT: button = ((key == KEY_LEFT ? --button : ++button) < 0) ? 4 : (button > 4 ? 0 : button); print_buttons(dialog, height, width, button); wrefresh(menu); break; case ' ': case 's': case 'y': case 'n': case 'm': case '/': case 'h': case '?': case 'z': case '\n': /* save scroll info */ *s_scroll = scroll; delwin(menu); delwin(dialog); item_set(scroll + choice); item_set_selected(1); switch (key) { case 'h': case '?': return 2; case 's': case 'y': return 5; case 'n': return 6; case 'm': return 7; case ' ': return 8; case '/': return 9; case 'z': return 10; case '\n': return button; } return 0; case 'e': case 'x': key = KEY_ESC; break; case KEY_ESC: key = on_key_esc(menu); break; case KEY_RESIZE: on_key_resize(); delwin(menu); delwin(dialog); goto do_resize; } } delwin(menu); delwin(dialog); return key; /* ESC pressed */ }
linux-master
scripts/kconfig/lxdialog/menubox.c
/* * "Optimize" a list of dependencies as spit out by gcc -MD * for the kernel build * =========================================================================== * * Author Kai Germaschewski * Copyright 2002 by Kai Germaschewski <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * * Introduction: * * gcc produces a very nice and correct list of dependencies which * tells make when to remake a file. * * To use this list as-is however has the drawback that virtually * every file in the kernel includes autoconf.h. * * If the user re-runs make *config, autoconf.h will be * regenerated. make notices that and will rebuild every file which * includes autoconf.h, i.e. basically all files. This is extremely * annoying if the user just changed CONFIG_HIS_DRIVER from n to m. * * So we play the same trick that "mkdep" played before. We replace * the dependency on autoconf.h by a dependency on every config * option which is mentioned in any of the listed prerequisites. * * kconfig populates a tree in include/config/ with an empty file * for each config symbol and when the configuration is updated * the files representing changed config options are touched * which then let make pick up the changes and the files that use * the config symbols are rebuilt. * * So if the user changes his CONFIG_HIS_DRIVER option, only the objects * which depend on "include/config/HIS_DRIVER" will be rebuilt, * so most likely only his driver ;-) * * The idea above dates, by the way, back to Michael E Chastain, AFAIK. * * So to get dependencies right, there are two issues: * o if any of the files the compiler read changed, we need to rebuild * o if the command line given to the compile the file changed, we * better rebuild as well. * * The former is handled by using the -MD output, the later by saving * the command line used to compile the old object and comparing it * to the one we would now use. * * Again, also this idea is pretty old and has been discussed on * kbuild-devel a long time ago. I don't have a sensibly working * internet connection right now, so I rather don't mention names * without double checking. * * This code here has been based partially based on mkdep.c, which * says the following about its history: * * Copyright abandoned, Michael Chastain, <mailto:[email protected]>. * This is a C version of syncdep.pl by Werner Almesberger. * * * It is invoked as * * fixdep <depfile> <target> <cmdline> * * and will read the dependency file <depfile> * * The transformed dependency snipped is written to stdout. * * It first generates a line * * savedcmd_<target> = <cmdline> * * and then basically copies the .<target>.d file to stdout, in the * process filtering out the dependency on autoconf.h and adding * dependencies on include/config/MY_OPTION for every * CONFIG_MY_OPTION encountered in any of the prerequisites. * * We don't even try to really parse the header files, but * merely grep, i.e. if CONFIG_FOO is mentioned in a comment, it will * be picked up as well. It's not a problem with respect to * correctness, since that can only give too many dependencies, thus * we cannot miss a rebuild. Since people tend to not mention totally * unrelated CONFIG_ options all over the place, it's not an * efficiency problem either. * * (Note: it'd be easy to port over the complete mkdep state machine, * but I don't think the added complexity is worth it) */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> static void usage(void) { fprintf(stderr, "Usage: fixdep <depfile> <target> <cmdline>\n"); exit(1); } struct item { struct item *next; unsigned int len; unsigned int hash; char name[]; }; #define HASHSZ 256 static struct item *config_hashtab[HASHSZ], *file_hashtab[HASHSZ]; static unsigned int strhash(const char *str, unsigned int sz) { /* fnv32 hash */ unsigned int i, hash = 2166136261U; for (i = 0; i < sz; i++) hash = (hash ^ str[i]) * 0x01000193; return hash; } /* * Add a new value to the configuration string. */ static void add_to_hashtable(const char *name, int len, unsigned int hash, struct item *hashtab[]) { struct item *aux = malloc(sizeof(*aux) + len); if (!aux) { perror("fixdep:malloc"); exit(1); } memcpy(aux->name, name, len); aux->len = len; aux->hash = hash; aux->next = hashtab[hash % HASHSZ]; hashtab[hash % HASHSZ] = aux; } /* * Lookup a string in the hash table. If found, just return true. * If not, add it to the hashtable and return false. */ static bool in_hashtable(const char *name, int len, struct item *hashtab[]) { struct item *aux; unsigned int hash = strhash(name, len); for (aux = hashtab[hash % HASHSZ]; aux; aux = aux->next) { if (aux->hash == hash && aux->len == len && memcmp(aux->name, name, len) == 0) return true; } add_to_hashtable(name, len, hash, hashtab); return false; } /* * Record the use of a CONFIG_* word. */ static void use_config(const char *m, int slen) { if (in_hashtable(m, slen, config_hashtab)) return; /* Print out a dependency path from a symbol name. */ printf(" $(wildcard include/config/%.*s) \\\n", slen, m); } /* test if s ends in sub */ static int str_ends_with(const char *s, int slen, const char *sub) { int sublen = strlen(sub); if (sublen > slen) return 0; return !memcmp(s + slen - sublen, sub, sublen); } static void parse_config_file(const char *p) { const char *q, *r; const char *start = p; while ((p = strstr(p, "CONFIG_"))) { if (p > start && (isalnum(p[-1]) || p[-1] == '_')) { p += 7; continue; } p += 7; q = p; while (isalnum(*q) || *q == '_') q++; if (str_ends_with(p, q - p, "_MODULE")) r = q - 7; else r = q; if (r > p) use_config(p, r - p); p = q; } } static void *read_file(const char *filename) { struct stat st; int fd; char *buf; fd = open(filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "fixdep: error opening file: "); perror(filename); exit(2); } if (fstat(fd, &st) < 0) { fprintf(stderr, "fixdep: error fstat'ing file: "); perror(filename); exit(2); } buf = malloc(st.st_size + 1); if (!buf) { perror("fixdep: malloc"); exit(2); } if (read(fd, buf, st.st_size) != st.st_size) { perror("fixdep: read"); exit(2); } buf[st.st_size] = '\0'; close(fd); return buf; } /* Ignore certain dependencies */ static int is_ignored_file(const char *s, int len) { return str_ends_with(s, len, "include/generated/autoconf.h"); } /* Do not parse these files */ static int is_no_parse_file(const char *s, int len) { /* rustc may list binary files in dep-info */ return str_ends_with(s, len, ".rlib") || str_ends_with(s, len, ".rmeta") || str_ends_with(s, len, ".so"); } /* * Important: The below generated source_foo.o and deps_foo.o variable * assignments are parsed not only by make, but also by the rather simple * parser in scripts/mod/sumversion.c. */ static void parse_dep_file(char *p, const char *target) { bool saw_any_target = false; bool is_target = true; bool is_source = false; bool need_parse; char *q, saved_c; while (*p) { /* handle some special characters first. */ switch (*p) { case '#': /* * skip comments. * rustc may emit comments to dep-info. */ p++; while (*p != '\0' && *p != '\n') { /* * escaped newlines continue the comment across * multiple lines. */ if (*p == '\\') p++; p++; } continue; case ' ': case '\t': /* skip whitespaces */ p++; continue; case '\\': /* * backslash/newline combinations continue the * statement. Skip it just like a whitespace. */ if (*(p + 1) == '\n') { p += 2; continue; } break; case '\n': /* * Makefiles use a line-based syntax, where the newline * is the end of a statement. After seeing a newline, * we expect the next token is a target. */ p++; is_target = true; continue; case ':': /* * assume the first dependency after a colon as the * source file. */ p++; is_target = false; is_source = true; continue; } /* find the end of the token */ q = p; while (*q != ' ' && *q != '\t' && *q != '\n' && *q != '#' && *q != ':') { if (*q == '\\') { /* * backslash/newline combinations work like as * a whitespace, so this is the end of token. */ if (*(q + 1) == '\n') break; /* escaped special characters */ if (*(q + 1) == '#' || *(q + 1) == ':') { memmove(p + 1, p, q - p); p++; } q++; } if (*q == '\0') break; q++; } /* Just discard the target */ if (is_target) { p = q; continue; } saved_c = *q; *q = '\0'; need_parse = false; /* * Do not list the source file as dependency, so that kbuild is * not confused if a .c file is rewritten into .S or vice versa. * Storing it in source_* is needed for modpost to compute * srcversions. */ if (is_source) { /* * The DT build rule concatenates multiple dep files. * When processing them, only process the first source * name, which will be the original one, and ignore any * other source names, which will be intermediate * temporary files. * * rustc emits the same dependency list for each * emission type. It is enough to list the source name * just once. */ if (!saw_any_target) { saw_any_target = true; printf("source_%s := %s\n\n", target, p); printf("deps_%s := \\\n", target); need_parse = true; } } else if (!is_ignored_file(p, q - p) && !in_hashtable(p, q - p, file_hashtab)) { printf(" %s \\\n", p); need_parse = true; } if (need_parse && !is_no_parse_file(p, q - p)) { void *buf; buf = read_file(p); parse_config_file(buf); free(buf); } is_source = false; *q = saved_c; p = q; } if (!saw_any_target) { fprintf(stderr, "fixdep: parse error; no targets found\n"); exit(1); } printf("\n%s: $(deps_%s)\n\n", target, target); printf("$(deps_%s):\n", target); } int main(int argc, char *argv[]) { const char *depfile, *target, *cmdline; void *buf; if (argc != 4) usage(); depfile = argv[1]; target = argv[2]; cmdline = argv[3]; printf("savedcmd_%s := %s\n\n", target, cmdline); buf = read_file(depfile); parse_dep_file(buf, target); free(buf); fflush(stdout); /* * In the intended usage, the stdout is redirected to .*.cmd files. * Call ferror() to catch errors such as "No space left on device". */ if (ferror(stdout)) { fprintf(stderr, "fixdep: not all data was written to the output\n"); exit(1); } return 0; }
linux-master
scripts/basic/fixdep.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright Linaro, Ltd. 2018 * (C) Copyright Arm Holdings. 2017 * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include <stdlib.h> #include <yaml.h> #include "dtc.h" #include "srcpos.h" char *yaml_error_name[] = { [YAML_NO_ERROR] = "no error", [YAML_MEMORY_ERROR] = "memory error", [YAML_READER_ERROR] = "reader error", [YAML_SCANNER_ERROR] = "scanner error", [YAML_PARSER_ERROR] = "parser error", [YAML_COMPOSER_ERROR] = "composer error", [YAML_WRITER_ERROR] = "writer error", [YAML_EMITTER_ERROR] = "emitter error", }; #define yaml_emitter_emit_or_die(emitter, event) ( \ { \ if (!yaml_emitter_emit(emitter, event)) \ die("yaml '%s': %s in %s, line %i\n", \ yaml_error_name[(emitter)->error], \ (emitter)->problem, __func__, __LINE__); \ }) static void yaml_propval_int(yaml_emitter_t *emitter, struct marker *markers, char *data, unsigned int seq_offset, unsigned int len, int width) { yaml_event_t event; void *tag; unsigned int off; switch(width) { case 1: tag = "!u8"; break; case 2: tag = "!u16"; break; case 4: tag = "!u32"; break; case 8: tag = "!u64"; break; default: die("Invalid width %i", width); } assert(len % width == 0); yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)tag, width == 4, YAML_FLOW_SEQUENCE_STYLE); yaml_emitter_emit_or_die(emitter, &event); for (off = 0; off < len; off += width) { char buf[32]; struct marker *m; bool is_phandle = false; switch(width) { case 1: sprintf(buf, "0x%"PRIx8, *(uint8_t*)(data + off)); break; case 2: sprintf(buf, "0x%"PRIx16, dtb_ld16(data + off)); break; case 4: sprintf(buf, "0x%"PRIx32, dtb_ld32(data + off)); m = markers; is_phandle = false; for_each_marker_of_type(m, REF_PHANDLE) { if (m->offset == (seq_offset + off)) { is_phandle = true; break; } } break; case 8: sprintf(buf, "0x%"PRIx64, dtb_ld64(data + off)); break; } if (is_phandle) yaml_scalar_event_initialize(&event, NULL, (yaml_char_t*)"!phandle", (yaml_char_t *)buf, strlen(buf), 0, 0, YAML_PLAIN_SCALAR_STYLE); else yaml_scalar_event_initialize(&event, NULL, (yaml_char_t*)YAML_INT_TAG, (yaml_char_t *)buf, strlen(buf), 1, 1, YAML_PLAIN_SCALAR_STYLE); yaml_emitter_emit_or_die(emitter, &event); } yaml_sequence_end_event_initialize(&event); yaml_emitter_emit_or_die(emitter, &event); } static void yaml_propval_string(yaml_emitter_t *emitter, char *str, int len) { yaml_event_t event; int i; assert(str[len-1] == '\0'); /* Make sure the entire string is in the lower 7-bit ascii range */ for (i = 0; i < len; i++) assert(isascii(str[i])); yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)str, len-1, 0, 1, YAML_DOUBLE_QUOTED_SCALAR_STYLE); yaml_emitter_emit_or_die(emitter, &event); } static void yaml_propval(yaml_emitter_t *emitter, struct property *prop) { yaml_event_t event; unsigned int len = prop->val.len; struct marker *m = prop->val.markers; struct marker *markers = prop->val.markers; /* Emit the property name */ yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)prop->name, strlen(prop->name), 1, 1, YAML_PLAIN_SCALAR_STYLE); yaml_emitter_emit_or_die(emitter, &event); /* Boolean properties are easiest to deal with. Length is zero, so just emit 'true' */ if (len == 0) { yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_BOOL_TAG, (yaml_char_t*)"true", strlen("true"), 1, 0, YAML_PLAIN_SCALAR_STYLE); yaml_emitter_emit_or_die(emitter, &event); return; } if (!m) die("No markers present in property '%s' value\n", prop->name); yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_FLOW_SEQUENCE_STYLE); yaml_emitter_emit_or_die(emitter, &event); for_each_marker(m) { int chunk_len; char *data = &prop->val.val[m->offset]; if (m->type < TYPE_UINT8) continue; chunk_len = type_marker_length(m) ? : len; assert(chunk_len > 0); len -= chunk_len; switch(m->type) { case TYPE_UINT16: yaml_propval_int(emitter, markers, data, m->offset, chunk_len, 2); break; case TYPE_UINT32: yaml_propval_int(emitter, markers, data, m->offset, chunk_len, 4); break; case TYPE_UINT64: yaml_propval_int(emitter, markers, data, m->offset, chunk_len, 8); break; case TYPE_STRING: yaml_propval_string(emitter, data, chunk_len); break; default: yaml_propval_int(emitter, markers, data, m->offset, chunk_len, 1); break; } } yaml_sequence_end_event_initialize(&event); yaml_emitter_emit_or_die(emitter, &event); } static void yaml_tree(struct node *tree, yaml_emitter_t *emitter) { struct property *prop; struct node *child; yaml_event_t event; if (tree->deleted) return; yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1, YAML_ANY_MAPPING_STYLE); yaml_emitter_emit_or_die(emitter, &event); for_each_property(tree, prop) yaml_propval(emitter, prop); /* Loop over all the children, emitting them into the map */ for_each_child(tree, child) { yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t*)child->name, strlen(child->name), 1, 0, YAML_PLAIN_SCALAR_STYLE); yaml_emitter_emit_or_die(emitter, &event); yaml_tree(child, emitter); } yaml_mapping_end_event_initialize(&event); yaml_emitter_emit_or_die(emitter, &event); } void dt_to_yaml(FILE *f, struct dt_info *dti) { yaml_emitter_t emitter; yaml_event_t event; yaml_emitter_initialize(&emitter); yaml_emitter_set_output_file(&emitter, f); yaml_stream_start_event_initialize(&event, YAML_UTF8_ENCODING); yaml_emitter_emit_or_die(&emitter, &event); yaml_document_start_event_initialize(&event, NULL, NULL, NULL, 0); yaml_emitter_emit_or_die(&emitter, &event); yaml_sequence_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_SEQ_TAG, 1, YAML_ANY_SEQUENCE_STYLE); yaml_emitter_emit_or_die(&emitter, &event); yaml_tree(dti->dt, &emitter); yaml_sequence_end_event_initialize(&event); yaml_emitter_emit_or_die(&emitter, &event); yaml_document_end_event_initialize(&event, 0); yaml_emitter_emit_or_die(&emitter, &event); yaml_stream_end_event_initialize(&event); yaml_emitter_emit_or_die(&emitter, &event); yaml_emitter_delete(&emitter); }
linux-master
scripts/dtc/yamltree.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright 2011 The Chromium Authors, All Rights Reserved. * Copyright 2008 Jon Loeliger, Freescale Semiconductor, Inc. * * util_is_printable_string contributed by * Pantelis Antoniou <pantelis.antoniou AT gmail.com> */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <assert.h> #include <inttypes.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include "libfdt.h" #include "util.h" #include "version_gen.h" char *xstrdup(const char *s) { int len = strlen(s) + 1; char *d = xmalloc(len); memcpy(d, s, len); return d; } char *xstrndup(const char *s, size_t n) { size_t len = strnlen(s, n) + 1; char *d = xmalloc(len); memcpy(d, s, len - 1); d[len - 1] = '\0'; return d; } int xavsprintf_append(char **strp, const char *fmt, va_list ap) { int n, size = 0; /* start with 128 bytes */ char *p; va_list ap_copy; p = *strp; if (p) size = strlen(p); va_copy(ap_copy, ap); n = vsnprintf(NULL, 0, fmt, ap_copy) + 1; va_end(ap_copy); p = xrealloc(p, size + n); n = vsnprintf(p + size, n, fmt, ap); *strp = p; return strlen(p); } int xasprintf_append(char **strp, const char *fmt, ...) { int n; va_list ap; va_start(ap, fmt); n = xavsprintf_append(strp, fmt, ap); va_end(ap); return n; } int xasprintf(char **strp, const char *fmt, ...) { int n; va_list ap; *strp = NULL; va_start(ap, fmt); n = xavsprintf_append(strp, fmt, ap); va_end(ap); return n; } char *join_path(const char *path, const char *name) { int lenp = strlen(path); int lenn = strlen(name); int len; int needslash = 1; char *str; len = lenp + lenn + 2; if ((lenp > 0) && (path[lenp-1] == '/')) { needslash = 0; len--; } str = xmalloc(len); memcpy(str, path, lenp); if (needslash) { str[lenp] = '/'; lenp++; } memcpy(str+lenp, name, lenn+1); return str; } bool util_is_printable_string(const void *data, int len) { const char *s = data; const char *ss, *se; /* zero length is not */ if (len == 0) return 0; /* must terminate with zero */ if (s[len - 1] != '\0') return 0; se = s + len; while (s < se) { ss = s; while (s < se && *s && isprint((unsigned char)*s)) s++; /* not zero, or not done yet */ if (*s != '\0' || s == ss) return 0; s++; } return 1; } /* * Parse a octal encoded character starting at index i in string s. The * resulting character will be returned and the index i will be updated to * point at the character directly after the end of the encoding, this may be * the '\0' terminator of the string. */ static char get_oct_char(const char *s, int *i) { char x[4]; char *endx; long val; x[3] = '\0'; strncpy(x, s + *i, 3); val = strtol(x, &endx, 8); assert(endx > x); (*i) += endx - x; return val; } /* * Parse a hexadecimal encoded character starting at index i in string s. The * resulting character will be returned and the index i will be updated to * point at the character directly after the end of the encoding, this may be * the '\0' terminator of the string. */ static char get_hex_char(const char *s, int *i) { char x[3]; char *endx; long val; x[2] = '\0'; strncpy(x, s + *i, 2); val = strtol(x, &endx, 16); if (!(endx > x)) die("\\x used with no following hex digits\n"); (*i) += endx - x; return val; } char get_escape_char(const char *s, int *i) { char c = s[*i]; int j = *i + 1; char val; switch (c) { case 'a': val = '\a'; break; case 'b': val = '\b'; break; case 't': val = '\t'; break; case 'n': val = '\n'; break; case 'v': val = '\v'; break; case 'f': val = '\f'; break; case 'r': val = '\r'; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': j--; /* need to re-read the first digit as * part of the octal value */ val = get_oct_char(s, &j); break; case 'x': val = get_hex_char(s, &j); break; default: val = c; } (*i) = j; return val; } int utilfdt_read_err(const char *filename, char **buffp, size_t *len) { int fd = 0; /* assume stdin */ char *buf = NULL; size_t bufsize = 1024, offset = 0; int ret = 0; *buffp = NULL; if (strcmp(filename, "-") != 0) { fd = open(filename, O_RDONLY); if (fd < 0) return errno; } /* Loop until we have read everything */ buf = xmalloc(bufsize); do { /* Expand the buffer to hold the next chunk */ if (offset == bufsize) { bufsize *= 2; buf = xrealloc(buf, bufsize); } ret = read(fd, &buf[offset], bufsize - offset); if (ret < 0) { ret = errno; break; } offset += ret; } while (ret != 0); /* Clean up, including closing stdin; return errno on error */ close(fd); if (ret) free(buf); else *buffp = buf; if (len) *len = bufsize; return ret; } char *utilfdt_read(const char *filename, size_t *len) { char *buff; int ret = utilfdt_read_err(filename, &buff, len); if (ret) { fprintf(stderr, "Couldn't open blob from '%s': %s\n", filename, strerror(ret)); return NULL; } /* Successful read */ return buff; } int utilfdt_write_err(const char *filename, const void *blob) { int fd = 1; /* assume stdout */ int totalsize; int offset; int ret = 0; const char *ptr = blob; if (strcmp(filename, "-") != 0) { fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) return errno; } totalsize = fdt_totalsize(blob); offset = 0; while (offset < totalsize) { ret = write(fd, ptr + offset, totalsize - offset); if (ret < 0) { ret = -errno; break; } offset += ret; } /* Close the file/stdin; return errno on error */ if (fd != 1) close(fd); return ret < 0 ? -ret : 0; } int utilfdt_write(const char *filename, const void *blob) { int ret = utilfdt_write_err(filename, blob); if (ret) { fprintf(stderr, "Couldn't write blob to '%s': %s\n", filename, strerror(ret)); } return ret ? -1 : 0; } int utilfdt_decode_type(const char *fmt, int *type, int *size) { int qualifier = 0; if (!*fmt) return -1; /* get the conversion qualifier */ *size = -1; if (strchr("hlLb", *fmt)) { qualifier = *fmt++; if (qualifier == *fmt) { switch (*fmt++) { /* TODO: case 'l': qualifier = 'L'; break;*/ case 'h': qualifier = 'b'; break; } } } /* we should now have a type */ if ((*fmt == '\0') || !strchr("iuxsr", *fmt)) return -1; /* convert qualifier (bhL) to byte size */ if (*fmt != 's' && *fmt != 'r') *size = qualifier == 'b' ? 1 : qualifier == 'h' ? 2 : qualifier == 'l' ? 4 : -1; *type = *fmt++; /* that should be it! */ if (*fmt) return -1; return 0; } void utilfdt_print_data(const char *data, int len) { int i; const char *s; /* no data, don't print */ if (len == 0) return; if (util_is_printable_string(data, len)) { printf(" = "); s = data; do { printf("\"%s\"", s); s += strlen(s) + 1; if (s < data + len) printf(", "); } while (s < data + len); } else if ((len % 4) == 0) { const fdt32_t *cell = (const fdt32_t *)data; printf(" = <"); for (i = 0, len /= 4; i < len; i++) printf("0x%08" PRIx32 "%s", fdt32_to_cpu(cell[i]), i < (len - 1) ? " " : ""); printf(">"); } else { const unsigned char *p = (const unsigned char *)data; printf(" = ["); for (i = 0; i < len; i++) printf("%02x%s", *p++, i < len - 1 ? " " : ""); printf("]"); } } void NORETURN util_version(void) { printf("Version: %s\n", DTC_VERSION); exit(0); } void NORETURN util_usage(const char *errmsg, const char *synopsis, const char *short_opts, struct option const long_opts[], const char * const opts_help[]) { FILE *fp = errmsg ? stderr : stdout; const char a_arg[] = "<arg>"; size_t a_arg_len = strlen(a_arg) + 1; size_t i; int optlen; fprintf(fp, "Usage: %s\n" "\n" "Options: -[%s]\n", synopsis, short_opts); /* prescan the --long opt length to auto-align */ optlen = 0; for (i = 0; long_opts[i].name; ++i) { /* +1 is for space between --opt and help text */ int l = strlen(long_opts[i].name) + 1; if (long_opts[i].has_arg == a_argument) l += a_arg_len; if (optlen < l) optlen = l; } for (i = 0; long_opts[i].name; ++i) { /* helps when adding new applets or options */ assert(opts_help[i] != NULL); /* first output the short flag if it has one */ if (long_opts[i].val > '~') fprintf(fp, " "); else fprintf(fp, " -%c, ", long_opts[i].val); /* then the long flag */ if (long_opts[i].has_arg == no_argument) fprintf(fp, "--%-*s", optlen, long_opts[i].name); else fprintf(fp, "--%s %s%*s", long_opts[i].name, a_arg, (int)(optlen - strlen(long_opts[i].name) - a_arg_len), ""); /* finally the help text */ fprintf(fp, "%s\n", opts_help[i]); } if (errmsg) { fprintf(fp, "\nError: %s\n", errmsg); exit(EXIT_FAILURE); } else exit(EXIT_SUCCESS); }
linux-master
scripts/dtc/util.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include "dtc.h" #include "srcpos.h" /* * Tree building functions */ void add_label(struct label **labels, char *label) { struct label *new; /* Make sure the label isn't already there */ for_each_label_withdel(*labels, new) if (streq(new->label, label)) { new->deleted = 0; return; } new = xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->label = label; new->next = *labels; *labels = new; } void delete_labels(struct label **labels) { struct label *label; for_each_label(*labels, label) label->deleted = 1; } struct property *build_property(char *name, struct data val, struct srcpos *srcpos) { struct property *new = xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->name = name; new->val = val; new->srcpos = srcpos_copy(srcpos); return new; } struct property *build_property_delete(char *name) { struct property *new = xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->name = name; new->deleted = 1; return new; } struct property *chain_property(struct property *first, struct property *list) { assert(first->next == NULL); first->next = list; return first; } struct property *reverse_properties(struct property *first) { struct property *p = first; struct property *head = NULL; struct property *next; while (p) { next = p->next; p->next = head; head = p; p = next; } return head; } struct node *build_node(struct property *proplist, struct node *children, struct srcpos *srcpos) { struct node *new = xmalloc(sizeof(*new)); struct node *child; memset(new, 0, sizeof(*new)); new->proplist = reverse_properties(proplist); new->children = children; new->srcpos = srcpos_copy(srcpos); for_each_child(new, child) { child->parent = new; } return new; } struct node *build_node_delete(struct srcpos *srcpos) { struct node *new = xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->deleted = 1; new->srcpos = srcpos_copy(srcpos); return new; } struct node *name_node(struct node *node, char *name) { assert(node->name == NULL); node->name = name; return node; } struct node *omit_node_if_unused(struct node *node) { node->omit_if_unused = 1; return node; } struct node *reference_node(struct node *node) { node->is_referenced = 1; return node; } struct node *merge_nodes(struct node *old_node, struct node *new_node) { struct property *new_prop, *old_prop; struct node *new_child, *old_child; struct label *l; old_node->deleted = 0; /* Add new node labels to old node */ for_each_label_withdel(new_node->labels, l) add_label(&old_node->labels, l->label); /* Move properties from the new node to the old node. If there * is a collision, replace the old value with the new */ while (new_node->proplist) { /* Pop the property off the list */ new_prop = new_node->proplist; new_node->proplist = new_prop->next; new_prop->next = NULL; if (new_prop->deleted) { delete_property_by_name(old_node, new_prop->name); free(new_prop); continue; } /* Look for a collision, set new value if there is */ for_each_property_withdel(old_node, old_prop) { if (streq(old_prop->name, new_prop->name)) { /* Add new labels to old property */ for_each_label_withdel(new_prop->labels, l) add_label(&old_prop->labels, l->label); old_prop->val = new_prop->val; old_prop->deleted = 0; free(old_prop->srcpos); old_prop->srcpos = new_prop->srcpos; free(new_prop); new_prop = NULL; break; } } /* if no collision occurred, add property to the old node. */ if (new_prop) add_property(old_node, new_prop); } /* Move the override child nodes into the primary node. If * there is a collision, then merge the nodes. */ while (new_node->children) { /* Pop the child node off the list */ new_child = new_node->children; new_node->children = new_child->next_sibling; new_child->parent = NULL; new_child->next_sibling = NULL; if (new_child->deleted) { delete_node_by_name(old_node, new_child->name); free(new_child); continue; } /* Search for a collision. Merge if there is */ for_each_child_withdel(old_node, old_child) { if (streq(old_child->name, new_child->name)) { merge_nodes(old_child, new_child); new_child = NULL; break; } } /* if no collision occurred, add child to the old node. */ if (new_child) add_child(old_node, new_child); } old_node->srcpos = srcpos_extend(old_node->srcpos, new_node->srcpos); /* The new node contents are now merged into the old node. Free * the new node. */ free(new_node); return old_node; } struct node * add_orphan_node(struct node *dt, struct node *new_node, char *ref) { static unsigned int next_orphan_fragment = 0; struct node *node; struct property *p; struct data d = empty_data; char *name; if (ref[0] == '/') { d = data_add_marker(d, TYPE_STRING, ref); d = data_append_data(d, ref, strlen(ref) + 1); p = build_property("target-path", d, NULL); } else { d = data_add_marker(d, REF_PHANDLE, ref); d = data_append_integer(d, 0xffffffff, 32); p = build_property("target", d, NULL); } xasprintf(&name, "fragment@%u", next_orphan_fragment++); name_node(new_node, "__overlay__"); node = build_node(p, new_node, NULL); name_node(node, name); add_child(dt, node); return dt; } struct node *chain_node(struct node *first, struct node *list) { assert(first->next_sibling == NULL); first->next_sibling = list; return first; } void add_property(struct node *node, struct property *prop) { struct property **p; prop->next = NULL; p = &node->proplist; while (*p) p = &((*p)->next); *p = prop; } void delete_property_by_name(struct node *node, char *name) { struct property *prop = node->proplist; while (prop) { if (streq(prop->name, name)) { delete_property(prop); return; } prop = prop->next; } } void delete_property(struct property *prop) { prop->deleted = 1; delete_labels(&prop->labels); } void add_child(struct node *parent, struct node *child) { struct node **p; child->next_sibling = NULL; child->parent = parent; p = &parent->children; while (*p) p = &((*p)->next_sibling); *p = child; } void delete_node_by_name(struct node *parent, char *name) { struct node *node = parent->children; while (node) { if (streq(node->name, name)) { delete_node(node); return; } node = node->next_sibling; } } void delete_node(struct node *node) { struct property *prop; struct node *child; node->deleted = 1; for_each_child(node, child) delete_node(child); for_each_property(node, prop) delete_property(prop); delete_labels(&node->labels); } void append_to_property(struct node *node, char *name, const void *data, int len, enum markertype type) { struct data d; struct property *p; p = get_property(node, name); if (p) { d = data_add_marker(p->val, type, name); d = data_append_data(d, data, len); p->val = d; } else { d = data_add_marker(empty_data, type, name); d = data_append_data(d, data, len); p = build_property(name, d, NULL); add_property(node, p); } } struct reserve_info *build_reserve_entry(uint64_t address, uint64_t size) { struct reserve_info *new = xmalloc(sizeof(*new)); memset(new, 0, sizeof(*new)); new->address = address; new->size = size; return new; } struct reserve_info *chain_reserve_entry(struct reserve_info *first, struct reserve_info *list) { assert(first->next == NULL); first->next = list; return first; } struct reserve_info *add_reserve_entry(struct reserve_info *list, struct reserve_info *new) { struct reserve_info *last; new->next = NULL; if (! list) return new; for (last = list; last->next; last = last->next) ; last->next = new; return list; } struct dt_info *build_dt_info(unsigned int dtsflags, struct reserve_info *reservelist, struct node *tree, uint32_t boot_cpuid_phys) { struct dt_info *dti; dti = xmalloc(sizeof(*dti)); dti->dtsflags = dtsflags; dti->reservelist = reservelist; dti->dt = tree; dti->boot_cpuid_phys = boot_cpuid_phys; return dti; } /* * Tree accessor functions */ const char *get_unitname(struct node *node) { if (node->name[node->basenamelen] == '\0') return ""; else return node->name + node->basenamelen + 1; } struct property *get_property(struct node *node, const char *propname) { struct property *prop; for_each_property(node, prop) if (streq(prop->name, propname)) return prop; return NULL; } cell_t propval_cell(struct property *prop) { assert(prop->val.len == sizeof(cell_t)); return fdt32_to_cpu(*((fdt32_t *)prop->val.val)); } cell_t propval_cell_n(struct property *prop, unsigned int n) { assert(prop->val.len / sizeof(cell_t) >= n); return fdt32_to_cpu(*((fdt32_t *)prop->val.val + n)); } struct property *get_property_by_label(struct node *tree, const char *label, struct node **node) { struct property *prop; struct node *c; *node = tree; for_each_property(tree, prop) { struct label *l; for_each_label(prop->labels, l) if (streq(l->label, label)) return prop; } for_each_child(tree, c) { prop = get_property_by_label(c, label, node); if (prop) return prop; } *node = NULL; return NULL; } struct marker *get_marker_label(struct node *tree, const char *label, struct node **node, struct property **prop) { struct marker *m; struct property *p; struct node *c; *node = tree; for_each_property(tree, p) { *prop = p; m = p->val.markers; for_each_marker_of_type(m, LABEL) if (streq(m->ref, label)) return m; } for_each_child(tree, c) { m = get_marker_label(c, label, node, prop); if (m) return m; } *prop = NULL; *node = NULL; return NULL; } struct node *get_subnode(struct node *node, const char *nodename) { struct node *child; for_each_child(node, child) if (streq(child->name, nodename)) return child; return NULL; } struct node *get_node_by_path(struct node *tree, const char *path) { const char *p; struct node *child; if (!path || ! (*path)) { if (tree->deleted) return NULL; return tree; } while (path[0] == '/') path++; p = strchr(path, '/'); for_each_child(tree, child) { if (p && strprefixeq(path, (size_t)(p - path), child->name)) return get_node_by_path(child, p+1); else if (!p && streq(path, child->name)) return child; } return NULL; } struct node *get_node_by_label(struct node *tree, const char *label) { struct node *child, *node; struct label *l; assert(label && (strlen(label) > 0)); for_each_label(tree->labels, l) if (streq(l->label, label)) return tree; for_each_child(tree, child) { node = get_node_by_label(child, label); if (node) return node; } return NULL; } struct node *get_node_by_phandle(struct node *tree, cell_t phandle) { struct node *child, *node; if (!phandle_is_valid(phandle)) { assert(generate_fixups); return NULL; } if (tree->phandle == phandle) { if (tree->deleted) return NULL; return tree; } for_each_child(tree, child) { node = get_node_by_phandle(child, phandle); if (node) return node; } return NULL; } struct node *get_node_by_ref(struct node *tree, const char *ref) { struct node *target = tree; const char *label = NULL, *path = NULL; if (streq(ref, "/")) return tree; if (ref[0] == '/') path = ref; else label = ref; if (label) { const char *slash = strchr(label, '/'); char *buf = NULL; if (slash) { buf = xstrndup(label, slash - label); label = buf; path = slash + 1; } target = get_node_by_label(tree, label); free(buf); if (!target) return NULL; } if (path) target = get_node_by_path(target, path); return target; } cell_t get_node_phandle(struct node *root, struct node *node) { static cell_t phandle = 1; /* FIXME: ick, static local */ struct data d = empty_data; if (phandle_is_valid(node->phandle)) return node->phandle; while (get_node_by_phandle(root, phandle)) phandle++; node->phandle = phandle; d = data_add_marker(d, TYPE_UINT32, NULL); d = data_append_cell(d, phandle); if (!get_property(node, "linux,phandle") && (phandle_format & PHANDLE_LEGACY)) add_property(node, build_property("linux,phandle", d, NULL)); if (!get_property(node, "phandle") && (phandle_format & PHANDLE_EPAPR)) add_property(node, build_property("phandle", d, NULL)); /* If the node *does* have a phandle property, we must * be dealing with a self-referencing phandle, which will be * fixed up momentarily in the caller */ return node->phandle; } uint32_t guess_boot_cpuid(struct node *tree) { struct node *cpus, *bootcpu; struct property *reg; cpus = get_node_by_path(tree, "/cpus"); if (!cpus) return 0; bootcpu = cpus->children; if (!bootcpu) return 0; reg = get_property(bootcpu, "reg"); if (!reg || (reg->val.len != sizeof(uint32_t))) return 0; /* FIXME: Sanity check node? */ return propval_cell(reg); } static int cmp_reserve_info(const void *ax, const void *bx) { const struct reserve_info *a, *b; a = *((const struct reserve_info * const *)ax); b = *((const struct reserve_info * const *)bx); if (a->address < b->address) return -1; else if (a->address > b->address) return 1; else if (a->size < b->size) return -1; else if (a->size > b->size) return 1; else return 0; } static void sort_reserve_entries(struct dt_info *dti) { struct reserve_info *ri, **tbl; int n = 0, i = 0; for (ri = dti->reservelist; ri; ri = ri->next) n++; if (n == 0) return; tbl = xmalloc(n * sizeof(*tbl)); for (ri = dti->reservelist; ri; ri = ri->next) tbl[i++] = ri; qsort(tbl, n, sizeof(*tbl), cmp_reserve_info); dti->reservelist = tbl[0]; for (i = 0; i < (n-1); i++) tbl[i]->next = tbl[i+1]; tbl[n-1]->next = NULL; free(tbl); } static int cmp_prop(const void *ax, const void *bx) { const struct property *a, *b; a = *((const struct property * const *)ax); b = *((const struct property * const *)bx); return strcmp(a->name, b->name); } static void sort_properties(struct node *node) { int n = 0, i = 0; struct property *prop, **tbl; for_each_property_withdel(node, prop) n++; if (n == 0) return; tbl = xmalloc(n * sizeof(*tbl)); for_each_property_withdel(node, prop) tbl[i++] = prop; qsort(tbl, n, sizeof(*tbl), cmp_prop); node->proplist = tbl[0]; for (i = 0; i < (n-1); i++) tbl[i]->next = tbl[i+1]; tbl[n-1]->next = NULL; free(tbl); } static int cmp_subnode(const void *ax, const void *bx) { const struct node *a, *b; a = *((const struct node * const *)ax); b = *((const struct node * const *)bx); return strcmp(a->name, b->name); } static void sort_subnodes(struct node *node) { int n = 0, i = 0; struct node *subnode, **tbl; for_each_child_withdel(node, subnode) n++; if (n == 0) return; tbl = xmalloc(n * sizeof(*tbl)); for_each_child_withdel(node, subnode) tbl[i++] = subnode; qsort(tbl, n, sizeof(*tbl), cmp_subnode); node->children = tbl[0]; for (i = 0; i < (n-1); i++) tbl[i]->next_sibling = tbl[i+1]; tbl[n-1]->next_sibling = NULL; free(tbl); } static void sort_node(struct node *node) { struct node *c; sort_properties(node); sort_subnodes(node); for_each_child_withdel(node, c) sort_node(c); } void sort_tree(struct dt_info *dti) { sort_reserve_entries(dti); sort_node(dti->dt); } /* utility helper to avoid code duplication */ static struct node *build_and_name_child_node(struct node *parent, char *name) { struct node *node; node = build_node(NULL, NULL, NULL); name_node(node, xstrdup(name)); add_child(parent, node); return node; } static struct node *build_root_node(struct node *dt, char *name) { struct node *an; an = get_subnode(dt, name); if (!an) an = build_and_name_child_node(dt, name); if (!an) die("Could not build root node /%s\n", name); return an; } static bool any_label_tree(struct dt_info *dti, struct node *node) { struct node *c; if (node->labels) return true; for_each_child(node, c) if (any_label_tree(dti, c)) return true; return false; } static void generate_label_tree_internal(struct dt_info *dti, struct node *an, struct node *node, bool allocph) { struct node *dt = dti->dt; struct node *c; struct property *p; struct label *l; /* if there are labels */ if (node->labels) { /* now add the label in the node */ for_each_label(node->labels, l) { /* check whether the label already exists */ p = get_property(an, l->label); if (p) { fprintf(stderr, "WARNING: label %s already" " exists in /%s", l->label, an->name); continue; } /* insert it */ p = build_property(l->label, data_copy_escape_string(node->fullpath, strlen(node->fullpath)), NULL); add_property(an, p); } /* force allocation of a phandle for this node */ if (allocph) (void)get_node_phandle(dt, node); } for_each_child(node, c) generate_label_tree_internal(dti, an, c, allocph); } static bool any_fixup_tree(struct dt_info *dti, struct node *node) { struct node *c; struct property *prop; struct marker *m; for_each_property(node, prop) { m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { if (!get_node_by_ref(dti->dt, m->ref)) return true; } } for_each_child(node, c) { if (any_fixup_tree(dti, c)) return true; } return false; } static void add_fixup_entry(struct dt_info *dti, struct node *fn, struct node *node, struct property *prop, struct marker *m) { char *entry; /* m->ref can only be a REF_PHANDLE, but check anyway */ assert(m->type == REF_PHANDLE); /* The format only permits fixups for references to label, not * references to path */ if (strchr(m->ref, '/')) die("Can't generate fixup for reference to path &{%s}\n", m->ref); /* there shouldn't be any ':' in the arguments */ if (strchr(node->fullpath, ':') || strchr(prop->name, ':')) die("arguments should not contain ':'\n"); xasprintf(&entry, "%s:%s:%u", node->fullpath, prop->name, m->offset); append_to_property(fn, m->ref, entry, strlen(entry) + 1, TYPE_STRING); free(entry); } static void generate_fixups_tree_internal(struct dt_info *dti, struct node *fn, struct node *node) { struct node *dt = dti->dt; struct node *c; struct property *prop; struct marker *m; struct node *refnode; for_each_property(node, prop) { m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { refnode = get_node_by_ref(dt, m->ref); if (!refnode) add_fixup_entry(dti, fn, node, prop, m); } } for_each_child(node, c) generate_fixups_tree_internal(dti, fn, c); } static bool any_local_fixup_tree(struct dt_info *dti, struct node *node) { struct node *c; struct property *prop; struct marker *m; for_each_property(node, prop) { m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { if (get_node_by_ref(dti->dt, m->ref)) return true; } } for_each_child(node, c) { if (any_local_fixup_tree(dti, c)) return true; } return false; } static void add_local_fixup_entry(struct dt_info *dti, struct node *lfn, struct node *node, struct property *prop, struct marker *m, struct node *refnode) { struct node *wn, *nwn; /* local fixup node, walk node, new */ fdt32_t value_32; char **compp; int i, depth; /* walk back retrieving depth */ depth = 0; for (wn = node; wn; wn = wn->parent) depth++; /* allocate name array */ compp = xmalloc(sizeof(*compp) * depth); /* store names in the array */ for (wn = node, i = depth - 1; wn; wn = wn->parent, i--) compp[i] = wn->name; /* walk the path components creating nodes if they don't exist */ for (wn = lfn, i = 1; i < depth; i++, wn = nwn) { /* if no node exists, create it */ nwn = get_subnode(wn, compp[i]); if (!nwn) nwn = build_and_name_child_node(wn, compp[i]); } free(compp); value_32 = cpu_to_fdt32(m->offset); append_to_property(wn, prop->name, &value_32, sizeof(value_32), TYPE_UINT32); } static void generate_local_fixups_tree_internal(struct dt_info *dti, struct node *lfn, struct node *node) { struct node *dt = dti->dt; struct node *c; struct property *prop; struct marker *m; struct node *refnode; for_each_property(node, prop) { m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { refnode = get_node_by_ref(dt, m->ref); if (refnode) add_local_fixup_entry(dti, lfn, node, prop, m, refnode); } } for_each_child(node, c) generate_local_fixups_tree_internal(dti, lfn, c); } void generate_label_tree(struct dt_info *dti, char *name, bool allocph) { if (!any_label_tree(dti, dti->dt)) return; generate_label_tree_internal(dti, build_root_node(dti->dt, name), dti->dt, allocph); } void generate_fixups_tree(struct dt_info *dti, char *name) { if (!any_fixup_tree(dti, dti->dt)) return; generate_fixups_tree_internal(dti, build_root_node(dti->dt, name), dti->dt); } void generate_local_fixups_tree(struct dt_info *dti, char *name) { if (!any_local_fixup_tree(dti, dti->dt)) return; generate_local_fixups_tree_internal(dti, build_root_node(dti->dt, name), dti->dt); }
linux-master
scripts/dtc/livetree.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include <sys/stat.h> #include "dtc.h" #include "srcpos.h" /* * Command line options */ int quiet; /* Level of quietness */ unsigned int reservenum;/* Number of memory reservation slots */ int minsize; /* Minimum blob size */ int padsize; /* Additional padding to blob */ int alignsize; /* Additional padding to blob accroding to the alignsize */ int phandle_format = PHANDLE_EPAPR; /* Use linux,phandle or phandle properties */ int generate_symbols; /* enable symbols & fixup support */ int generate_fixups; /* suppress generation of fixups on symbol support */ int auto_label_aliases; /* auto generate labels -> aliases */ int annotate; /* Level of annotation: 1 for input source location >1 for full input source location. */ static int is_power_of_2(int x) { return (x > 0) && ((x & (x - 1)) == 0); } static void fill_fullpaths(struct node *tree, const char *prefix) { struct node *child; const char *unit; tree->fullpath = join_path(prefix, tree->name); unit = strchr(tree->name, '@'); if (unit) tree->basenamelen = unit - tree->name; else tree->basenamelen = strlen(tree->name); for_each_child(tree, child) fill_fullpaths(child, tree->fullpath); } /* Usage related data. */ static const char usage_synopsis[] = "dtc [options] <input file>"; static const char usage_short_opts[] = "qI:O:o:V:d:R:S:p:a:fb:i:H:sW:E:@AThv"; static struct option const usage_long_opts[] = { {"quiet", no_argument, NULL, 'q'}, {"in-format", a_argument, NULL, 'I'}, {"out", a_argument, NULL, 'o'}, {"out-format", a_argument, NULL, 'O'}, {"out-version", a_argument, NULL, 'V'}, {"out-dependency", a_argument, NULL, 'd'}, {"reserve", a_argument, NULL, 'R'}, {"space", a_argument, NULL, 'S'}, {"pad", a_argument, NULL, 'p'}, {"align", a_argument, NULL, 'a'}, {"boot-cpu", a_argument, NULL, 'b'}, {"force", no_argument, NULL, 'f'}, {"include", a_argument, NULL, 'i'}, {"sort", no_argument, NULL, 's'}, {"phandle", a_argument, NULL, 'H'}, {"warning", a_argument, NULL, 'W'}, {"error", a_argument, NULL, 'E'}, {"symbols", no_argument, NULL, '@'}, {"auto-alias", no_argument, NULL, 'A'}, {"annotate", no_argument, NULL, 'T'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, no_argument, NULL, 0x0}, }; static const char * const usage_opts_help[] = { "\n\tQuiet: -q suppress warnings, -qq errors, -qqq all", "\n\tInput formats are:\n" "\t\tdts - device tree source text\n" "\t\tdtb - device tree blob\n" "\t\tfs - /proc/device-tree style directory", "\n\tOutput file", "\n\tOutput formats are:\n" "\t\tdts - device tree source text\n" "\t\tdtb - device tree blob\n" #ifndef NO_YAML "\t\tyaml - device tree encoded as YAML\n" #endif "\t\tasm - assembler source", "\n\tBlob version to produce, defaults to "stringify(DEFAULT_FDT_VERSION)" (for dtb and asm output)", "\n\tOutput dependency file", "\n\tMake space for <number> reserve map entries (for dtb and asm output)", "\n\tMake the blob at least <bytes> long (extra space)", "\n\tAdd padding to the blob of <bytes> long (extra space)", "\n\tMake the blob align to the <bytes> (extra space)", "\n\tSet the physical boot cpu", "\n\tTry to produce output even if the input tree has errors", "\n\tAdd a path to search for include files", "\n\tSort nodes and properties before outputting (useful for comparing trees)", "\n\tValid phandle formats are:\n" "\t\tlegacy - \"linux,phandle\" properties only\n" "\t\tepapr - \"phandle\" properties only\n" "\t\tboth - Both \"linux,phandle\" and \"phandle\" properties", "\n\tEnable/disable warnings (prefix with \"no-\")", "\n\tEnable/disable errors (prefix with \"no-\")", "\n\tEnable generation of symbols", "\n\tEnable auto-alias of labels", "\n\tAnnotate output .dts with input source file and line (-T -T for more details)", "\n\tPrint this help and exit", "\n\tPrint version and exit", NULL, }; static const char *guess_type_by_name(const char *fname, const char *fallback) { const char *s; s = strrchr(fname, '.'); if (s == NULL) return fallback; if (!strcasecmp(s, ".dts")) return "dts"; if (!strcasecmp(s, ".yaml")) return "yaml"; if (!strcasecmp(s, ".dtbo")) return "dtb"; if (!strcasecmp(s, ".dtb")) return "dtb"; return fallback; } static const char *guess_input_format(const char *fname, const char *fallback) { struct stat statbuf; fdt32_t magic; FILE *f; if (stat(fname, &statbuf) != 0) return fallback; if (S_ISDIR(statbuf.st_mode)) return "fs"; if (!S_ISREG(statbuf.st_mode)) return fallback; f = fopen(fname, "r"); if (f == NULL) return fallback; if (fread(&magic, 4, 1, f) != 1) { fclose(f); return fallback; } fclose(f); if (fdt32_to_cpu(magic) == FDT_MAGIC) return "dtb"; return guess_type_by_name(fname, fallback); } int main(int argc, char *argv[]) { struct dt_info *dti; const char *inform = NULL; const char *outform = NULL; const char *outname = "-"; const char *depname = NULL; bool force = false, sort = false; const char *arg; int opt; FILE *outf = NULL; int outversion = DEFAULT_FDT_VERSION; long long cmdline_boot_cpuid = -1; quiet = 0; reservenum = 0; minsize = 0; padsize = 0; alignsize = 0; while ((opt = util_getopt_long()) != EOF) { switch (opt) { case 'I': inform = optarg; break; case 'O': outform = optarg; break; case 'o': outname = optarg; break; case 'V': outversion = strtol(optarg, NULL, 0); break; case 'd': depname = optarg; break; case 'R': reservenum = strtoul(optarg, NULL, 0); break; case 'S': minsize = strtol(optarg, NULL, 0); break; case 'p': padsize = strtol(optarg, NULL, 0); break; case 'a': alignsize = strtol(optarg, NULL, 0); if (!is_power_of_2(alignsize)) die("Invalid argument \"%d\" to -a option\n", alignsize); break; case 'f': force = true; break; case 'q': quiet++; break; case 'b': cmdline_boot_cpuid = strtoll(optarg, NULL, 0); break; case 'i': srcfile_add_search_path(optarg); break; case 'v': util_version(); case 'H': if (streq(optarg, "legacy")) phandle_format = PHANDLE_LEGACY; else if (streq(optarg, "epapr")) phandle_format = PHANDLE_EPAPR; else if (streq(optarg, "both")) phandle_format = PHANDLE_BOTH; else die("Invalid argument \"%s\" to -H option\n", optarg); break; case 's': sort = true; break; case 'W': parse_checks_option(true, false, optarg); break; case 'E': parse_checks_option(false, true, optarg); break; case '@': generate_symbols = 1; break; case 'A': auto_label_aliases = 1; break; case 'T': annotate++; break; case 'h': usage(NULL); default: usage("unknown option"); } } if (argc > (optind+1)) usage("missing files"); else if (argc < (optind+1)) arg = "-"; else arg = argv[optind]; /* minsize and padsize are mutually exclusive */ if (minsize && padsize) die("Can't set both -p and -S\n"); if (depname) { depfile = fopen(depname, "w"); if (!depfile) die("Couldn't open dependency file %s: %s\n", depname, strerror(errno)); fprintf(depfile, "%s:", outname); } if (inform == NULL) inform = guess_input_format(arg, "dts"); if (outform == NULL) { outform = guess_type_by_name(outname, NULL); if (outform == NULL) { if (streq(inform, "dts")) outform = "dtb"; else outform = "dts"; } } if (annotate && (!streq(inform, "dts") || !streq(outform, "dts"))) die("--annotate requires -I dts -O dts\n"); if (streq(inform, "dts")) dti = dt_from_source(arg); else if (streq(inform, "fs")) dti = dt_from_fs(arg); else if(streq(inform, "dtb")) dti = dt_from_blob(arg); else die("Unknown input format \"%s\"\n", inform); dti->outname = outname; if (depfile) { fputc('\n', depfile); fclose(depfile); } if (cmdline_boot_cpuid != -1) dti->boot_cpuid_phys = cmdline_boot_cpuid; fill_fullpaths(dti->dt, ""); /* on a plugin, generate by default */ if (dti->dtsflags & DTSF_PLUGIN) { generate_fixups = 1; } process_checks(force, dti); if (auto_label_aliases) generate_label_tree(dti, "aliases", false); if (generate_symbols) generate_label_tree(dti, "__symbols__", true); if (generate_fixups) { generate_fixups_tree(dti, "__fixups__"); generate_local_fixups_tree(dti, "__local_fixups__"); } if (sort) sort_tree(dti); if (streq(outname, "-")) { outf = stdout; } else { outf = fopen(outname, "wb"); if (! outf) die("Couldn't open output file %s: %s\n", outname, strerror(errno)); } if (streq(outform, "dts")) { dt_to_source(outf, dti); #ifndef NO_YAML } else if (streq(outform, "yaml")) { if (!streq(inform, "dts")) die("YAML output format requires dts input format\n"); dt_to_yaml(outf, dti); #endif } else if (streq(outform, "dtb")) { dt_to_blob(outf, dti, outversion); } else if (streq(outform, "asm")) { dt_to_asm(outf, dti, outversion); } else if (streq(outform, "null")) { /* do nothing */ } else { die("Unknown output format \"%s\"\n", outform); } exit(0); }
linux-master
scripts/dtc/dtc.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2011 The Chromium OS Authors. All rights reserved. * * Portions from U-Boot cmd_fdt.c (C) Copyright 2007 * Gerald Van Baren, Custom IDEAS, [email protected] * Based on code written by: * Pantelis Antoniou <[email protected]> and * Matthew McClintock <[email protected]> */ #include <assert.h> #include <ctype.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libfdt.h> #include "util.h" enum display_mode { MODE_SHOW_VALUE, /* show values for node properties */ MODE_LIST_PROPS, /* list the properties for a node */ MODE_LIST_SUBNODES, /* list the subnodes of a node */ }; /* Holds information which controls our output and options */ struct display_info { int type; /* data type (s/i/u/x or 0 for default) */ int size; /* data size (1/2/4) */ enum display_mode mode; /* display mode that we are using */ const char *default_val; /* default value if node/property not found */ }; static void report_error(const char *where, int err) { fprintf(stderr, "Error at '%s': %s\n", where, fdt_strerror(err)); } /** * Displays data of a given length according to selected options * * If a specific data type is provided in disp, then this is used. Otherwise * we try to guess the data type / size from the contents. * * @param disp Display information / options * @param data Data to display * @param len Maximum length of buffer * @return 0 if ok, -1 if data does not match format */ static int show_data(struct display_info *disp, const char *data, int len) { int i, size; const uint8_t *p = (const uint8_t *)data; const char *s; int value; int is_string; char fmt[3]; /* no data, don't print */ if (len == 0) return 0; is_string = (disp->type) == 's' || (!disp->type && util_is_printable_string(data, len)); if (is_string) { if (data[len - 1] != '\0') { fprintf(stderr, "Unterminated string\n"); return -1; } for (s = data; s - data < len; s += strlen(s) + 1) { if (s != data) printf(" "); printf("%s", (const char *)s); } return 0; } size = disp->size; if (size == -1) { size = (len % 4) == 0 ? 4 : 1; } else if (len % size) { fprintf(stderr, "Property length must be a multiple of " "selected data size\n"); return -1; } fmt[0] = '%'; fmt[1] = disp->type ? disp->type : 'd'; fmt[2] = '\0'; for (i = 0; i < len; i += size, p += size) { if (i) printf(" "); value = size == 4 ? fdt32_to_cpu(*(const uint32_t *)p) : size == 2 ? (*p << 8) | p[1] : *p; printf(fmt, value); } return 0; } /** * List all properties in a node, one per line. * * @param blob FDT blob * @param node Node to display * @return 0 if ok, or FDT_ERR... if not. */ static int list_properties(const void *blob, int node) { const struct fdt_property *data; const char *name; int prop; prop = fdt_first_property_offset(blob, node); do { /* Stop silently when there are no more properties */ if (prop < 0) return prop == -FDT_ERR_NOTFOUND ? 0 : prop; data = fdt_get_property_by_offset(blob, prop, NULL); name = fdt_string(blob, fdt32_to_cpu(data->nameoff)); if (name) puts(name); prop = fdt_next_property_offset(blob, prop); } while (1); } #define MAX_LEVEL 32 /* how deeply nested we will go */ /** * List all subnodes in a node, one per line * * @param blob FDT blob * @param node Node to display * @return 0 if ok, or FDT_ERR... if not. */ static int list_subnodes(const void *blob, int node) { int nextoffset; /* next node offset from libfdt */ uint32_t tag; /* current tag */ int level = 0; /* keep track of nesting level */ const char *pathp; int depth = 1; /* the assumed depth of this node */ while (level >= 0) { tag = fdt_next_tag(blob, node, &nextoffset); switch (tag) { case FDT_BEGIN_NODE: pathp = fdt_get_name(blob, node, NULL); if (level <= depth) { if (pathp == NULL) pathp = "/* NULL pointer error */"; if (*pathp == '\0') pathp = "/"; /* root is nameless */ if (level == 1) puts(pathp); } level++; if (level >= MAX_LEVEL) { printf("Nested too deep, aborting.\n"); return 1; } break; case FDT_END_NODE: level--; if (level == 0) level = -1; /* exit the loop */ break; case FDT_END: return 1; case FDT_PROP: break; default: if (level <= depth) printf("Unknown tag 0x%08X\n", tag); return 1; } node = nextoffset; } return 0; } /** * Show the data for a given node (and perhaps property) according to the * display option provided. * * @param blob FDT blob * @param disp Display information / options * @param node Node to display * @param property Name of property to display, or NULL if none * @return 0 if ok, -ve on error */ static int show_data_for_item(const void *blob, struct display_info *disp, int node, const char *property) { const void *value = NULL; int len, err = 0; switch (disp->mode) { case MODE_LIST_PROPS: err = list_properties(blob, node); break; case MODE_LIST_SUBNODES: err = list_subnodes(blob, node); break; default: assert(property); value = fdt_getprop(blob, node, property, &len); if (value) { if (show_data(disp, value, len)) err = -1; else printf("\n"); } else if (disp->default_val) { puts(disp->default_val); } else { report_error(property, len); err = -1; } break; } return err; } /** * Run the main fdtget operation, given a filename and valid arguments * * @param disp Display information / options * @param filename Filename of blob file * @param arg List of arguments to process * @param arg_count Number of arguments * @param return 0 if ok, -ve on error */ static int do_fdtget(struct display_info *disp, const char *filename, char **arg, int arg_count, int args_per_step) { char *blob; const char *prop; int i, node; blob = utilfdt_read(filename); if (!blob) return -1; for (i = 0; i + args_per_step <= arg_count; i += args_per_step) { node = fdt_path_offset(blob, arg[i]); if (node < 0) { if (disp->default_val) { puts(disp->default_val); continue; } else { report_error(arg[i], node); return -1; } } prop = args_per_step == 1 ? NULL : arg[i + 1]; if (show_data_for_item(blob, disp, node, prop)) return -1; } return 0; } static const char *usage_msg = "fdtget - read values from device tree\n" "\n" "Each value is printed on a new line.\n\n" "Usage:\n" " fdtget <options> <dt file> [<node> <property>]...\n" " fdtget -p <options> <dt file> [<node> ]...\n" "Options:\n" "\t-t <type>\tType of data\n" "\t-p\t\tList properties for each node\n" "\t-l\t\tList subnodes for each node\n" "\t-d\t\tDefault value to display when the property is " "missing\n" "\t-h\t\tPrint this help\n\n" USAGE_TYPE_MSG; static void usage(const char *msg) { if (msg) fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "%s", usage_msg); exit(2); } int main(int argc, char *argv[]) { char *filename = NULL; struct display_info disp; int args_per_step = 2; /* set defaults */ memset(&disp, '\0', sizeof(disp)); disp.size = -1; disp.mode = MODE_SHOW_VALUE; for (;;) { int c = getopt(argc, argv, "d:hlpt:"); if (c == -1) break; switch (c) { case 'h': case '?': usage(NULL); case 't': if (utilfdt_decode_type(optarg, &disp.type, &disp.size)) usage("Invalid type string"); break; case 'p': disp.mode = MODE_LIST_PROPS; args_per_step = 1; break; case 'l': disp.mode = MODE_LIST_SUBNODES; args_per_step = 1; break; case 'd': disp.default_val = optarg; break; } } if (optind < argc) filename = argv[optind++]; if (!filename) usage("Missing filename"); argv += optind; argc -= optind; /* Allow no arguments, and silently succeed */ if (!argc) return 0; /* Check for node, property arguments */ if (args_per_step == 2 && (argc % 2)) usage("Must have an even number of arguments"); if (do_fdtget(&disp, filename, argv, argc, args_per_step)) return 1; return 0; }
linux-master
scripts/dtc/fdtget.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2017 Konsulko Group Inc. All rights reserved. * * Author: * Pantelis Antoniou <[email protected]> */ #include <assert.h> #include <ctype.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <libfdt.h> #include "util.h" #define BUF_INCREMENT 65536 /* Usage related data. */ static const char usage_synopsis[] = "apply a number of overlays to a base blob\n" " fdtoverlay <options> [<overlay.dtbo> [<overlay.dtbo>]]\n" "\n" USAGE_TYPE_MSG; static const char usage_short_opts[] = "i:o:v" USAGE_COMMON_SHORT_OPTS; static struct option const usage_long_opts[] = { {"input", required_argument, NULL, 'i'}, {"output", required_argument, NULL, 'o'}, {"verbose", no_argument, NULL, 'v'}, USAGE_COMMON_LONG_OPTS, }; static const char * const usage_opts_help[] = { "Input base DT blob", "Output DT blob", "Verbose messages", USAGE_COMMON_OPTS_HELP }; int verbose = 0; static void *apply_one(char *base, const char *overlay, size_t *buf_len, const char *name) { char *tmp = NULL; char *tmpo; int ret; /* * We take a copies first, because a a failed apply can trash * both the base blob and the overlay */ tmpo = xmalloc(fdt_totalsize(overlay)); do { tmp = xrealloc(tmp, *buf_len); ret = fdt_open_into(base, tmp, *buf_len); if (ret) { fprintf(stderr, "\nFailed to make temporary copy: %s\n", fdt_strerror(ret)); goto fail; } memcpy(tmpo, overlay, fdt_totalsize(overlay)); ret = fdt_overlay_apply(tmp, tmpo); if (ret == -FDT_ERR_NOSPACE) { *buf_len += BUF_INCREMENT; } } while (ret == -FDT_ERR_NOSPACE); if (ret) { fprintf(stderr, "\nFailed to apply '%s': %s\n", name, fdt_strerror(ret)); goto fail; } free(base); free(tmpo); return tmp; fail: free(tmpo); if (tmp) free(tmp); return NULL; } static int do_fdtoverlay(const char *input_filename, const char *output_filename, int argc, char *argv[]) { char *blob = NULL; char **ovblob = NULL; size_t buf_len; int i, ret = -1; blob = utilfdt_read(input_filename, &buf_len); if (!blob) { fprintf(stderr, "\nFailed to read '%s'\n", input_filename); goto out_err; } if (fdt_totalsize(blob) > buf_len) { fprintf(stderr, "\nBase blob is incomplete (%lu / %" PRIu32 " bytes read)\n", (unsigned long)buf_len, fdt_totalsize(blob)); goto out_err; } /* allocate blob pointer array */ ovblob = xmalloc(sizeof(*ovblob) * argc); memset(ovblob, 0, sizeof(*ovblob) * argc); /* read and keep track of the overlay blobs */ for (i = 0; i < argc; i++) { size_t ov_len; ovblob[i] = utilfdt_read(argv[i], &ov_len); if (!ovblob[i]) { fprintf(stderr, "\nFailed to read '%s'\n", argv[i]); goto out_err; } if (fdt_totalsize(ovblob[i]) > ov_len) { fprintf(stderr, "\nOverlay '%s' is incomplete (%lu / %" PRIu32 " bytes read)\n", argv[i], (unsigned long)ov_len, fdt_totalsize(ovblob[i])); goto out_err; } } buf_len = fdt_totalsize(blob); /* apply the overlays in sequence */ for (i = 0; i < argc; i++) { blob = apply_one(blob, ovblob[i], &buf_len, argv[i]); if (!blob) goto out_err; } fdt_pack(blob); ret = utilfdt_write(output_filename, blob); if (ret) fprintf(stderr, "\nFailed to write '%s'\n", output_filename); out_err: if (ovblob) { for (i = 0; i < argc; i++) { if (ovblob[i]) free(ovblob[i]); } free(ovblob); } free(blob); return ret; } int main(int argc, char *argv[]) { int opt, i; char *input_filename = NULL; char *output_filename = NULL; while ((opt = util_getopt_long()) != EOF) { switch (opt) { case_USAGE_COMMON_FLAGS case 'i': input_filename = optarg; break; case 'o': output_filename = optarg; break; case 'v': verbose = 1; break; } } if (!input_filename) usage("missing input file"); if (!output_filename) usage("missing output file"); argv += optind; argc -= optind; if (argc <= 0) usage("missing overlay file(s)"); if (verbose) { printf("input = %s\n", input_filename); printf("output = %s\n", output_filename); for (i = 0; i < argc; i++) printf("overlay[%d] = %s\n", i, argv[i]); } if (do_fdtoverlay(input_filename, output_filename, argc, argv)) return 1; return 0; }
linux-master
scripts/dtc/fdtoverlay.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright 2007 Jon Loeliger, Freescale Semiconductor, Inc. */ #define _GNU_SOURCE #include <stdio.h> #include "dtc.h" #include "srcpos.h" /* A node in our list of directories to search for source/include files */ struct search_path { struct search_path *next; /* next node in list, NULL for end */ const char *dirname; /* name of directory to search */ }; /* This is the list of directories that we search for source files */ static struct search_path *search_path_head, **search_path_tail; /* Detect infinite include recursion. */ #define MAX_SRCFILE_DEPTH (200) static int srcfile_depth; /* = 0 */ static char *get_dirname(const char *path) { const char *slash = strrchr(path, '/'); if (slash) { int len = slash - path; char *dir = xmalloc(len + 1); memcpy(dir, path, len); dir[len] = '\0'; return dir; } return NULL; } FILE *depfile; /* = NULL */ struct srcfile_state *current_srcfile; /* = NULL */ static char *initial_path; /* = NULL */ static int initial_pathlen; /* = 0 */ static bool initial_cpp = true; static void set_initial_path(char *fname) { int i, len = strlen(fname); xasprintf(&initial_path, "%s", fname); initial_pathlen = 0; for (i = 0; i != len; i++) if (initial_path[i] == '/') initial_pathlen++; } static char *shorten_to_initial_path(char *fname) { char *p1, *p2, *prevslash1 = NULL; int slashes = 0; for (p1 = fname, p2 = initial_path; *p1 && *p2; p1++, p2++) { if (*p1 != *p2) break; if (*p1 == '/') { prevslash1 = p1; slashes++; } } p1 = prevslash1 + 1; if (prevslash1) { int diff = initial_pathlen - slashes, i, j; int restlen = strlen(fname) - (p1 - fname); char *res; res = xmalloc((3 * diff) + restlen + 1); for (i = 0, j = 0; i != diff; i++) { res[j++] = '.'; res[j++] = '.'; res[j++] = '/'; } strcpy(res + j, p1); return res; } return NULL; } /** * Try to open a file in a given directory. * * If the filename is an absolute path, then dirname is ignored. If it is a * relative path, then we look in that directory for the file. * * @param dirname Directory to look in, or NULL for none * @param fname Filename to look for * @param fp Set to NULL if file did not open * @return allocated filename on success (caller must free), NULL on failure */ static char *try_open(const char *dirname, const char *fname, FILE **fp) { char *fullname; if (!dirname || fname[0] == '/') fullname = xstrdup(fname); else fullname = join_path(dirname, fname); *fp = fopen(fullname, "rb"); if (!*fp) { free(fullname); fullname = NULL; } return fullname; } /** * Open a file for read access * * If it is a relative filename, we search the full search path for it. * * @param fname Filename to open * @param fp Returns pointer to opened FILE, or NULL on failure * @return pointer to allocated filename, which caller must free */ static char *fopen_any_on_path(const char *fname, FILE **fp) { const char *cur_dir = NULL; struct search_path *node; char *fullname; /* Try current directory first */ assert(fp); if (current_srcfile) cur_dir = current_srcfile->dir; fullname = try_open(cur_dir, fname, fp); /* Failing that, try each search path in turn */ for (node = search_path_head; !*fp && node; node = node->next) fullname = try_open(node->dirname, fname, fp); return fullname; } FILE *srcfile_relative_open(const char *fname, char **fullnamep) { FILE *f; char *fullname; if (streq(fname, "-")) { f = stdin; fullname = xstrdup("<stdin>"); } else { fullname = fopen_any_on_path(fname, &f); if (!f) die("Couldn't open \"%s\": %s\n", fname, strerror(errno)); } if (depfile) fprintf(depfile, " %s", fullname); if (fullnamep) *fullnamep = fullname; else free(fullname); return f; } void srcfile_push(const char *fname) { struct srcfile_state *srcfile; if (srcfile_depth++ >= MAX_SRCFILE_DEPTH) die("Includes nested too deeply"); srcfile = xmalloc(sizeof(*srcfile)); srcfile->f = srcfile_relative_open(fname, &srcfile->name); srcfile->dir = get_dirname(srcfile->name); srcfile->prev = current_srcfile; srcfile->lineno = 1; srcfile->colno = 1; current_srcfile = srcfile; if (srcfile_depth == 1) set_initial_path(srcfile->name); } bool srcfile_pop(void) { struct srcfile_state *srcfile = current_srcfile; assert(srcfile); current_srcfile = srcfile->prev; if (fclose(srcfile->f)) die("Error closing \"%s\": %s\n", srcfile->name, strerror(errno)); /* FIXME: We allow the srcfile_state structure to leak, * because it could still be referenced from a location * variable being carried through the parser somewhere. To * fix this we could either allocate all the files from a * table, or use a pool allocator. */ return current_srcfile ? true : false; } void srcfile_add_search_path(const char *dirname) { struct search_path *node; /* Create the node */ node = xmalloc(sizeof(*node)); node->next = NULL; node->dirname = xstrdup(dirname); /* Add to the end of our list */ if (search_path_tail) *search_path_tail = node; else search_path_head = node; search_path_tail = &node->next; } void srcpos_update(struct srcpos *pos, const char *text, int len) { int i; pos->file = current_srcfile; pos->first_line = current_srcfile->lineno; pos->first_column = current_srcfile->colno; for (i = 0; i < len; i++) if (text[i] == '\n') { current_srcfile->lineno++; current_srcfile->colno = 1; } else { current_srcfile->colno++; } pos->last_line = current_srcfile->lineno; pos->last_column = current_srcfile->colno; } struct srcpos * srcpos_copy(struct srcpos *pos) { struct srcpos *pos_new; struct srcfile_state *srcfile_state; if (!pos) return NULL; pos_new = xmalloc(sizeof(struct srcpos)); assert(pos->next == NULL); memcpy(pos_new, pos, sizeof(struct srcpos)); /* allocate without free */ srcfile_state = xmalloc(sizeof(struct srcfile_state)); memcpy(srcfile_state, pos->file, sizeof(struct srcfile_state)); pos_new->file = srcfile_state; return pos_new; } struct srcpos *srcpos_extend(struct srcpos *pos, struct srcpos *newtail) { struct srcpos *p; if (!pos) return newtail; for (p = pos; p->next != NULL; p = p->next); p->next = newtail; return pos; } char * srcpos_string(struct srcpos *pos) { const char *fname = "<no-file>"; char *pos_str; if (pos->file && pos->file->name) fname = pos->file->name; if (pos->first_line != pos->last_line) xasprintf(&pos_str, "%s:%d.%d-%d.%d", fname, pos->first_line, pos->first_column, pos->last_line, pos->last_column); else if (pos->first_column != pos->last_column) xasprintf(&pos_str, "%s:%d.%d-%d", fname, pos->first_line, pos->first_column, pos->last_column); else xasprintf(&pos_str, "%s:%d.%d", fname, pos->first_line, pos->first_column); return pos_str; } static char * srcpos_string_comment(struct srcpos *pos, bool first_line, int level) { char *pos_str, *fname, *first, *rest; bool fresh_fname = false; if (!pos) { if (level > 1) { xasprintf(&pos_str, "<no-file>:<no-line>"); return pos_str; } else { return NULL; } } if (!pos->file) fname = "<no-file>"; else if (!pos->file->name) fname = "<no-filename>"; else if (level > 1) fname = pos->file->name; else { fname = shorten_to_initial_path(pos->file->name); if (fname) fresh_fname = true; else fname = pos->file->name; } if (level > 1) xasprintf(&first, "%s:%d:%d-%d:%d", fname, pos->first_line, pos->first_column, pos->last_line, pos->last_column); else xasprintf(&first, "%s:%d", fname, first_line ? pos->first_line : pos->last_line); if (fresh_fname) free(fname); if (pos->next != NULL) { rest = srcpos_string_comment(pos->next, first_line, level); xasprintf(&pos_str, "%s, %s", first, rest); free(first); free(rest); } else { pos_str = first; } return pos_str; } char *srcpos_string_first(struct srcpos *pos, int level) { return srcpos_string_comment(pos, true, level); } char *srcpos_string_last(struct srcpos *pos, int level) { return srcpos_string_comment(pos, false, level); } void srcpos_verror(struct srcpos *pos, const char *prefix, const char *fmt, va_list va) { char *srcstr; srcstr = srcpos_string(pos); fprintf(stderr, "%s: %s ", prefix, srcstr); vfprintf(stderr, fmt, va); fprintf(stderr, "\n"); free(srcstr); } void srcpos_error(struct srcpos *pos, const char *prefix, const char *fmt, ...) { va_list va; va_start(va, fmt); srcpos_verror(pos, prefix, fmt, va); va_end(va); } void srcpos_set_line(char *f, int l) { current_srcfile->name = f; current_srcfile->lineno = l; if (initial_cpp) { initial_cpp = false; set_initial_path(f); } }
linux-master
scripts/dtc/srcpos.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include "dtc.h" #include "srcpos.h" #define FTF_FULLPATH 0x1 #define FTF_VARALIGN 0x2 #define FTF_NAMEPROPS 0x4 #define FTF_BOOTCPUID 0x8 #define FTF_STRTABSIZE 0x10 #define FTF_STRUCTSIZE 0x20 #define FTF_NOPS 0x40 static struct version_info { int version; int last_comp_version; int hdr_size; int flags; } version_table[] = { {1, 1, FDT_V1_SIZE, FTF_FULLPATH|FTF_VARALIGN|FTF_NAMEPROPS}, {2, 1, FDT_V2_SIZE, FTF_FULLPATH|FTF_VARALIGN|FTF_NAMEPROPS|FTF_BOOTCPUID}, {3, 1, FDT_V3_SIZE, FTF_FULLPATH|FTF_VARALIGN|FTF_NAMEPROPS|FTF_BOOTCPUID|FTF_STRTABSIZE}, {16, 16, FDT_V3_SIZE, FTF_BOOTCPUID|FTF_STRTABSIZE|FTF_NOPS}, {17, 16, FDT_V17_SIZE, FTF_BOOTCPUID|FTF_STRTABSIZE|FTF_STRUCTSIZE|FTF_NOPS}, }; struct emitter { void (*cell)(void *, cell_t); void (*string)(void *, const char *, int); void (*align)(void *, int); void (*data)(void *, struct data); void (*beginnode)(void *, struct label *labels); void (*endnode)(void *, struct label *labels); void (*property)(void *, struct label *labels); }; static void bin_emit_cell(void *e, cell_t val) { struct data *dtbuf = e; *dtbuf = data_append_cell(*dtbuf, val); } static void bin_emit_string(void *e, const char *str, int len) { struct data *dtbuf = e; if (len == 0) len = strlen(str); *dtbuf = data_append_data(*dtbuf, str, len); *dtbuf = data_append_byte(*dtbuf, '\0'); } static void bin_emit_align(void *e, int a) { struct data *dtbuf = e; *dtbuf = data_append_align(*dtbuf, a); } static void bin_emit_data(void *e, struct data d) { struct data *dtbuf = e; *dtbuf = data_append_data(*dtbuf, d.val, d.len); } static void bin_emit_beginnode(void *e, struct label *labels) { bin_emit_cell(e, FDT_BEGIN_NODE); } static void bin_emit_endnode(void *e, struct label *labels) { bin_emit_cell(e, FDT_END_NODE); } static void bin_emit_property(void *e, struct label *labels) { bin_emit_cell(e, FDT_PROP); } static struct emitter bin_emitter = { .cell = bin_emit_cell, .string = bin_emit_string, .align = bin_emit_align, .data = bin_emit_data, .beginnode = bin_emit_beginnode, .endnode = bin_emit_endnode, .property = bin_emit_property, }; static void emit_label(FILE *f, const char *prefix, const char *label) { fprintf(f, "\t.globl\t%s_%s\n", prefix, label); fprintf(f, "%s_%s:\n", prefix, label); fprintf(f, "_%s_%s:\n", prefix, label); } static void emit_offset_label(FILE *f, const char *label, int offset) { fprintf(f, "\t.globl\t%s\n", label); fprintf(f, "%s\t= . + %d\n", label, offset); } #define ASM_EMIT_BELONG(f, fmt, ...) \ { \ fprintf((f), "\t.byte\t((" fmt ") >> 24) & 0xff\n", __VA_ARGS__); \ fprintf((f), "\t.byte\t((" fmt ") >> 16) & 0xff\n", __VA_ARGS__); \ fprintf((f), "\t.byte\t((" fmt ") >> 8) & 0xff\n", __VA_ARGS__); \ fprintf((f), "\t.byte\t(" fmt ") & 0xff\n", __VA_ARGS__); \ } static void asm_emit_cell(void *e, cell_t val) { FILE *f = e; fprintf(f, "\t.byte\t0x%02x\n" "\t.byte\t0x%02x\n" "\t.byte\t0x%02x\n" "\t.byte\t0x%02x\n", (val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff); } static void asm_emit_string(void *e, const char *str, int len) { FILE *f = e; if (len != 0) fprintf(f, "\t.asciz\t\"%.*s\"\n", len, str); else fprintf(f, "\t.asciz\t\"%s\"\n", str); } static void asm_emit_align(void *e, int a) { FILE *f = e; fprintf(f, "\t.balign\t%d, 0\n", a); } static void asm_emit_data(void *e, struct data d) { FILE *f = e; unsigned int off = 0; struct marker *m = d.markers; for_each_marker_of_type(m, LABEL) emit_offset_label(f, m->ref, m->offset); while ((d.len - off) >= sizeof(uint32_t)) { asm_emit_cell(e, dtb_ld32(d.val + off)); off += sizeof(uint32_t); } while ((d.len - off) >= 1) { fprintf(f, "\t.byte\t0x%hhx\n", d.val[off]); off += 1; } assert(off == d.len); } static void asm_emit_beginnode(void *e, struct label *labels) { FILE *f = e; struct label *l; for_each_label(labels, l) { fprintf(f, "\t.globl\t%s\n", l->label); fprintf(f, "%s:\n", l->label); } fprintf(f, "\t/* FDT_BEGIN_NODE */\n"); asm_emit_cell(e, FDT_BEGIN_NODE); } static void asm_emit_endnode(void *e, struct label *labels) { FILE *f = e; struct label *l; fprintf(f, "\t/* FDT_END_NODE */\n"); asm_emit_cell(e, FDT_END_NODE); for_each_label(labels, l) { fprintf(f, "\t.globl\t%s_end\n", l->label); fprintf(f, "%s_end:\n", l->label); } } static void asm_emit_property(void *e, struct label *labels) { FILE *f = e; struct label *l; for_each_label(labels, l) { fprintf(f, "\t.globl\t%s\n", l->label); fprintf(f, "%s:\n", l->label); } fprintf(f, "\t/* FDT_PROP */\n"); asm_emit_cell(e, FDT_PROP); } static struct emitter asm_emitter = { .cell = asm_emit_cell, .string = asm_emit_string, .align = asm_emit_align, .data = asm_emit_data, .beginnode = asm_emit_beginnode, .endnode = asm_emit_endnode, .property = asm_emit_property, }; static int stringtable_insert(struct data *d, const char *str) { unsigned int i; /* FIXME: do this more efficiently? */ for (i = 0; i < d->len; i++) { if (streq(str, d->val + i)) return i; } *d = data_append_data(*d, str, strlen(str)+1); return i; } static void flatten_tree(struct node *tree, struct emitter *emit, void *etarget, struct data *strbuf, struct version_info *vi) { struct property *prop; struct node *child; bool seen_name_prop = false; if (tree->deleted) return; emit->beginnode(etarget, tree->labels); if (vi->flags & FTF_FULLPATH) emit->string(etarget, tree->fullpath, 0); else emit->string(etarget, tree->name, 0); emit->align(etarget, sizeof(cell_t)); for_each_property(tree, prop) { int nameoff; if (streq(prop->name, "name")) seen_name_prop = true; nameoff = stringtable_insert(strbuf, prop->name); emit->property(etarget, prop->labels); emit->cell(etarget, prop->val.len); emit->cell(etarget, nameoff); if ((vi->flags & FTF_VARALIGN) && (prop->val.len >= 8)) emit->align(etarget, 8); emit->data(etarget, prop->val); emit->align(etarget, sizeof(cell_t)); } if ((vi->flags & FTF_NAMEPROPS) && !seen_name_prop) { emit->property(etarget, NULL); emit->cell(etarget, tree->basenamelen+1); emit->cell(etarget, stringtable_insert(strbuf, "name")); if ((vi->flags & FTF_VARALIGN) && ((tree->basenamelen+1) >= 8)) emit->align(etarget, 8); emit->string(etarget, tree->name, tree->basenamelen); emit->align(etarget, sizeof(cell_t)); } for_each_child(tree, child) { flatten_tree(child, emit, etarget, strbuf, vi); } emit->endnode(etarget, tree->labels); } static struct data flatten_reserve_list(struct reserve_info *reservelist, struct version_info *vi) { struct reserve_info *re; struct data d = empty_data; unsigned int j; for (re = reservelist; re; re = re->next) { d = data_append_re(d, re->address, re->size); } /* * Add additional reserved slots if the user asked for them. */ for (j = 0; j < reservenum; j++) { d = data_append_re(d, 0, 0); } return d; } static void make_fdt_header(struct fdt_header *fdt, struct version_info *vi, int reservesize, int dtsize, int strsize, int boot_cpuid_phys) { int reserve_off; reservesize += sizeof(struct fdt_reserve_entry); memset(fdt, 0xff, sizeof(*fdt)); fdt->magic = cpu_to_fdt32(FDT_MAGIC); fdt->version = cpu_to_fdt32(vi->version); fdt->last_comp_version = cpu_to_fdt32(vi->last_comp_version); /* Reserve map should be doubleword aligned */ reserve_off = ALIGN(vi->hdr_size, 8); fdt->off_mem_rsvmap = cpu_to_fdt32(reserve_off); fdt->off_dt_struct = cpu_to_fdt32(reserve_off + reservesize); fdt->off_dt_strings = cpu_to_fdt32(reserve_off + reservesize + dtsize); fdt->totalsize = cpu_to_fdt32(reserve_off + reservesize + dtsize + strsize); if (vi->flags & FTF_BOOTCPUID) fdt->boot_cpuid_phys = cpu_to_fdt32(boot_cpuid_phys); if (vi->flags & FTF_STRTABSIZE) fdt->size_dt_strings = cpu_to_fdt32(strsize); if (vi->flags & FTF_STRUCTSIZE) fdt->size_dt_struct = cpu_to_fdt32(dtsize); } void dt_to_blob(FILE *f, struct dt_info *dti, int version) { struct version_info *vi = NULL; unsigned int i; struct data blob = empty_data; struct data reservebuf = empty_data; struct data dtbuf = empty_data; struct data strbuf = empty_data; struct fdt_header fdt; int padlen = 0; for (i = 0; i < ARRAY_SIZE(version_table); i++) { if (version_table[i].version == version) vi = &version_table[i]; } if (!vi) die("Unknown device tree blob version %d\n", version); flatten_tree(dti->dt, &bin_emitter, &dtbuf, &strbuf, vi); bin_emit_cell(&dtbuf, FDT_END); reservebuf = flatten_reserve_list(dti->reservelist, vi); /* Make header */ make_fdt_header(&fdt, vi, reservebuf.len, dtbuf.len, strbuf.len, dti->boot_cpuid_phys); /* * If the user asked for more space than is used, adjust the totalsize. */ if (minsize > 0) { padlen = minsize - fdt32_to_cpu(fdt.totalsize); if (padlen < 0) { padlen = 0; if (quiet < 1) fprintf(stderr, "Warning: blob size %"PRIu32" >= minimum size %d\n", fdt32_to_cpu(fdt.totalsize), minsize); } } if (padsize > 0) padlen = padsize; if (alignsize > 0) padlen = ALIGN(fdt32_to_cpu(fdt.totalsize) + padlen, alignsize) - fdt32_to_cpu(fdt.totalsize); if (padlen > 0) { int tsize = fdt32_to_cpu(fdt.totalsize); tsize += padlen; fdt.totalsize = cpu_to_fdt32(tsize); } /* * Assemble the blob: start with the header, add with alignment * the reserve buffer, add the reserve map terminating zeroes, * the device tree itself, and finally the strings. */ blob = data_append_data(blob, &fdt, vi->hdr_size); blob = data_append_align(blob, 8); blob = data_merge(blob, reservebuf); blob = data_append_zeroes(blob, sizeof(struct fdt_reserve_entry)); blob = data_merge(blob, dtbuf); blob = data_merge(blob, strbuf); /* * If the user asked for more space than is used, pad out the blob. */ if (padlen > 0) blob = data_append_zeroes(blob, padlen); if (fwrite(blob.val, blob.len, 1, f) != 1) { if (ferror(f)) die("Error writing device tree blob: %s\n", strerror(errno)); else die("Short write on device tree blob\n"); } /* * data_merge() frees the right-hand element so only the blob * remains to be freed. */ data_free(blob); } static void dump_stringtable_asm(FILE *f, struct data strbuf) { const char *p; int len; p = strbuf.val; while (p < (strbuf.val + strbuf.len)) { len = strlen(p); fprintf(f, "\t.asciz \"%s\"\n", p); p += len+1; } } void dt_to_asm(FILE *f, struct dt_info *dti, int version) { struct version_info *vi = NULL; unsigned int i; struct data strbuf = empty_data; struct reserve_info *re; const char *symprefix = "dt"; for (i = 0; i < ARRAY_SIZE(version_table); i++) { if (version_table[i].version == version) vi = &version_table[i]; } if (!vi) die("Unknown device tree blob version %d\n", version); fprintf(f, "/* autogenerated by dtc, do not edit */\n\n"); emit_label(f, symprefix, "blob_start"); emit_label(f, symprefix, "header"); fprintf(f, "\t/* magic */\n"); asm_emit_cell(f, FDT_MAGIC); fprintf(f, "\t/* totalsize */\n"); ASM_EMIT_BELONG(f, "_%s_blob_abs_end - _%s_blob_start", symprefix, symprefix); fprintf(f, "\t/* off_dt_struct */\n"); ASM_EMIT_BELONG(f, "_%s_struct_start - _%s_blob_start", symprefix, symprefix); fprintf(f, "\t/* off_dt_strings */\n"); ASM_EMIT_BELONG(f, "_%s_strings_start - _%s_blob_start", symprefix, symprefix); fprintf(f, "\t/* off_mem_rsvmap */\n"); ASM_EMIT_BELONG(f, "_%s_reserve_map - _%s_blob_start", symprefix, symprefix); fprintf(f, "\t/* version */\n"); asm_emit_cell(f, vi->version); fprintf(f, "\t/* last_comp_version */\n"); asm_emit_cell(f, vi->last_comp_version); if (vi->flags & FTF_BOOTCPUID) { fprintf(f, "\t/* boot_cpuid_phys */\n"); asm_emit_cell(f, dti->boot_cpuid_phys); } if (vi->flags & FTF_STRTABSIZE) { fprintf(f, "\t/* size_dt_strings */\n"); ASM_EMIT_BELONG(f, "_%s_strings_end - _%s_strings_start", symprefix, symprefix); } if (vi->flags & FTF_STRUCTSIZE) { fprintf(f, "\t/* size_dt_struct */\n"); ASM_EMIT_BELONG(f, "_%s_struct_end - _%s_struct_start", symprefix, symprefix); } /* * Reserve map entries. * Align the reserve map to a doubleword boundary. * Each entry is an (address, size) pair of u64 values. * Always supply a zero-sized temination entry. */ asm_emit_align(f, 8); emit_label(f, symprefix, "reserve_map"); fprintf(f, "/* Memory reserve map from source file */\n"); /* * Use .long on high and low halves of u64s to avoid .quad * as it appears .quad isn't available in some assemblers. */ for (re = dti->reservelist; re; re = re->next) { struct label *l; for_each_label(re->labels, l) { fprintf(f, "\t.globl\t%s\n", l->label); fprintf(f, "%s:\n", l->label); } ASM_EMIT_BELONG(f, "0x%08x", (unsigned int)(re->address >> 32)); ASM_EMIT_BELONG(f, "0x%08x", (unsigned int)(re->address & 0xffffffff)); ASM_EMIT_BELONG(f, "0x%08x", (unsigned int)(re->size >> 32)); ASM_EMIT_BELONG(f, "0x%08x", (unsigned int)(re->size & 0xffffffff)); } for (i = 0; i < reservenum; i++) { fprintf(f, "\t.long\t0, 0\n\t.long\t0, 0\n"); } fprintf(f, "\t.long\t0, 0\n\t.long\t0, 0\n"); emit_label(f, symprefix, "struct_start"); flatten_tree(dti->dt, &asm_emitter, f, &strbuf, vi); fprintf(f, "\t/* FDT_END */\n"); asm_emit_cell(f, FDT_END); emit_label(f, symprefix, "struct_end"); emit_label(f, symprefix, "strings_start"); dump_stringtable_asm(f, strbuf); emit_label(f, symprefix, "strings_end"); emit_label(f, symprefix, "blob_end"); /* * If the user asked for more space than is used, pad it out. */ if (minsize > 0) { fprintf(f, "\t.space\t%d - (_%s_blob_end - _%s_blob_start), 0\n", minsize, symprefix, symprefix); } if (padsize > 0) { fprintf(f, "\t.space\t%d, 0\n", padsize); } if (alignsize > 0) asm_emit_align(f, alignsize); emit_label(f, symprefix, "blob_abs_end"); data_free(strbuf); } struct inbuf { char *base, *limit, *ptr; }; static void inbuf_init(struct inbuf *inb, void *base, void *limit) { inb->base = base; inb->limit = limit; inb->ptr = inb->base; } static void flat_read_chunk(struct inbuf *inb, void *p, int len) { if ((inb->ptr + len) > inb->limit) die("Premature end of data parsing flat device tree\n"); memcpy(p, inb->ptr, len); inb->ptr += len; } static uint32_t flat_read_word(struct inbuf *inb) { fdt32_t val; assert(((inb->ptr - inb->base) % sizeof(val)) == 0); flat_read_chunk(inb, &val, sizeof(val)); return fdt32_to_cpu(val); } static void flat_realign(struct inbuf *inb, int align) { int off = inb->ptr - inb->base; inb->ptr = inb->base + ALIGN(off, align); if (inb->ptr > inb->limit) die("Premature end of data parsing flat device tree\n"); } static char *flat_read_string(struct inbuf *inb) { int len = 0; const char *p = inb->ptr; char *str; do { if (p >= inb->limit) die("Premature end of data parsing flat device tree\n"); len++; } while ((*p++) != '\0'); str = xstrdup(inb->ptr); inb->ptr += len; flat_realign(inb, sizeof(uint32_t)); return str; } static struct data flat_read_data(struct inbuf *inb, int len) { struct data d = empty_data; if (len == 0) return empty_data; d = data_grow_for(d, len); d.len = len; flat_read_chunk(inb, d.val, len); flat_realign(inb, sizeof(uint32_t)); return d; } static char *flat_read_stringtable(struct inbuf *inb, int offset) { const char *p; p = inb->base + offset; while (1) { if (p >= inb->limit || p < inb->base) die("String offset %d overruns string table\n", offset); if (*p == '\0') break; p++; } return xstrdup(inb->base + offset); } static struct property *flat_read_property(struct inbuf *dtbuf, struct inbuf *strbuf, int flags) { uint32_t proplen, stroff; char *name; struct data val; proplen = flat_read_word(dtbuf); stroff = flat_read_word(dtbuf); name = flat_read_stringtable(strbuf, stroff); if ((flags & FTF_VARALIGN) && (proplen >= 8)) flat_realign(dtbuf, 8); val = flat_read_data(dtbuf, proplen); return build_property(name, val, NULL); } static struct reserve_info *flat_read_mem_reserve(struct inbuf *inb) { struct reserve_info *reservelist = NULL; struct reserve_info *new; struct fdt_reserve_entry re; /* * Each entry is a pair of u64 (addr, size) values for 4 cell_t's. * List terminates at an entry with size equal to zero. * * First pass, count entries. */ while (1) { uint64_t address, size; flat_read_chunk(inb, &re, sizeof(re)); address = fdt64_to_cpu(re.address); size = fdt64_to_cpu(re.size); if (size == 0) break; new = build_reserve_entry(address, size); reservelist = add_reserve_entry(reservelist, new); } return reservelist; } static char *nodename_from_path(const char *ppath, const char *cpath) { int plen; plen = strlen(ppath); if (!strstarts(cpath, ppath)) die("Path \"%s\" is not valid as a child of \"%s\"\n", cpath, ppath); /* root node is a special case */ if (!streq(ppath, "/")) plen++; return xstrdup(cpath + plen); } static struct node *unflatten_tree(struct inbuf *dtbuf, struct inbuf *strbuf, const char *parent_flatname, int flags) { struct node *node; char *flatname; uint32_t val; node = build_node(NULL, NULL, NULL); flatname = flat_read_string(dtbuf); if (flags & FTF_FULLPATH) node->name = nodename_from_path(parent_flatname, flatname); else node->name = flatname; do { struct property *prop; struct node *child; val = flat_read_word(dtbuf); switch (val) { case FDT_PROP: if (node->children) fprintf(stderr, "Warning: Flat tree input has " "subnodes preceding a property.\n"); prop = flat_read_property(dtbuf, strbuf, flags); add_property(node, prop); break; case FDT_BEGIN_NODE: child = unflatten_tree(dtbuf,strbuf, flatname, flags); add_child(node, child); break; case FDT_END_NODE: break; case FDT_END: die("Premature FDT_END in device tree blob\n"); break; case FDT_NOP: if (!(flags & FTF_NOPS)) fprintf(stderr, "Warning: NOP tag found in flat tree" " version <16\n"); /* Ignore */ break; default: die("Invalid opcode word %08x in device tree blob\n", val); } } while (val != FDT_END_NODE); if (node->name != flatname) { free(flatname); } return node; } struct dt_info *dt_from_blob(const char *fname) { FILE *f; fdt32_t magic_buf, totalsize_buf; uint32_t magic, totalsize, version, size_dt, boot_cpuid_phys; uint32_t off_dt, off_str, off_mem_rsvmap; int rc; char *blob; struct fdt_header *fdt; char *p; struct inbuf dtbuf, strbuf; struct inbuf memresvbuf; int sizeleft; struct reserve_info *reservelist; struct node *tree; uint32_t val; int flags = 0; f = srcfile_relative_open(fname, NULL); rc = fread(&magic_buf, sizeof(magic_buf), 1, f); if (ferror(f)) die("Error reading DT blob magic number: %s\n", strerror(errno)); if (rc < 1) { if (feof(f)) die("EOF reading DT blob magic number\n"); else die("Mysterious short read reading magic number\n"); } magic = fdt32_to_cpu(magic_buf); if (magic != FDT_MAGIC) die("Blob has incorrect magic number\n"); rc = fread(&totalsize_buf, sizeof(totalsize_buf), 1, f); if (ferror(f)) die("Error reading DT blob size: %s\n", strerror(errno)); if (rc < 1) { if (feof(f)) die("EOF reading DT blob size\n"); else die("Mysterious short read reading blob size\n"); } totalsize = fdt32_to_cpu(totalsize_buf); if (totalsize < FDT_V1_SIZE) die("DT blob size (%d) is too small\n", totalsize); blob = xmalloc(totalsize); fdt = (struct fdt_header *)blob; fdt->magic = cpu_to_fdt32(magic); fdt->totalsize = cpu_to_fdt32(totalsize); sizeleft = totalsize - sizeof(magic) - sizeof(totalsize); p = blob + sizeof(magic) + sizeof(totalsize); while (sizeleft) { if (feof(f)) die("EOF before reading %d bytes of DT blob\n", totalsize); rc = fread(p, 1, sizeleft, f); if (ferror(f)) die("Error reading DT blob: %s\n", strerror(errno)); sizeleft -= rc; p += rc; } off_dt = fdt32_to_cpu(fdt->off_dt_struct); off_str = fdt32_to_cpu(fdt->off_dt_strings); off_mem_rsvmap = fdt32_to_cpu(fdt->off_mem_rsvmap); version = fdt32_to_cpu(fdt->version); boot_cpuid_phys = fdt32_to_cpu(fdt->boot_cpuid_phys); if (off_mem_rsvmap >= totalsize) die("Mem Reserve structure offset exceeds total size\n"); if (off_dt >= totalsize) die("DT structure offset exceeds total size\n"); if (off_str > totalsize) die("String table offset exceeds total size\n"); if (version >= 3) { uint32_t size_str = fdt32_to_cpu(fdt->size_dt_strings); if ((off_str+size_str < off_str) || (off_str+size_str > totalsize)) die("String table extends past total size\n"); inbuf_init(&strbuf, blob + off_str, blob + off_str + size_str); } else { inbuf_init(&strbuf, blob + off_str, blob + totalsize); } if (version >= 17) { size_dt = fdt32_to_cpu(fdt->size_dt_struct); if ((off_dt+size_dt < off_dt) || (off_dt+size_dt > totalsize)) die("Structure block extends past total size\n"); } if (version < 16) { flags |= FTF_FULLPATH | FTF_NAMEPROPS | FTF_VARALIGN; } else { flags |= FTF_NOPS; } inbuf_init(&memresvbuf, blob + off_mem_rsvmap, blob + totalsize); inbuf_init(&dtbuf, blob + off_dt, blob + totalsize); reservelist = flat_read_mem_reserve(&memresvbuf); val = flat_read_word(&dtbuf); if (val != FDT_BEGIN_NODE) die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val); tree = unflatten_tree(&dtbuf, &strbuf, "", flags); val = flat_read_word(&dtbuf); if (val != FDT_END) die("Device tree blob doesn't end with FDT_END\n"); free(blob); fclose(f); return build_dt_info(DTSF_V1, reservelist, tree, boot_cpuid_phys); }
linux-master
scripts/dtc/flattree.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include "dtc.h" #include "srcpos.h" extern FILE *yyin; extern int yyparse(void); extern YYLTYPE yylloc; struct dt_info *parser_output; bool treesource_error; struct dt_info *dt_from_source(const char *fname) { parser_output = NULL; treesource_error = false; srcfile_push(fname); yyin = current_srcfile->f; yylloc.file = current_srcfile; if (yyparse() != 0) die("Unable to parse input tree\n"); if (treesource_error) die("Syntax error parsing input tree\n"); return parser_output; } static void write_prefix(FILE *f, int level) { int i; for (i = 0; i < level; i++) fputc('\t', f); } static bool isstring(char c) { return (isprint((unsigned char)c) || (c == '\0') || strchr("\a\b\t\n\v\f\r", c)); } static void write_propval_string(FILE *f, const char *s, size_t len) { const char *end = s + len - 1; if (!len) return; assert(*end == '\0'); fprintf(f, "\""); while (s < end) { char c = *s++; switch (c) { case '\a': fprintf(f, "\\a"); break; case '\b': fprintf(f, "\\b"); break; case '\t': fprintf(f, "\\t"); break; case '\n': fprintf(f, "\\n"); break; case '\v': fprintf(f, "\\v"); break; case '\f': fprintf(f, "\\f"); break; case '\r': fprintf(f, "\\r"); break; case '\\': fprintf(f, "\\\\"); break; case '\"': fprintf(f, "\\\""); break; case '\0': fprintf(f, "\\0"); break; default: if (isprint((unsigned char)c)) fprintf(f, "%c", c); else fprintf(f, "\\x%02"PRIx8, c); } } fprintf(f, "\""); } static void write_propval_int(FILE *f, const char *p, size_t len, size_t width) { const char *end = p + len; assert(len % width == 0); for (; p < end; p += width) { switch (width) { case 1: fprintf(f, "%02"PRIx8, *(const uint8_t*)p); break; case 2: fprintf(f, "0x%02"PRIx16, dtb_ld16(p)); break; case 4: fprintf(f, "0x%02"PRIx32, dtb_ld32(p)); break; case 8: fprintf(f, "0x%02"PRIx64, dtb_ld64(p)); break; } if (p + width < end) fputc(' ', f); } } static const char *delim_start[] = { [TYPE_UINT8] = "[", [TYPE_UINT16] = "/bits/ 16 <", [TYPE_UINT32] = "<", [TYPE_UINT64] = "/bits/ 64 <", [TYPE_STRING] = "", }; static const char *delim_end[] = { [TYPE_UINT8] = "]", [TYPE_UINT16] = ">", [TYPE_UINT32] = ">", [TYPE_UINT64] = ">", [TYPE_STRING] = "", }; static enum markertype guess_value_type(struct property *prop) { int len = prop->val.len; const char *p = prop->val.val; struct marker *m = prop->val.markers; int nnotstring = 0, nnul = 0; int nnotstringlbl = 0, nnotcelllbl = 0; int i; for (i = 0; i < len; i++) { if (! isstring(p[i])) nnotstring++; if (p[i] == '\0') nnul++; } for_each_marker_of_type(m, LABEL) { if ((m->offset > 0) && (prop->val.val[m->offset - 1] != '\0')) nnotstringlbl++; if ((m->offset % sizeof(cell_t)) != 0) nnotcelllbl++; } if ((p[len-1] == '\0') && (nnotstring == 0) && (nnul <= (len-nnul)) && (nnotstringlbl == 0)) { return TYPE_STRING; } else if (((len % sizeof(cell_t)) == 0) && (nnotcelllbl == 0)) { return TYPE_UINT32; } return TYPE_UINT8; } static void write_propval(FILE *f, struct property *prop) { size_t len = prop->val.len; struct marker *m = prop->val.markers; struct marker dummy_marker; enum markertype emit_type = TYPE_NONE; char *srcstr; if (len == 0) { fprintf(f, ";"); if (annotate) { srcstr = srcpos_string_first(prop->srcpos, annotate); if (srcstr) { fprintf(f, " /* %s */", srcstr); free(srcstr); } } fprintf(f, "\n"); return; } fprintf(f, " ="); if (!next_type_marker(m)) { /* data type information missing, need to guess */ dummy_marker.type = guess_value_type(prop); dummy_marker.next = prop->val.markers; dummy_marker.offset = 0; dummy_marker.ref = NULL; m = &dummy_marker; } for_each_marker(m) { size_t chunk_len = (m->next ? m->next->offset : len) - m->offset; size_t data_len = type_marker_length(m) ? : len - m->offset; const char *p = &prop->val.val[m->offset]; struct marker *m_phandle; if (is_type_marker(m->type)) { emit_type = m->type; fprintf(f, " %s", delim_start[emit_type]); } else if (m->type == LABEL) fprintf(f, " %s:", m->ref); if (emit_type == TYPE_NONE || chunk_len == 0) continue; switch(emit_type) { case TYPE_UINT16: write_propval_int(f, p, chunk_len, 2); break; case TYPE_UINT32: m_phandle = prop->val.markers; for_each_marker_of_type(m_phandle, REF_PHANDLE) if (m->offset == m_phandle->offset) break; if (m_phandle) { if (m_phandle->ref[0] == '/') fprintf(f, "&{%s}", m_phandle->ref); else fprintf(f, "&%s", m_phandle->ref); if (chunk_len > 4) { fputc(' ', f); write_propval_int(f, p + 4, chunk_len - 4, 4); } } else { write_propval_int(f, p, chunk_len, 4); } break; case TYPE_UINT64: write_propval_int(f, p, chunk_len, 8); break; case TYPE_STRING: write_propval_string(f, p, chunk_len); break; default: write_propval_int(f, p, chunk_len, 1); } if (chunk_len == data_len) { size_t pos = m->offset + chunk_len; fprintf(f, pos == len ? "%s" : "%s,", delim_end[emit_type] ? : ""); emit_type = TYPE_NONE; } } fprintf(f, ";"); if (annotate) { srcstr = srcpos_string_first(prop->srcpos, annotate); if (srcstr) { fprintf(f, " /* %s */", srcstr); free(srcstr); } } fprintf(f, "\n"); } static void write_tree_source_node(FILE *f, struct node *tree, int level) { struct property *prop; struct node *child; struct label *l; char *srcstr; write_prefix(f, level); for_each_label(tree->labels, l) fprintf(f, "%s: ", l->label); if (tree->name && (*tree->name)) fprintf(f, "%s {", tree->name); else fprintf(f, "/ {"); if (annotate) { srcstr = srcpos_string_first(tree->srcpos, annotate); if (srcstr) { fprintf(f, " /* %s */", srcstr); free(srcstr); } } fprintf(f, "\n"); for_each_property(tree, prop) { write_prefix(f, level+1); for_each_label(prop->labels, l) fprintf(f, "%s: ", l->label); fprintf(f, "%s", prop->name); write_propval(f, prop); } for_each_child(tree, child) { fprintf(f, "\n"); write_tree_source_node(f, child, level+1); } write_prefix(f, level); fprintf(f, "};"); if (annotate) { srcstr = srcpos_string_last(tree->srcpos, annotate); if (srcstr) { fprintf(f, " /* %s */", srcstr); free(srcstr); } } fprintf(f, "\n"); } void dt_to_source(FILE *f, struct dt_info *dti) { struct reserve_info *re; fprintf(f, "/dts-v1/;\n\n"); for (re = dti->reservelist; re; re = re->next) { struct label *l; for_each_label(re->labels, l) fprintf(f, "%s: ", l->label); fprintf(f, "/memreserve/\t0x%016llx 0x%016llx;\n", (unsigned long long)re->address, (unsigned long long)re->size); } write_tree_source_node(f, dti->dt, 0); }
linux-master
scripts/dtc/treesource.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2011 The Chromium OS Authors. All rights reserved. */ #include <assert.h> #include <ctype.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libfdt.h> #include "util.h" /* These are the operations we support */ enum oper_type { OPER_WRITE_PROP, /* Write a property in a node */ OPER_CREATE_NODE, /* Create a new node */ }; struct display_info { enum oper_type oper; /* operation to perform */ int type; /* data type (s/i/u/x or 0 for default) */ int size; /* data size (1/2/4) */ int verbose; /* verbose output */ int auto_path; /* automatically create all path components */ }; /** * Report an error with a particular node. * * @param name Node name to report error on * @param namelen Length of node name, or -1 to use entire string * @param err Error number to report (-FDT_ERR_...) */ static void report_error(const char *name, int namelen, int err) { if (namelen == -1) namelen = strlen(name); fprintf(stderr, "Error at '%1.*s': %s\n", namelen, name, fdt_strerror(err)); } /** * Encode a series of arguments in a property value. * * @param disp Display information / options * @param arg List of arguments from command line * @param arg_count Number of arguments (may be 0) * @param valuep Returns buffer containing value * @param *value_len Returns length of value encoded */ static int encode_value(struct display_info *disp, char **arg, int arg_count, char **valuep, int *value_len) { char *value = NULL; /* holding area for value */ int value_size = 0; /* size of holding area */ char *ptr; /* pointer to current value position */ int len; /* length of this cell/string/byte */ int ival; int upto; /* the number of bytes we have written to buf */ char fmt[3]; upto = 0; if (disp->verbose) fprintf(stderr, "Decoding value:\n"); fmt[0] = '%'; fmt[1] = disp->type ? disp->type : 'd'; fmt[2] = '\0'; for (; arg_count > 0; arg++, arg_count--, upto += len) { /* assume integer unless told otherwise */ if (disp->type == 's') len = strlen(*arg) + 1; else len = disp->size == -1 ? 4 : disp->size; /* enlarge our value buffer by a suitable margin if needed */ if (upto + len > value_size) { value_size = (upto + len) + 500; value = realloc(value, value_size); if (!value) { fprintf(stderr, "Out of mmory: cannot alloc " "%d bytes\n", value_size); return -1; } } ptr = value + upto; if (disp->type == 's') { memcpy(ptr, *arg, len); if (disp->verbose) fprintf(stderr, "\tstring: '%s'\n", ptr); } else { int *iptr = (int *)ptr; sscanf(*arg, fmt, &ival); if (len == 4) *iptr = cpu_to_fdt32(ival); else *ptr = (uint8_t)ival; if (disp->verbose) { fprintf(stderr, "\t%s: %d\n", disp->size == 1 ? "byte" : disp->size == 2 ? "short" : "int", ival); } } } *value_len = upto; *valuep = value; if (disp->verbose) fprintf(stderr, "Value size %d\n", upto); return 0; } static int store_key_value(void *blob, const char *node_name, const char *property, const char *buf, int len) { int node; int err; node = fdt_path_offset(blob, node_name); if (node < 0) { report_error(node_name, -1, node); return -1; } err = fdt_setprop(blob, node, property, buf, len); if (err) { report_error(property, -1, err); return -1; } return 0; } /** * Create paths as needed for all components of a path * * Any components of the path that do not exist are created. Errors are * reported. * * @param blob FDT blob to write into * @param in_path Path to process * @return 0 if ok, -1 on error */ static int create_paths(void *blob, const char *in_path) { const char *path = in_path; const char *sep; int node, offset = 0; /* skip leading '/' */ while (*path == '/') path++; for (sep = path; *sep; path = sep + 1, offset = node) { /* equivalent to strchrnul(), but it requires _GNU_SOURCE */ sep = strchr(path, '/'); if (!sep) sep = path + strlen(path); node = fdt_subnode_offset_namelen(blob, offset, path, sep - path); if (node == -FDT_ERR_NOTFOUND) { node = fdt_add_subnode_namelen(blob, offset, path, sep - path); } if (node < 0) { report_error(path, sep - path, node); return -1; } } return 0; } /** * Create a new node in the fdt. * * This will overwrite the node_name string. Any error is reported. * * TODO: Perhaps create fdt_path_offset_namelen() so we don't need to do this. * * @param blob FDT blob to write into * @param node_name Name of node to create * @return new node offset if found, or -1 on failure */ static int create_node(void *blob, const char *node_name) { int node = 0; char *p; p = strrchr(node_name, '/'); if (!p) { report_error(node_name, -1, -FDT_ERR_BADPATH); return -1; } *p = '\0'; if (p > node_name) { node = fdt_path_offset(blob, node_name); if (node < 0) { report_error(node_name, -1, node); return -1; } } node = fdt_add_subnode(blob, node, p + 1); if (node < 0) { report_error(p + 1, -1, node); return -1; } return 0; } static int do_fdtput(struct display_info *disp, const char *filename, char **arg, int arg_count) { char *value; char *blob; int len, ret = 0; blob = utilfdt_read(filename); if (!blob) return -1; switch (disp->oper) { case OPER_WRITE_PROP: /* * Convert the arguments into a single binary value, then * store them into the property. */ assert(arg_count >= 2); if (disp->auto_path && create_paths(blob, *arg)) return -1; if (encode_value(disp, arg + 2, arg_count - 2, &value, &len) || store_key_value(blob, *arg, arg[1], value, len)) ret = -1; break; case OPER_CREATE_NODE: for (; ret >= 0 && arg_count--; arg++) { if (disp->auto_path) ret = create_paths(blob, *arg); else ret = create_node(blob, *arg); } break; } if (ret >= 0) ret = utilfdt_write(filename, blob); free(blob); return ret; } static const char *usage_msg = "fdtput - write a property value to a device tree\n" "\n" "The command line arguments are joined together into a single value.\n" "\n" "Usage:\n" " fdtput <options> <dt file> <node> <property> [<value>...]\n" " fdtput -c <options> <dt file> [<node>...]\n" "Options:\n" "\t-c\t\tCreate nodes if they don't already exist\n" "\t-p\t\tAutomatically create nodes as needed for the node path\n" "\t-t <type>\tType of data\n" "\t-v\t\tVerbose: display each value decoded from command line\n" "\t-h\t\tPrint this help\n\n" USAGE_TYPE_MSG; static void usage(const char *msg) { if (msg) fprintf(stderr, "Error: %s\n\n", msg); fprintf(stderr, "%s", usage_msg); exit(2); } int main(int argc, char *argv[]) { struct display_info disp; char *filename = NULL; memset(&disp, '\0', sizeof(disp)); disp.size = -1; disp.oper = OPER_WRITE_PROP; for (;;) { int c = getopt(argc, argv, "chpt:v"); if (c == -1) break; /* * TODO: add options to: * - delete property * - delete node (optionally recursively) * - rename node * - pack fdt before writing * - set amount of free space when writing * - expand fdt if value doesn't fit */ switch (c) { case 'c': disp.oper = OPER_CREATE_NODE; break; case 'h': case '?': usage(NULL); case 'p': disp.auto_path = 1; break; case 't': if (utilfdt_decode_type(optarg, &disp.type, &disp.size)) usage("Invalid type string"); break; case 'v': disp.verbose = 1; break; } } if (optind < argc) filename = argv[optind++]; if (!filename) usage("Missing filename"); argv += optind; argc -= optind; if (disp.oper == OPER_WRITE_PROP) { if (argc < 1) usage("Missing node"); if (argc < 2) usage("Missing property"); } if (do_fdtput(&disp, filename, argv, argc)) return 1; return 0; }
linux-master
scripts/dtc/fdtput.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include "dtc.h" void data_free(struct data d) { struct marker *m, *nm; m = d.markers; while (m) { nm = m->next; free(m->ref); free(m); m = nm; } if (d.val) free(d.val); } struct data data_grow_for(struct data d, unsigned int xlen) { struct data nd; unsigned int newsize; if (xlen == 0) return d; nd = d; newsize = xlen; while ((d.len + xlen) > newsize) newsize *= 2; nd.val = xrealloc(d.val, newsize); return nd; } struct data data_copy_mem(const char *mem, int len) { struct data d; d = data_grow_for(empty_data, len); d.len = len; memcpy(d.val, mem, len); return d; } struct data data_copy_escape_string(const char *s, int len) { int i = 0; struct data d; char *q; d = data_add_marker(empty_data, TYPE_STRING, NULL); d = data_grow_for(d, len + 1); q = d.val; while (i < len) { char c = s[i++]; if (c == '\\') c = get_escape_char(s, &i); q[d.len++] = c; } q[d.len++] = '\0'; return d; } struct data data_copy_file(FILE *f, size_t maxlen) { struct data d = empty_data; d = data_add_marker(d, TYPE_NONE, NULL); while (!feof(f) && (d.len < maxlen)) { size_t chunksize, ret; if (maxlen == (size_t)-1) chunksize = 4096; else chunksize = maxlen - d.len; d = data_grow_for(d, chunksize); ret = fread(d.val + d.len, 1, chunksize, f); if (ferror(f)) die("Error reading file into data: %s", strerror(errno)); if (d.len + ret < d.len) die("Overflow reading file into data\n"); d.len += ret; } return d; } struct data data_append_data(struct data d, const void *p, int len) { d = data_grow_for(d, len); memcpy(d.val + d.len, p, len); d.len += len; return d; } struct data data_insert_at_marker(struct data d, struct marker *m, const void *p, int len) { d = data_grow_for(d, len); memmove(d.val + m->offset + len, d.val + m->offset, d.len - m->offset); memcpy(d.val + m->offset, p, len); d.len += len; /* Adjust all markers after the one we're inserting at */ m = m->next; for_each_marker(m) m->offset += len; return d; } static struct data data_append_markers(struct data d, struct marker *m) { struct marker **mp = &d.markers; /* Find the end of the markerlist */ while (*mp) mp = &((*mp)->next); *mp = m; return d; } struct data data_merge(struct data d1, struct data d2) { struct data d; struct marker *m2 = d2.markers; d = data_append_markers(data_append_data(d1, d2.val, d2.len), m2); /* Adjust for the length of d1 */ for_each_marker(m2) m2->offset += d1.len; d2.markers = NULL; /* So data_free() doesn't clobber them */ data_free(d2); return d; } struct data data_append_integer(struct data d, uint64_t value, int bits) { uint8_t value_8; fdt16_t value_16; fdt32_t value_32; fdt64_t value_64; switch (bits) { case 8: value_8 = value; return data_append_data(d, &value_8, 1); case 16: value_16 = cpu_to_fdt16(value); return data_append_data(d, &value_16, 2); case 32: value_32 = cpu_to_fdt32(value); return data_append_data(d, &value_32, 4); case 64: value_64 = cpu_to_fdt64(value); return data_append_data(d, &value_64, 8); default: die("Invalid literal size (%d)\n", bits); } } struct data data_append_re(struct data d, uint64_t address, uint64_t size) { struct fdt_reserve_entry re; re.address = cpu_to_fdt64(address); re.size = cpu_to_fdt64(size); return data_append_data(d, &re, sizeof(re)); } struct data data_append_cell(struct data d, cell_t word) { return data_append_integer(d, word, sizeof(word) * 8); } struct data data_append_addr(struct data d, uint64_t addr) { return data_append_integer(d, addr, sizeof(addr) * 8); } struct data data_append_byte(struct data d, uint8_t byte) { return data_append_data(d, &byte, 1); } struct data data_append_zeroes(struct data d, int len) { d = data_grow_for(d, len); memset(d.val + d.len, 0, len); d.len += len; return d; } struct data data_append_align(struct data d, int align) { int newlen = ALIGN(d.len, align); return data_append_zeroes(d, newlen - d.len); } struct data data_add_marker(struct data d, enum markertype type, char *ref) { struct marker *m; m = xmalloc(sizeof(*m)); m->offset = d.len; m->type = type; m->ref = ref; m->next = NULL; return data_append_markers(d, m); } bool data_is_one_string(struct data d) { int i; int len = d.len; if (len == 0) return false; for (i = 0; i < len-1; i++) if (d.val[i] == '\0') return false; if (d.val[len-1] != '\0') return false; return true; }
linux-master
scripts/dtc/data.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2005. */ #include "dtc.h" #include <dirent.h> #include <sys/stat.h> static struct node *read_fstree(const char *dirname) { DIR *d; struct dirent *de; struct stat st; struct node *tree; d = opendir(dirname); if (!d) die("Couldn't opendir() \"%s\": %s\n", dirname, strerror(errno)); tree = build_node(NULL, NULL, NULL); while ((de = readdir(d)) != NULL) { char *tmpname; if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; tmpname = join_path(dirname, de->d_name); if (stat(tmpname, &st) < 0) die("stat(%s): %s\n", tmpname, strerror(errno)); if (S_ISREG(st.st_mode)) { struct property *prop; FILE *pfile; pfile = fopen(tmpname, "rb"); if (! pfile) { fprintf(stderr, "WARNING: Cannot open %s: %s\n", tmpname, strerror(errno)); } else { prop = build_property(xstrdup(de->d_name), data_copy_file(pfile, st.st_size), NULL); add_property(tree, prop); fclose(pfile); } } else if (S_ISDIR(st.st_mode)) { struct node *newchild; newchild = read_fstree(tmpname); newchild = name_node(newchild, xstrdup(de->d_name)); add_child(tree, newchild); } free(tmpname); } closedir(d); return tree; } struct dt_info *dt_from_fs(const char *dirname) { struct node *tree; tree = read_fstree(dirname); tree = name_node(tree, ""); return build_dt_info(DTSF_V1, NULL, tree, guess_boot_cpuid(tree)); }
linux-master
scripts/dtc/fstree.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright David Gibson <[email protected]>, IBM Corporation. 2007. */ #include "dtc.h" #include "srcpos.h" #ifdef TRACE_CHECKS #define TRACE(c, ...) \ do { \ fprintf(stderr, "=== %s: ", (c)->name); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ } while (0) #else #define TRACE(c, fmt, ...) do { } while (0) #endif enum checkstatus { UNCHECKED = 0, PREREQ, PASSED, FAILED, }; struct check; typedef void (*check_fn)(struct check *c, struct dt_info *dti, struct node *node); struct check { const char *name; check_fn fn; void *data; bool warn, error; enum checkstatus status; bool inprogress; int num_prereqs; struct check **prereq; }; #define CHECK_ENTRY(nm_, fn_, d_, w_, e_, ...) \ static struct check *nm_##_prereqs[] = { __VA_ARGS__ }; \ static struct check nm_ = { \ .name = #nm_, \ .fn = (fn_), \ .data = (d_), \ .warn = (w_), \ .error = (e_), \ .status = UNCHECKED, \ .num_prereqs = ARRAY_SIZE(nm_##_prereqs), \ .prereq = nm_##_prereqs, \ }; #define WARNING(nm_, fn_, d_, ...) \ CHECK_ENTRY(nm_, fn_, d_, true, false, __VA_ARGS__) #define ERROR(nm_, fn_, d_, ...) \ CHECK_ENTRY(nm_, fn_, d_, false, true, __VA_ARGS__) #define CHECK(nm_, fn_, d_, ...) \ CHECK_ENTRY(nm_, fn_, d_, false, false, __VA_ARGS__) static inline void PRINTF(5, 6) check_msg(struct check *c, struct dt_info *dti, struct node *node, struct property *prop, const char *fmt, ...) { va_list ap; char *str = NULL; struct srcpos *pos = NULL; char *file_str; if (!(c->warn && (quiet < 1)) && !(c->error && (quiet < 2))) return; if (prop && prop->srcpos) pos = prop->srcpos; else if (node && node->srcpos) pos = node->srcpos; if (pos) { file_str = srcpos_string(pos); xasprintf(&str, "%s", file_str); free(file_str); } else if (streq(dti->outname, "-")) { xasprintf(&str, "<stdout>"); } else { xasprintf(&str, "%s", dti->outname); } xasprintf_append(&str, ": %s (%s): ", (c->error) ? "ERROR" : "Warning", c->name); if (node) { if (prop) xasprintf_append(&str, "%s:%s: ", node->fullpath, prop->name); else xasprintf_append(&str, "%s: ", node->fullpath); } va_start(ap, fmt); xavsprintf_append(&str, fmt, ap); va_end(ap); xasprintf_append(&str, "\n"); if (!prop && pos) { pos = node->srcpos; while (pos->next) { pos = pos->next; file_str = srcpos_string(pos); xasprintf_append(&str, " also defined at %s\n", file_str); free(file_str); } } fputs(str, stderr); } #define FAIL(c, dti, node, ...) \ do { \ TRACE((c), "\t\tFAILED at %s:%d", __FILE__, __LINE__); \ (c)->status = FAILED; \ check_msg((c), dti, node, NULL, __VA_ARGS__); \ } while (0) #define FAIL_PROP(c, dti, node, prop, ...) \ do { \ TRACE((c), "\t\tFAILED at %s:%d", __FILE__, __LINE__); \ (c)->status = FAILED; \ check_msg((c), dti, node, prop, __VA_ARGS__); \ } while (0) static void check_nodes_props(struct check *c, struct dt_info *dti, struct node *node) { struct node *child; TRACE(c, "%s", node->fullpath); if (c->fn) c->fn(c, dti, node); for_each_child(node, child) check_nodes_props(c, dti, child); } static bool is_multiple_of(int multiple, int divisor) { if (divisor == 0) return multiple == 0; else return (multiple % divisor) == 0; } static bool run_check(struct check *c, struct dt_info *dti) { struct node *dt = dti->dt; bool error = false; int i; assert(!c->inprogress); if (c->status != UNCHECKED) goto out; c->inprogress = true; for (i = 0; i < c->num_prereqs; i++) { struct check *prq = c->prereq[i]; error = error || run_check(prq, dti); if (prq->status != PASSED) { c->status = PREREQ; check_msg(c, dti, NULL, NULL, "Failed prerequisite '%s'", c->prereq[i]->name); } } if (c->status != UNCHECKED) goto out; check_nodes_props(c, dti, dt); if (c->status == UNCHECKED) c->status = PASSED; TRACE(c, "\tCompleted, status %d", c->status); out: c->inprogress = false; if ((c->status != PASSED) && (c->error)) error = true; return error; } /* * Utility check functions */ /* A check which always fails, for testing purposes only */ static inline void check_always_fail(struct check *c, struct dt_info *dti, struct node *node) { FAIL(c, dti, node, "always_fail check"); } CHECK(always_fail, check_always_fail, NULL); static void check_is_string(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; char *propname = c->data; prop = get_property(node, propname); if (!prop) return; /* Not present, assumed ok */ if (!data_is_one_string(prop->val)) FAIL_PROP(c, dti, node, prop, "property is not a string"); } #define WARNING_IF_NOT_STRING(nm, propname) \ WARNING(nm, check_is_string, (propname)) #define ERROR_IF_NOT_STRING(nm, propname) \ ERROR(nm, check_is_string, (propname)) static void check_is_string_list(struct check *c, struct dt_info *dti, struct node *node) { int rem, l; struct property *prop; char *propname = c->data; char *str; prop = get_property(node, propname); if (!prop) return; /* Not present, assumed ok */ str = prop->val.val; rem = prop->val.len; while (rem > 0) { l = strnlen(str, rem); if (l == rem) { FAIL_PROP(c, dti, node, prop, "property is not a string list"); break; } rem -= l + 1; str += l + 1; } } #define WARNING_IF_NOT_STRING_LIST(nm, propname) \ WARNING(nm, check_is_string_list, (propname)) #define ERROR_IF_NOT_STRING_LIST(nm, propname) \ ERROR(nm, check_is_string_list, (propname)) static void check_is_cell(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; char *propname = c->data; prop = get_property(node, propname); if (!prop) return; /* Not present, assumed ok */ if (prop->val.len != sizeof(cell_t)) FAIL_PROP(c, dti, node, prop, "property is not a single cell"); } #define WARNING_IF_NOT_CELL(nm, propname) \ WARNING(nm, check_is_cell, (propname)) #define ERROR_IF_NOT_CELL(nm, propname) \ ERROR(nm, check_is_cell, (propname)) /* * Structural check functions */ static void check_duplicate_node_names(struct check *c, struct dt_info *dti, struct node *node) { struct node *child, *child2; for_each_child(node, child) for (child2 = child->next_sibling; child2; child2 = child2->next_sibling) if (streq(child->name, child2->name)) FAIL(c, dti, child2, "Duplicate node name"); } ERROR(duplicate_node_names, check_duplicate_node_names, NULL); static void check_duplicate_property_names(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop, *prop2; for_each_property(node, prop) { for (prop2 = prop->next; prop2; prop2 = prop2->next) { if (prop2->deleted) continue; if (streq(prop->name, prop2->name)) FAIL_PROP(c, dti, node, prop, "Duplicate property name"); } } } ERROR(duplicate_property_names, check_duplicate_property_names, NULL); #define LOWERCASE "abcdefghijklmnopqrstuvwxyz" #define UPPERCASE "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define DIGITS "0123456789" #define NODECHARS LOWERCASE UPPERCASE DIGITS ",._+-@" #define PROPCHARS LOWERCASE UPPERCASE DIGITS ",._+*#?-" #define PROPNODECHARSSTRICT LOWERCASE UPPERCASE DIGITS ",-" static void check_node_name_chars(struct check *c, struct dt_info *dti, struct node *node) { size_t n = strspn(node->name, c->data); if (n < strlen(node->name)) FAIL(c, dti, node, "Bad character '%c' in node name", node->name[n]); } ERROR(node_name_chars, check_node_name_chars, NODECHARS); static void check_node_name_chars_strict(struct check *c, struct dt_info *dti, struct node *node) { int n = strspn(node->name, c->data); if (n < node->basenamelen) FAIL(c, dti, node, "Character '%c' not recommended in node name", node->name[n]); } CHECK(node_name_chars_strict, check_node_name_chars_strict, PROPNODECHARSSTRICT); static void check_node_name_format(struct check *c, struct dt_info *dti, struct node *node) { if (strchr(get_unitname(node), '@')) FAIL(c, dti, node, "multiple '@' characters in node name"); } ERROR(node_name_format, check_node_name_format, NULL, &node_name_chars); static void check_node_name_vs_property_name(struct check *c, struct dt_info *dti, struct node *node) { if (!node->parent) return; if (get_property(node->parent, node->name)) { FAIL(c, dti, node, "node name and property name conflict"); } } WARNING(node_name_vs_property_name, check_node_name_vs_property_name, NULL, &node_name_chars); static void check_unit_address_vs_reg(struct check *c, struct dt_info *dti, struct node *node) { const char *unitname = get_unitname(node); struct property *prop = get_property(node, "reg"); if (get_subnode(node, "__overlay__")) { /* HACK: Overlay fragments are a special case */ return; } if (!prop) { prop = get_property(node, "ranges"); if (prop && !prop->val.len) prop = NULL; } if (prop) { if (!unitname[0]) FAIL(c, dti, node, "node has a reg or ranges property, but no unit name"); } else { if (unitname[0]) FAIL(c, dti, node, "node has a unit name, but no reg or ranges property"); } } WARNING(unit_address_vs_reg, check_unit_address_vs_reg, NULL); static void check_property_name_chars(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; for_each_property(node, prop) { size_t n = strspn(prop->name, c->data); if (n < strlen(prop->name)) FAIL_PROP(c, dti, node, prop, "Bad character '%c' in property name", prop->name[n]); } } ERROR(property_name_chars, check_property_name_chars, PROPCHARS); static void check_property_name_chars_strict(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; for_each_property(node, prop) { const char *name = prop->name; size_t n = strspn(name, c->data); if (n == strlen(prop->name)) continue; /* Certain names are whitelisted */ if (streq(name, "device_type")) continue; /* * # is only allowed at the beginning of property names not counting * the vendor prefix. */ if (name[n] == '#' && ((n == 0) || (name[n-1] == ','))) { name += n + 1; n = strspn(name, c->data); } if (n < strlen(name)) FAIL_PROP(c, dti, node, prop, "Character '%c' not recommended in property name", name[n]); } } CHECK(property_name_chars_strict, check_property_name_chars_strict, PROPNODECHARSSTRICT); #define DESCLABEL_FMT "%s%s%s%s%s" #define DESCLABEL_ARGS(node,prop,mark) \ ((mark) ? "value of " : ""), \ ((prop) ? "'" : ""), \ ((prop) ? (prop)->name : ""), \ ((prop) ? "' in " : ""), (node)->fullpath static void check_duplicate_label(struct check *c, struct dt_info *dti, const char *label, struct node *node, struct property *prop, struct marker *mark) { struct node *dt = dti->dt; struct node *othernode = NULL; struct property *otherprop = NULL; struct marker *othermark = NULL; othernode = get_node_by_label(dt, label); if (!othernode) otherprop = get_property_by_label(dt, label, &othernode); if (!othernode) othermark = get_marker_label(dt, label, &othernode, &otherprop); if (!othernode) return; if ((othernode != node) || (otherprop != prop) || (othermark != mark)) FAIL(c, dti, node, "Duplicate label '%s' on " DESCLABEL_FMT " and " DESCLABEL_FMT, label, DESCLABEL_ARGS(node, prop, mark), DESCLABEL_ARGS(othernode, otherprop, othermark)); } static void check_duplicate_label_node(struct check *c, struct dt_info *dti, struct node *node) { struct label *l; struct property *prop; for_each_label(node->labels, l) check_duplicate_label(c, dti, l->label, node, NULL, NULL); for_each_property(node, prop) { struct marker *m = prop->val.markers; for_each_label(prop->labels, l) check_duplicate_label(c, dti, l->label, node, prop, NULL); for_each_marker_of_type(m, LABEL) check_duplicate_label(c, dti, m->ref, node, prop, m); } } ERROR(duplicate_label, check_duplicate_label_node, NULL); static cell_t check_phandle_prop(struct check *c, struct dt_info *dti, struct node *node, const char *propname) { struct node *root = dti->dt; struct property *prop; struct marker *m; cell_t phandle; prop = get_property(node, propname); if (!prop) return 0; if (prop->val.len != sizeof(cell_t)) { FAIL_PROP(c, dti, node, prop, "bad length (%d) %s property", prop->val.len, prop->name); return 0; } m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { assert(m->offset == 0); if (node != get_node_by_ref(root, m->ref)) /* "Set this node's phandle equal to some * other node's phandle". That's nonsensical * by construction. */ { FAIL(c, dti, node, "%s is a reference to another node", prop->name); } /* But setting this node's phandle equal to its own * phandle is allowed - that means allocate a unique * phandle for this node, even if it's not otherwise * referenced. The value will be filled in later, so * we treat it as having no phandle data for now. */ return 0; } phandle = propval_cell(prop); if (!phandle_is_valid(phandle)) { FAIL_PROP(c, dti, node, prop, "bad value (0x%x) in %s property", phandle, prop->name); return 0; } return phandle; } static void check_explicit_phandles(struct check *c, struct dt_info *dti, struct node *node) { struct node *root = dti->dt; struct node *other; cell_t phandle, linux_phandle; /* Nothing should have assigned phandles yet */ assert(!node->phandle); phandle = check_phandle_prop(c, dti, node, "phandle"); linux_phandle = check_phandle_prop(c, dti, node, "linux,phandle"); if (!phandle && !linux_phandle) /* No valid phandles; nothing further to check */ return; if (linux_phandle && phandle && (phandle != linux_phandle)) FAIL(c, dti, node, "mismatching 'phandle' and 'linux,phandle'" " properties"); if (linux_phandle && !phandle) phandle = linux_phandle; other = get_node_by_phandle(root, phandle); if (other && (other != node)) { FAIL(c, dti, node, "duplicated phandle 0x%x (seen before at %s)", phandle, other->fullpath); return; } node->phandle = phandle; } ERROR(explicit_phandles, check_explicit_phandles, NULL); static void check_name_properties(struct check *c, struct dt_info *dti, struct node *node) { struct property **pp, *prop = NULL; for (pp = &node->proplist; *pp; pp = &((*pp)->next)) if (streq((*pp)->name, "name")) { prop = *pp; break; } if (!prop) return; /* No name property, that's fine */ if ((prop->val.len != node->basenamelen + 1U) || (memcmp(prop->val.val, node->name, node->basenamelen) != 0)) { FAIL(c, dti, node, "\"name\" property is incorrect (\"%s\" instead" " of base node name)", prop->val.val); } else { /* The name property is correct, and therefore redundant. * Delete it */ *pp = prop->next; free(prop->name); data_free(prop->val); free(prop); } } ERROR_IF_NOT_STRING(name_is_string, "name"); ERROR(name_properties, check_name_properties, NULL, &name_is_string); /* * Reference fixup functions */ static void fixup_phandle_references(struct check *c, struct dt_info *dti, struct node *node) { struct node *dt = dti->dt; struct property *prop; for_each_property(node, prop) { struct marker *m = prop->val.markers; struct node *refnode; cell_t phandle; for_each_marker_of_type(m, REF_PHANDLE) { assert(m->offset + sizeof(cell_t) <= prop->val.len); refnode = get_node_by_ref(dt, m->ref); if (! refnode) { if (!(dti->dtsflags & DTSF_PLUGIN)) FAIL(c, dti, node, "Reference to non-existent node or " "label \"%s\"\n", m->ref); else /* mark the entry as unresolved */ *((fdt32_t *)(prop->val.val + m->offset)) = cpu_to_fdt32(0xffffffff); continue; } phandle = get_node_phandle(dt, refnode); *((fdt32_t *)(prop->val.val + m->offset)) = cpu_to_fdt32(phandle); reference_node(refnode); } } } ERROR(phandle_references, fixup_phandle_references, NULL, &duplicate_node_names, &explicit_phandles); static void fixup_path_references(struct check *c, struct dt_info *dti, struct node *node) { struct node *dt = dti->dt; struct property *prop; for_each_property(node, prop) { struct marker *m = prop->val.markers; struct node *refnode; char *path; for_each_marker_of_type(m, REF_PATH) { assert(m->offset <= prop->val.len); refnode = get_node_by_ref(dt, m->ref); if (!refnode) { FAIL(c, dti, node, "Reference to non-existent node or label \"%s\"\n", m->ref); continue; } path = refnode->fullpath; prop->val = data_insert_at_marker(prop->val, m, path, strlen(path) + 1); reference_node(refnode); } } } ERROR(path_references, fixup_path_references, NULL, &duplicate_node_names); static void fixup_omit_unused_nodes(struct check *c, struct dt_info *dti, struct node *node) { if (generate_symbols && node->labels) return; if (node->omit_if_unused && !node->is_referenced) delete_node(node); } ERROR(omit_unused_nodes, fixup_omit_unused_nodes, NULL, &phandle_references, &path_references); /* * Semantic checks */ WARNING_IF_NOT_CELL(address_cells_is_cell, "#address-cells"); WARNING_IF_NOT_CELL(size_cells_is_cell, "#size-cells"); WARNING_IF_NOT_STRING(device_type_is_string, "device_type"); WARNING_IF_NOT_STRING(model_is_string, "model"); WARNING_IF_NOT_STRING(status_is_string, "status"); WARNING_IF_NOT_STRING(label_is_string, "label"); WARNING_IF_NOT_STRING_LIST(compatible_is_string_list, "compatible"); static void check_names_is_string_list(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; for_each_property(node, prop) { if (!strends(prop->name, "-names")) continue; c->data = prop->name; check_is_string_list(c, dti, node); } } WARNING(names_is_string_list, check_names_is_string_list, NULL); static void check_alias_paths(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; if (!streq(node->name, "aliases")) return; for_each_property(node, prop) { if (streq(prop->name, "phandle") || streq(prop->name, "linux,phandle")) { continue; } if (!prop->val.val || !get_node_by_path(dti->dt, prop->val.val)) { FAIL_PROP(c, dti, node, prop, "aliases property is not a valid node (%s)", prop->val.val); continue; } if (strspn(prop->name, LOWERCASE DIGITS "-") != strlen(prop->name)) FAIL(c, dti, node, "aliases property name must include only lowercase and '-'"); } } WARNING(alias_paths, check_alias_paths, NULL); static void fixup_addr_size_cells(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; node->addr_cells = -1; node->size_cells = -1; prop = get_property(node, "#address-cells"); if (prop) node->addr_cells = propval_cell(prop); prop = get_property(node, "#size-cells"); if (prop) node->size_cells = propval_cell(prop); } WARNING(addr_size_cells, fixup_addr_size_cells, NULL, &address_cells_is_cell, &size_cells_is_cell); #define node_addr_cells(n) \ (((n)->addr_cells == -1) ? 2 : (n)->addr_cells) #define node_size_cells(n) \ (((n)->size_cells == -1) ? 1 : (n)->size_cells) static void check_reg_format(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; int addr_cells, size_cells, entrylen; prop = get_property(node, "reg"); if (!prop) return; /* No "reg", that's fine */ if (!node->parent) { FAIL(c, dti, node, "Root node has a \"reg\" property"); return; } if (prop->val.len == 0) FAIL_PROP(c, dti, node, prop, "property is empty"); addr_cells = node_addr_cells(node->parent); size_cells = node_size_cells(node->parent); entrylen = (addr_cells + size_cells) * sizeof(cell_t); if (!is_multiple_of(prop->val.len, entrylen)) FAIL_PROP(c, dti, node, prop, "property has invalid length (%d bytes) " "(#address-cells == %d, #size-cells == %d)", prop->val.len, addr_cells, size_cells); } WARNING(reg_format, check_reg_format, NULL, &addr_size_cells); static void check_ranges_format(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; int c_addr_cells, p_addr_cells, c_size_cells, p_size_cells, entrylen; const char *ranges = c->data; prop = get_property(node, ranges); if (!prop) return; if (!node->parent) { FAIL_PROP(c, dti, node, prop, "Root node has a \"%s\" property", ranges); return; } p_addr_cells = node_addr_cells(node->parent); p_size_cells = node_size_cells(node->parent); c_addr_cells = node_addr_cells(node); c_size_cells = node_size_cells(node); entrylen = (p_addr_cells + c_addr_cells + c_size_cells) * sizeof(cell_t); if (prop->val.len == 0) { if (p_addr_cells != c_addr_cells) FAIL_PROP(c, dti, node, prop, "empty \"%s\" property but its " "#address-cells (%d) differs from %s (%d)", ranges, c_addr_cells, node->parent->fullpath, p_addr_cells); if (p_size_cells != c_size_cells) FAIL_PROP(c, dti, node, prop, "empty \"%s\" property but its " "#size-cells (%d) differs from %s (%d)", ranges, c_size_cells, node->parent->fullpath, p_size_cells); } else if (!is_multiple_of(prop->val.len, entrylen)) { FAIL_PROP(c, dti, node, prop, "\"%s\" property has invalid length (%d bytes) " "(parent #address-cells == %d, child #address-cells == %d, " "#size-cells == %d)", ranges, prop->val.len, p_addr_cells, c_addr_cells, c_size_cells); } } WARNING(ranges_format, check_ranges_format, "ranges", &addr_size_cells); WARNING(dma_ranges_format, check_ranges_format, "dma-ranges", &addr_size_cells); static const struct bus_type pci_bus = { .name = "PCI", }; static void check_pci_bridge(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; cell_t *cells; prop = get_property(node, "device_type"); if (!prop || !streq(prop->val.val, "pci")) return; node->bus = &pci_bus; if (!strprefixeq(node->name, node->basenamelen, "pci") && !strprefixeq(node->name, node->basenamelen, "pcie")) FAIL(c, dti, node, "node name is not \"pci\" or \"pcie\""); prop = get_property(node, "ranges"); if (!prop) FAIL(c, dti, node, "missing ranges for PCI bridge (or not a bridge)"); if (node_addr_cells(node) != 3) FAIL(c, dti, node, "incorrect #address-cells for PCI bridge"); if (node_size_cells(node) != 2) FAIL(c, dti, node, "incorrect #size-cells for PCI bridge"); prop = get_property(node, "bus-range"); if (!prop) return; if (prop->val.len != (sizeof(cell_t) * 2)) { FAIL_PROP(c, dti, node, prop, "value must be 2 cells"); return; } cells = (cell_t *)prop->val.val; if (fdt32_to_cpu(cells[0]) > fdt32_to_cpu(cells[1])) FAIL_PROP(c, dti, node, prop, "1st cell must be less than or equal to 2nd cell"); if (fdt32_to_cpu(cells[1]) > 0xff) FAIL_PROP(c, dti, node, prop, "maximum bus number must be less than 256"); } WARNING(pci_bridge, check_pci_bridge, NULL, &device_type_is_string, &addr_size_cells); static void check_pci_device_bus_num(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; unsigned int bus_num, min_bus, max_bus; cell_t *cells; if (!node->parent || (node->parent->bus != &pci_bus)) return; prop = get_property(node, "reg"); if (!prop) return; cells = (cell_t *)prop->val.val; bus_num = (fdt32_to_cpu(cells[0]) & 0x00ff0000) >> 16; prop = get_property(node->parent, "bus-range"); if (!prop) { min_bus = max_bus = 0; } else { cells = (cell_t *)prop->val.val; min_bus = fdt32_to_cpu(cells[0]); max_bus = fdt32_to_cpu(cells[1]); } if ((bus_num < min_bus) || (bus_num > max_bus)) FAIL_PROP(c, dti, node, prop, "PCI bus number %d out of range, expected (%d - %d)", bus_num, min_bus, max_bus); } WARNING(pci_device_bus_num, check_pci_device_bus_num, NULL, &reg_format, &pci_bridge); static void check_pci_device_reg(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; const char *unitname = get_unitname(node); char unit_addr[5]; unsigned int dev, func, reg; cell_t *cells; if (!node->parent || (node->parent->bus != &pci_bus)) return; prop = get_property(node, "reg"); if (!prop) return; cells = (cell_t *)prop->val.val; if (cells[1] || cells[2]) FAIL_PROP(c, dti, node, prop, "PCI reg config space address cells 2 and 3 must be 0"); reg = fdt32_to_cpu(cells[0]); dev = (reg & 0xf800) >> 11; func = (reg & 0x700) >> 8; if (reg & 0xff000000) FAIL_PROP(c, dti, node, prop, "PCI reg address is not configuration space"); if (reg & 0x000000ff) FAIL_PROP(c, dti, node, prop, "PCI reg config space address register number must be 0"); if (func == 0) { snprintf(unit_addr, sizeof(unit_addr), "%x", dev); if (streq(unitname, unit_addr)) return; } snprintf(unit_addr, sizeof(unit_addr), "%x,%x", dev, func); if (streq(unitname, unit_addr)) return; FAIL(c, dti, node, "PCI unit address format error, expected \"%s\"", unit_addr); } WARNING(pci_device_reg, check_pci_device_reg, NULL, &reg_format, &pci_bridge); static const struct bus_type simple_bus = { .name = "simple-bus", }; static bool node_is_compatible(struct node *node, const char *compat) { struct property *prop; const char *str, *end; prop = get_property(node, "compatible"); if (!prop) return false; for (str = prop->val.val, end = str + prop->val.len; str < end; str += strnlen(str, end - str) + 1) { if (streq(str, compat)) return true; } return false; } static void check_simple_bus_bridge(struct check *c, struct dt_info *dti, struct node *node) { if (node_is_compatible(node, "simple-bus")) node->bus = &simple_bus; } WARNING(simple_bus_bridge, check_simple_bus_bridge, NULL, &addr_size_cells, &compatible_is_string_list); static void check_simple_bus_reg(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; const char *unitname = get_unitname(node); char unit_addr[17]; unsigned int size; uint64_t reg = 0; cell_t *cells = NULL; if (!node->parent || (node->parent->bus != &simple_bus)) return; prop = get_property(node, "reg"); if (prop) cells = (cell_t *)prop->val.val; else { prop = get_property(node, "ranges"); if (prop && prop->val.len) /* skip of child address */ cells = ((cell_t *)prop->val.val) + node_addr_cells(node); } if (!cells) { if (node->parent->parent && !(node->bus == &simple_bus)) FAIL(c, dti, node, "missing or empty reg/ranges property"); return; } size = node_addr_cells(node->parent); while (size--) reg = (reg << 32) | fdt32_to_cpu(*(cells++)); snprintf(unit_addr, sizeof(unit_addr), "%"PRIx64, reg); if (!streq(unitname, unit_addr)) FAIL(c, dti, node, "simple-bus unit address format error, expected \"%s\"", unit_addr); } WARNING(simple_bus_reg, check_simple_bus_reg, NULL, &reg_format, &simple_bus_bridge); static const struct bus_type i2c_bus = { .name = "i2c-bus", }; static void check_i2c_bus_bridge(struct check *c, struct dt_info *dti, struct node *node) { if (strprefixeq(node->name, node->basenamelen, "i2c-bus") || strprefixeq(node->name, node->basenamelen, "i2c-arb")) { node->bus = &i2c_bus; } else if (strprefixeq(node->name, node->basenamelen, "i2c")) { struct node *child; for_each_child(node, child) { if (strprefixeq(child->name, node->basenamelen, "i2c-bus")) return; } node->bus = &i2c_bus; } else return; if (!node->children) return; if (node_addr_cells(node) != 1) FAIL(c, dti, node, "incorrect #address-cells for I2C bus"); if (node_size_cells(node) != 0) FAIL(c, dti, node, "incorrect #size-cells for I2C bus"); } WARNING(i2c_bus_bridge, check_i2c_bus_bridge, NULL, &addr_size_cells); #define I2C_OWN_SLAVE_ADDRESS (1U << 30) #define I2C_TEN_BIT_ADDRESS (1U << 31) static void check_i2c_bus_reg(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; const char *unitname = get_unitname(node); char unit_addr[17]; uint32_t reg = 0; int len; cell_t *cells = NULL; if (!node->parent || (node->parent->bus != &i2c_bus)) return; prop = get_property(node, "reg"); if (prop) cells = (cell_t *)prop->val.val; if (!cells) { FAIL(c, dti, node, "missing or empty reg property"); return; } reg = fdt32_to_cpu(*cells); /* Ignore I2C_OWN_SLAVE_ADDRESS */ reg &= ~I2C_OWN_SLAVE_ADDRESS; snprintf(unit_addr, sizeof(unit_addr), "%x", reg); if (!streq(unitname, unit_addr)) FAIL(c, dti, node, "I2C bus unit address format error, expected \"%s\"", unit_addr); for (len = prop->val.len; len > 0; len -= 4) { reg = fdt32_to_cpu(*(cells++)); /* Ignore I2C_OWN_SLAVE_ADDRESS */ reg &= ~I2C_OWN_SLAVE_ADDRESS; if ((reg & I2C_TEN_BIT_ADDRESS) && ((reg & ~I2C_TEN_BIT_ADDRESS) > 0x3ff)) FAIL_PROP(c, dti, node, prop, "I2C address must be less than 10-bits, got \"0x%x\"", reg); else if (reg > 0x7f) FAIL_PROP(c, dti, node, prop, "I2C address must be less than 7-bits, got \"0x%x\". Set I2C_TEN_BIT_ADDRESS for 10 bit addresses or fix the property", reg); } } WARNING(i2c_bus_reg, check_i2c_bus_reg, NULL, &reg_format, &i2c_bus_bridge); static const struct bus_type spi_bus = { .name = "spi-bus", }; static void check_spi_bus_bridge(struct check *c, struct dt_info *dti, struct node *node) { int spi_addr_cells = 1; if (strprefixeq(node->name, node->basenamelen, "spi")) { node->bus = &spi_bus; } else { /* Try to detect SPI buses which don't have proper node name */ struct node *child; if (node_addr_cells(node) != 1 || node_size_cells(node) != 0) return; for_each_child(node, child) { struct property *prop; for_each_property(child, prop) { if (strprefixeq(prop->name, 4, "spi-")) { node->bus = &spi_bus; break; } } if (node->bus == &spi_bus) break; } if (node->bus == &spi_bus && get_property(node, "reg")) FAIL(c, dti, node, "node name for SPI buses should be 'spi'"); } if (node->bus != &spi_bus || !node->children) return; if (get_property(node, "spi-slave")) spi_addr_cells = 0; if (node_addr_cells(node) != spi_addr_cells) FAIL(c, dti, node, "incorrect #address-cells for SPI bus"); if (node_size_cells(node) != 0) FAIL(c, dti, node, "incorrect #size-cells for SPI bus"); } WARNING(spi_bus_bridge, check_spi_bus_bridge, NULL, &addr_size_cells); static void check_spi_bus_reg(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; const char *unitname = get_unitname(node); char unit_addr[9]; uint32_t reg = 0; cell_t *cells = NULL; if (!node->parent || (node->parent->bus != &spi_bus)) return; if (get_property(node->parent, "spi-slave")) return; prop = get_property(node, "reg"); if (prop) cells = (cell_t *)prop->val.val; if (!cells) { FAIL(c, dti, node, "missing or empty reg property"); return; } reg = fdt32_to_cpu(*cells); snprintf(unit_addr, sizeof(unit_addr), "%x", reg); if (!streq(unitname, unit_addr)) FAIL(c, dti, node, "SPI bus unit address format error, expected \"%s\"", unit_addr); } WARNING(spi_bus_reg, check_spi_bus_reg, NULL, &reg_format, &spi_bus_bridge); static void check_unit_address_format(struct check *c, struct dt_info *dti, struct node *node) { const char *unitname = get_unitname(node); if (node->parent && node->parent->bus) return; if (!unitname[0]) return; if (!strncmp(unitname, "0x", 2)) { FAIL(c, dti, node, "unit name should not have leading \"0x\""); /* skip over 0x for next test */ unitname += 2; } if (unitname[0] == '0' && isxdigit(unitname[1])) FAIL(c, dti, node, "unit name should not have leading 0s"); } WARNING(unit_address_format, check_unit_address_format, NULL, &node_name_format, &pci_bridge, &simple_bus_bridge); /* * Style checks */ static void check_avoid_default_addr_size(struct check *c, struct dt_info *dti, struct node *node) { struct property *reg, *ranges; if (!node->parent) return; /* Ignore root node */ reg = get_property(node, "reg"); ranges = get_property(node, "ranges"); if (!reg && !ranges) return; if (node->parent->addr_cells == -1) FAIL(c, dti, node, "Relying on default #address-cells value"); if (node->parent->size_cells == -1) FAIL(c, dti, node, "Relying on default #size-cells value"); } WARNING(avoid_default_addr_size, check_avoid_default_addr_size, NULL, &addr_size_cells); static void check_avoid_unnecessary_addr_size(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; struct node *child; bool has_reg = false; if (!node->parent || node->addr_cells < 0 || node->size_cells < 0) return; if (get_property(node, "ranges") || !node->children) return; for_each_child(node, child) { prop = get_property(child, "reg"); if (prop) has_reg = true; } if (!has_reg) FAIL(c, dti, node, "unnecessary #address-cells/#size-cells without \"ranges\" or child \"reg\" property"); } WARNING(avoid_unnecessary_addr_size, check_avoid_unnecessary_addr_size, NULL, &avoid_default_addr_size); static bool node_is_disabled(struct node *node) { struct property *prop; prop = get_property(node, "status"); if (prop) { char *str = prop->val.val; if (streq("disabled", str)) return true; } return false; } static void check_unique_unit_address_common(struct check *c, struct dt_info *dti, struct node *node, bool disable_check) { struct node *childa; if (node->addr_cells < 0 || node->size_cells < 0) return; if (!node->children) return; for_each_child(node, childa) { struct node *childb; const char *addr_a = get_unitname(childa); if (!strlen(addr_a)) continue; if (disable_check && node_is_disabled(childa)) continue; for_each_child(node, childb) { const char *addr_b = get_unitname(childb); if (childa == childb) break; if (disable_check && node_is_disabled(childb)) continue; if (streq(addr_a, addr_b)) FAIL(c, dti, childb, "duplicate unit-address (also used in node %s)", childa->fullpath); } } } static void check_unique_unit_address(struct check *c, struct dt_info *dti, struct node *node) { check_unique_unit_address_common(c, dti, node, false); } WARNING(unique_unit_address, check_unique_unit_address, NULL, &avoid_default_addr_size); static void check_unique_unit_address_if_enabled(struct check *c, struct dt_info *dti, struct node *node) { check_unique_unit_address_common(c, dti, node, true); } CHECK_ENTRY(unique_unit_address_if_enabled, check_unique_unit_address_if_enabled, NULL, false, false, &avoid_default_addr_size); static void check_obsolete_chosen_interrupt_controller(struct check *c, struct dt_info *dti, struct node *node) { struct node *dt = dti->dt; struct node *chosen; struct property *prop; if (node != dt) return; chosen = get_node_by_path(dt, "/chosen"); if (!chosen) return; prop = get_property(chosen, "interrupt-controller"); if (prop) FAIL_PROP(c, dti, node, prop, "/chosen has obsolete \"interrupt-controller\" property"); } WARNING(obsolete_chosen_interrupt_controller, check_obsolete_chosen_interrupt_controller, NULL); static void check_chosen_node_is_root(struct check *c, struct dt_info *dti, struct node *node) { if (!streq(node->name, "chosen")) return; if (node->parent != dti->dt) FAIL(c, dti, node, "chosen node must be at root node"); } WARNING(chosen_node_is_root, check_chosen_node_is_root, NULL); static void check_chosen_node_bootargs(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; if (!streq(node->name, "chosen")) return; prop = get_property(node, "bootargs"); if (!prop) return; c->data = prop->name; check_is_string(c, dti, node); } WARNING(chosen_node_bootargs, check_chosen_node_bootargs, NULL); static void check_chosen_node_stdout_path(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; if (!streq(node->name, "chosen")) return; prop = get_property(node, "stdout-path"); if (!prop) { prop = get_property(node, "linux,stdout-path"); if (!prop) return; FAIL_PROP(c, dti, node, prop, "Use 'stdout-path' instead"); } c->data = prop->name; check_is_string(c, dti, node); } WARNING(chosen_node_stdout_path, check_chosen_node_stdout_path, NULL); struct provider { const char *prop_name; const char *cell_name; bool optional; }; static void check_property_phandle_args(struct check *c, struct dt_info *dti, struct node *node, struct property *prop, const struct provider *provider) { struct node *root = dti->dt; unsigned int cell, cellsize = 0; if (!is_multiple_of(prop->val.len, sizeof(cell_t))) { FAIL_PROP(c, dti, node, prop, "property size (%d) is invalid, expected multiple of %zu", prop->val.len, sizeof(cell_t)); return; } for (cell = 0; cell < prop->val.len / sizeof(cell_t); cell += cellsize + 1) { struct node *provider_node; struct property *cellprop; cell_t phandle; unsigned int expected; phandle = propval_cell_n(prop, cell); /* * Some bindings use a cell value 0 or -1 to skip over optional * entries when each index position has a specific definition. */ if (!phandle_is_valid(phandle)) { /* Give up if this is an overlay with external references */ if (dti->dtsflags & DTSF_PLUGIN) break; cellsize = 0; continue; } /* If we have markers, verify the current cell is a phandle */ if (prop->val.markers) { struct marker *m = prop->val.markers; for_each_marker_of_type(m, REF_PHANDLE) { if (m->offset == (cell * sizeof(cell_t))) break; } if (!m) FAIL_PROP(c, dti, node, prop, "cell %d is not a phandle reference", cell); } provider_node = get_node_by_phandle(root, phandle); if (!provider_node) { FAIL_PROP(c, dti, node, prop, "Could not get phandle node for (cell %d)", cell); break; } cellprop = get_property(provider_node, provider->cell_name); if (cellprop) { cellsize = propval_cell(cellprop); } else if (provider->optional) { cellsize = 0; } else { FAIL(c, dti, node, "Missing property '%s' in node %s or bad phandle (referred from %s[%d])", provider->cell_name, provider_node->fullpath, prop->name, cell); break; } expected = (cell + cellsize + 1) * sizeof(cell_t); if ((expected <= cell) || prop->val.len < expected) { FAIL_PROP(c, dti, node, prop, "property size (%d) too small for cell size %u", prop->val.len, cellsize); break; } } } static void check_provider_cells_property(struct check *c, struct dt_info *dti, struct node *node) { struct provider *provider = c->data; struct property *prop; prop = get_property(node, provider->prop_name); if (!prop) return; check_property_phandle_args(c, dti, node, prop, provider); } #define WARNING_PROPERTY_PHANDLE_CELLS(nm, propname, cells_name, ...) \ static struct provider nm##_provider = { (propname), (cells_name), __VA_ARGS__ }; \ WARNING_IF_NOT_CELL(nm##_is_cell, cells_name); \ WARNING(nm##_property, check_provider_cells_property, &nm##_provider, &nm##_is_cell, &phandle_references); WARNING_PROPERTY_PHANDLE_CELLS(clocks, "clocks", "#clock-cells"); WARNING_PROPERTY_PHANDLE_CELLS(cooling_device, "cooling-device", "#cooling-cells"); WARNING_PROPERTY_PHANDLE_CELLS(dmas, "dmas", "#dma-cells"); WARNING_PROPERTY_PHANDLE_CELLS(hwlocks, "hwlocks", "#hwlock-cells"); WARNING_PROPERTY_PHANDLE_CELLS(interrupts_extended, "interrupts-extended", "#interrupt-cells"); WARNING_PROPERTY_PHANDLE_CELLS(io_channels, "io-channels", "#io-channel-cells"); WARNING_PROPERTY_PHANDLE_CELLS(iommus, "iommus", "#iommu-cells"); WARNING_PROPERTY_PHANDLE_CELLS(mboxes, "mboxes", "#mbox-cells"); WARNING_PROPERTY_PHANDLE_CELLS(msi_parent, "msi-parent", "#msi-cells", true); WARNING_PROPERTY_PHANDLE_CELLS(mux_controls, "mux-controls", "#mux-control-cells"); WARNING_PROPERTY_PHANDLE_CELLS(phys, "phys", "#phy-cells"); WARNING_PROPERTY_PHANDLE_CELLS(power_domains, "power-domains", "#power-domain-cells"); WARNING_PROPERTY_PHANDLE_CELLS(pwms, "pwms", "#pwm-cells"); WARNING_PROPERTY_PHANDLE_CELLS(resets, "resets", "#reset-cells"); WARNING_PROPERTY_PHANDLE_CELLS(sound_dai, "sound-dai", "#sound-dai-cells"); WARNING_PROPERTY_PHANDLE_CELLS(thermal_sensors, "thermal-sensors", "#thermal-sensor-cells"); static bool prop_is_gpio(struct property *prop) { /* * *-gpios and *-gpio can appear in property names, * so skip over any false matches (only one known ATM) */ if (strends(prop->name, ",nr-gpios")) return false; return strends(prop->name, "-gpios") || streq(prop->name, "gpios") || strends(prop->name, "-gpio") || streq(prop->name, "gpio"); } static void check_gpios_property(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; /* Skip GPIO hog nodes which have 'gpios' property */ if (get_property(node, "gpio-hog")) return; for_each_property(node, prop) { struct provider provider; if (!prop_is_gpio(prop)) continue; provider.prop_name = prop->name; provider.cell_name = "#gpio-cells"; provider.optional = false; check_property_phandle_args(c, dti, node, prop, &provider); } } WARNING(gpios_property, check_gpios_property, NULL, &phandle_references); static void check_deprecated_gpio_property(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; for_each_property(node, prop) { if (!prop_is_gpio(prop)) continue; if (!strends(prop->name, "gpio")) continue; FAIL_PROP(c, dti, node, prop, "'[*-]gpio' is deprecated, use '[*-]gpios' instead"); } } CHECK(deprecated_gpio_property, check_deprecated_gpio_property, NULL); static bool node_is_interrupt_provider(struct node *node) { struct property *prop; prop = get_property(node, "interrupt-controller"); if (prop) return true; prop = get_property(node, "interrupt-map"); if (prop) return true; return false; } static void check_interrupt_provider(struct check *c, struct dt_info *dti, struct node *node) { struct property *prop; bool irq_provider = node_is_interrupt_provider(node); prop = get_property(node, "#interrupt-cells"); if (irq_provider && !prop) { FAIL(c, dti, node, "Missing '#interrupt-cells' in interrupt provider"); return; } if (!irq_provider && prop) { FAIL(c, dti, node, "'#interrupt-cells' found, but node is not an interrupt provider"); return; } } WARNING(interrupt_provider, check_interrupt_provider, NULL, &interrupts_extended_is_cell); static void check_interrupt_map(struct check *c, struct dt_info *dti, struct node *node) { struct node *root = dti->dt; struct property *prop, *irq_map_prop; size_t cellsize, cell, map_cells; irq_map_prop = get_property(node, "interrupt-map"); if (!irq_map_prop) return; if (node->addr_cells < 0) { FAIL(c, dti, node, "Missing '#address-cells' in interrupt-map provider"); return; } cellsize = node_addr_cells(node); cellsize += propval_cell(get_property(node, "#interrupt-cells")); prop = get_property(node, "interrupt-map-mask"); if (prop && (prop->val.len != (cellsize * sizeof(cell_t)))) FAIL_PROP(c, dti, node, prop, "property size (%d) is invalid, expected %zu", prop->val.len, cellsize * sizeof(cell_t)); if (!is_multiple_of(irq_map_prop->val.len, sizeof(cell_t))) { FAIL_PROP(c, dti, node, irq_map_prop, "property size (%d) is invalid, expected multiple of %zu", irq_map_prop->val.len, sizeof(cell_t)); return; } map_cells = irq_map_prop->val.len / sizeof(cell_t); for (cell = 0; cell < map_cells; ) { struct node *provider_node; struct property *cellprop; int phandle; size_t parent_cellsize; if ((cell + cellsize) >= map_cells) { FAIL_PROP(c, dti, node, irq_map_prop, "property size (%d) too small, expected > %zu", irq_map_prop->val.len, (cell + cellsize) * sizeof(cell_t)); break; } cell += cellsize; phandle = propval_cell_n(irq_map_prop, cell); if (!phandle_is_valid(phandle)) { /* Give up if this is an overlay with external references */ if (!(dti->dtsflags & DTSF_PLUGIN)) FAIL_PROP(c, dti, node, irq_map_prop, "Cell %zu is not a phandle(%d)", cell, phandle); break; } provider_node = get_node_by_phandle(root, phandle); if (!provider_node) { FAIL_PROP(c, dti, node, irq_map_prop, "Could not get phandle(%d) node for (cell %zu)", phandle, cell); break; } cellprop = get_property(provider_node, "#interrupt-cells"); if (cellprop) { parent_cellsize = propval_cell(cellprop); } else { FAIL(c, dti, node, "Missing property '#interrupt-cells' in node %s or bad phandle (referred from interrupt-map[%zu])", provider_node->fullpath, cell); break; } cellprop = get_property(provider_node, "#address-cells"); if (cellprop) parent_cellsize += propval_cell(cellprop); cell += 1 + parent_cellsize; } } WARNING(interrupt_map, check_interrupt_map, NULL, &phandle_references, &addr_size_cells, &interrupt_provider); static void check_interrupts_property(struct check *c, struct dt_info *dti, struct node *node) { struct node *root = dti->dt; struct node *irq_node = NULL, *parent = node; struct property *irq_prop, *prop = NULL; cell_t irq_cells, phandle; irq_prop = get_property(node, "interrupts"); if (!irq_prop) return; if (!is_multiple_of(irq_prop->val.len, sizeof(cell_t))) FAIL_PROP(c, dti, node, irq_prop, "size (%d) is invalid, expected multiple of %zu", irq_prop->val.len, sizeof(cell_t)); while (parent && !prop) { if (parent != node && node_is_interrupt_provider(parent)) { irq_node = parent; break; } prop = get_property(parent, "interrupt-parent"); if (prop) { phandle = propval_cell(prop); if (!phandle_is_valid(phandle)) { /* Give up if this is an overlay with * external references */ if (dti->dtsflags & DTSF_PLUGIN) return; FAIL_PROP(c, dti, parent, prop, "Invalid phandle"); continue; } irq_node = get_node_by_phandle(root, phandle); if (!irq_node) { FAIL_PROP(c, dti, parent, prop, "Bad phandle"); return; } if (!node_is_interrupt_provider(irq_node)) FAIL(c, dti, irq_node, "Missing interrupt-controller or interrupt-map property"); break; } parent = parent->parent; } if (!irq_node) { FAIL(c, dti, node, "Missing interrupt-parent"); return; } prop = get_property(irq_node, "#interrupt-cells"); if (!prop) { /* We warn about that already in another test. */ return; } irq_cells = propval_cell(prop); if (!is_multiple_of(irq_prop->val.len, irq_cells * sizeof(cell_t))) { FAIL_PROP(c, dti, node, prop, "size is (%d), expected multiple of %d", irq_prop->val.len, (int)(irq_cells * sizeof(cell_t))); } } WARNING(interrupts_property, check_interrupts_property, &phandle_references); static const struct bus_type graph_port_bus = { .name = "graph-port", }; static const struct bus_type graph_ports_bus = { .name = "graph-ports", }; static void check_graph_nodes(struct check *c, struct dt_info *dti, struct node *node) { struct node *child; for_each_child(node, child) { if (!(strprefixeq(child->name, child->basenamelen, "endpoint") || get_property(child, "remote-endpoint"))) continue; node->bus = &graph_port_bus; /* The parent of 'port' nodes can be either 'ports' or a device */ if (!node->parent->bus && (streq(node->parent->name, "ports") || get_property(node, "reg"))) node->parent->bus = &graph_ports_bus; break; } } WARNING(graph_nodes, check_graph_nodes, NULL); static void check_graph_child_address(struct check *c, struct dt_info *dti, struct node *node) { int cnt = 0; struct node *child; if (node->bus != &graph_ports_bus && node->bus != &graph_port_bus) return; for_each_child(node, child) { struct property *prop = get_property(child, "reg"); /* No error if we have any non-zero unit address */ if (prop && propval_cell(prop) != 0) return; cnt++; } if (cnt == 1 && node->addr_cells != -1) FAIL(c, dti, node, "graph node has single child node '%s', #address-cells/#size-cells are not necessary", node->children->name); } WARNING(graph_child_address, check_graph_child_address, NULL, &graph_nodes); static void check_graph_reg(struct check *c, struct dt_info *dti, struct node *node) { char unit_addr[9]; const char *unitname = get_unitname(node); struct property *prop; prop = get_property(node, "reg"); if (!prop || !unitname) return; if (!(prop->val.val && prop->val.len == sizeof(cell_t))) { FAIL(c, dti, node, "graph node malformed 'reg' property"); return; } snprintf(unit_addr, sizeof(unit_addr), "%x", propval_cell(prop)); if (!streq(unitname, unit_addr)) FAIL(c, dti, node, "graph node unit address error, expected \"%s\"", unit_addr); if (node->parent->addr_cells != 1) FAIL_PROP(c, dti, node, get_property(node, "#address-cells"), "graph node '#address-cells' is %d, must be 1", node->parent->addr_cells); if (node->parent->size_cells != 0) FAIL_PROP(c, dti, node, get_property(node, "#size-cells"), "graph node '#size-cells' is %d, must be 0", node->parent->size_cells); } static void check_graph_port(struct check *c, struct dt_info *dti, struct node *node) { if (node->bus != &graph_port_bus) return; if (!strprefixeq(node->name, node->basenamelen, "port")) FAIL(c, dti, node, "graph port node name should be 'port'"); check_graph_reg(c, dti, node); } WARNING(graph_port, check_graph_port, NULL, &graph_nodes); static struct node *get_remote_endpoint(struct check *c, struct dt_info *dti, struct node *endpoint) { cell_t phandle; struct node *node; struct property *prop; prop = get_property(endpoint, "remote-endpoint"); if (!prop) return NULL; phandle = propval_cell(prop); /* Give up if this is an overlay with external references */ if (!phandle_is_valid(phandle)) return NULL; node = get_node_by_phandle(dti->dt, phandle); if (!node) FAIL_PROP(c, dti, endpoint, prop, "graph phandle is not valid"); return node; } static void check_graph_endpoint(struct check *c, struct dt_info *dti, struct node *node) { struct node *remote_node; if (!node->parent || node->parent->bus != &graph_port_bus) return; if (!strprefixeq(node->name, node->basenamelen, "endpoint")) FAIL(c, dti, node, "graph endpoint node name should be 'endpoint'"); check_graph_reg(c, dti, node); remote_node = get_remote_endpoint(c, dti, node); if (!remote_node) return; if (get_remote_endpoint(c, dti, remote_node) != node) FAIL(c, dti, node, "graph connection to node '%s' is not bidirectional", remote_node->fullpath); } WARNING(graph_endpoint, check_graph_endpoint, NULL, &graph_nodes); static struct check *check_table[] = { &duplicate_node_names, &duplicate_property_names, &node_name_chars, &node_name_format, &property_name_chars, &name_is_string, &name_properties, &node_name_vs_property_name, &duplicate_label, &explicit_phandles, &phandle_references, &path_references, &omit_unused_nodes, &address_cells_is_cell, &size_cells_is_cell, &device_type_is_string, &model_is_string, &status_is_string, &label_is_string, &compatible_is_string_list, &names_is_string_list, &property_name_chars_strict, &node_name_chars_strict, &addr_size_cells, &reg_format, &ranges_format, &dma_ranges_format, &unit_address_vs_reg, &unit_address_format, &pci_bridge, &pci_device_reg, &pci_device_bus_num, &simple_bus_bridge, &simple_bus_reg, &i2c_bus_bridge, &i2c_bus_reg, &spi_bus_bridge, &spi_bus_reg, &avoid_default_addr_size, &avoid_unnecessary_addr_size, &unique_unit_address, &unique_unit_address_if_enabled, &obsolete_chosen_interrupt_controller, &chosen_node_is_root, &chosen_node_bootargs, &chosen_node_stdout_path, &clocks_property, &clocks_is_cell, &cooling_device_property, &cooling_device_is_cell, &dmas_property, &dmas_is_cell, &hwlocks_property, &hwlocks_is_cell, &interrupts_extended_property, &interrupts_extended_is_cell, &io_channels_property, &io_channels_is_cell, &iommus_property, &iommus_is_cell, &mboxes_property, &mboxes_is_cell, &msi_parent_property, &msi_parent_is_cell, &mux_controls_property, &mux_controls_is_cell, &phys_property, &phys_is_cell, &power_domains_property, &power_domains_is_cell, &pwms_property, &pwms_is_cell, &resets_property, &resets_is_cell, &sound_dai_property, &sound_dai_is_cell, &thermal_sensors_property, &thermal_sensors_is_cell, &deprecated_gpio_property, &gpios_property, &interrupts_property, &interrupt_provider, &interrupt_map, &alias_paths, &graph_nodes, &graph_child_address, &graph_port, &graph_endpoint, &always_fail, }; static void enable_warning_error(struct check *c, bool warn, bool error) { int i; /* Raising level, also raise it for prereqs */ if ((warn && !c->warn) || (error && !c->error)) for (i = 0; i < c->num_prereqs; i++) enable_warning_error(c->prereq[i], warn, error); c->warn = c->warn || warn; c->error = c->error || error; } static void disable_warning_error(struct check *c, bool warn, bool error) { unsigned int i; /* Lowering level, also lower it for things this is the prereq * for */ if ((warn && c->warn) || (error && c->error)) { for (i = 0; i < ARRAY_SIZE(check_table); i++) { struct check *cc = check_table[i]; int j; for (j = 0; j < cc->num_prereqs; j++) if (cc->prereq[j] == c) disable_warning_error(cc, warn, error); } } c->warn = c->warn && !warn; c->error = c->error && !error; } void parse_checks_option(bool warn, bool error, const char *arg) { unsigned int i; const char *name = arg; bool enable = true; if ((strncmp(arg, "no-", 3) == 0) || (strncmp(arg, "no_", 3) == 0)) { name = arg + 3; enable = false; } for (i = 0; i < ARRAY_SIZE(check_table); i++) { struct check *c = check_table[i]; if (streq(c->name, name)) { if (enable) enable_warning_error(c, warn, error); else disable_warning_error(c, warn, error); return; } } die("Unrecognized check name \"%s\"\n", name); } void process_checks(bool force, struct dt_info *dti) { unsigned int i; int error = 0; for (i = 0; i < ARRAY_SIZE(check_table); i++) { struct check *c = check_table[i]; if (c->warn || c->error) error = error || run_check(c, dti); } if (error) { if (!force) { fprintf(stderr, "ERROR: Input tree has errors, aborting " "(use -f to force output)\n"); exit(2); } else if (quiet < 3) { fprintf(stderr, "Warning: Input tree has errors, " "output forced\n"); } } }
linux-master
scripts/dtc/checks.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2012 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" int fdt_create_empty_tree(void *buf, int bufsize) { int err; err = fdt_create(buf, bufsize); if (err) return err; err = fdt_finish_reservemap(buf); if (err) return err; err = fdt_begin_node(buf, ""); if (err) return err; err = fdt_end_node(buf); if (err) return err; err = fdt_finish(buf); if (err) return err; return fdt_open_into(buf, buf, bufsize); }
linux-master
scripts/dtc/libfdt/fdt_empty_tree.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2016 Free Electrons * Copyright (C) 2016 NextThing Co. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" /** * overlay_get_target_phandle - retrieves the target phandle of a fragment * @fdto: pointer to the device tree overlay blob * @fragment: node offset of the fragment in the overlay * * overlay_get_target_phandle() retrieves the target phandle of an * overlay fragment when that fragment uses a phandle (target * property) instead of a path (target-path property). * * returns: * the phandle pointed by the target property * 0, if the phandle was not found * -1, if the phandle was malformed */ static uint32_t overlay_get_target_phandle(const void *fdto, int fragment) { const fdt32_t *val; int len; val = fdt_getprop(fdto, fragment, "target", &len); if (!val) return 0; if ((len != sizeof(*val)) || (fdt32_to_cpu(*val) == (uint32_t)-1)) return (uint32_t)-1; return fdt32_to_cpu(*val); } int fdt_overlay_target_offset(const void *fdt, const void *fdto, int fragment_offset, char const **pathp) { uint32_t phandle; const char *path = NULL; int path_len = 0, ret; /* Try first to do a phandle based lookup */ phandle = overlay_get_target_phandle(fdto, fragment_offset); if (phandle == (uint32_t)-1) return -FDT_ERR_BADPHANDLE; /* no phandle, try path */ if (!phandle) { /* And then a path based lookup */ path = fdt_getprop(fdto, fragment_offset, "target-path", &path_len); if (path) ret = fdt_path_offset(fdt, path); else ret = path_len; } else ret = fdt_node_offset_by_phandle(fdt, phandle); /* * If we haven't found either a target or a * target-path property in a node that contains a * __overlay__ subnode (we wouldn't be called * otherwise), consider it a improperly written * overlay */ if (ret < 0 && path_len == -FDT_ERR_NOTFOUND) ret = -FDT_ERR_BADOVERLAY; /* return on error */ if (ret < 0) return ret; /* return pointer to path (if available) */ if (pathp) *pathp = path ? path : NULL; return ret; } /** * overlay_phandle_add_offset - Increases a phandle by an offset * @fdt: Base device tree blob * @node: Device tree overlay blob * @name: Name of the property to modify (phandle or linux,phandle) * @delta: offset to apply * * overlay_phandle_add_offset() increments a node phandle by a given * offset. * * returns: * 0 on success. * Negative error code on error */ static int overlay_phandle_add_offset(void *fdt, int node, const char *name, uint32_t delta) { const fdt32_t *val; uint32_t adj_val; int len; val = fdt_getprop(fdt, node, name, &len); if (!val) return len; if (len != sizeof(*val)) return -FDT_ERR_BADPHANDLE; adj_val = fdt32_to_cpu(*val); if ((adj_val + delta) < adj_val) return -FDT_ERR_NOPHANDLES; adj_val += delta; if (adj_val == (uint32_t)-1) return -FDT_ERR_NOPHANDLES; return fdt_setprop_inplace_u32(fdt, node, name, adj_val); } /** * overlay_adjust_node_phandles - Offsets the phandles of a node * @fdto: Device tree overlay blob * @node: Offset of the node we want to adjust * @delta: Offset to shift the phandles of * * overlay_adjust_node_phandles() adds a constant to all the phandles * of a given node. This is mainly use as part of the overlay * application process, when we want to update all the overlay * phandles to not conflict with the overlays of the base device tree. * * returns: * 0 on success * Negative error code on failure */ static int overlay_adjust_node_phandles(void *fdto, int node, uint32_t delta) { int child; int ret; ret = overlay_phandle_add_offset(fdto, node, "phandle", delta); if (ret && ret != -FDT_ERR_NOTFOUND) return ret; ret = overlay_phandle_add_offset(fdto, node, "linux,phandle", delta); if (ret && ret != -FDT_ERR_NOTFOUND) return ret; fdt_for_each_subnode(child, fdto, node) { ret = overlay_adjust_node_phandles(fdto, child, delta); if (ret) return ret; } return 0; } /** * overlay_adjust_local_phandles - Adjust the phandles of a whole overlay * @fdto: Device tree overlay blob * @delta: Offset to shift the phandles of * * overlay_adjust_local_phandles() adds a constant to all the * phandles of an overlay. This is mainly use as part of the overlay * application process, when we want to update all the overlay * phandles to not conflict with the overlays of the base device tree. * * returns: * 0 on success * Negative error code on failure */ static int overlay_adjust_local_phandles(void *fdto, uint32_t delta) { /* * Start adjusting the phandles from the overlay root */ return overlay_adjust_node_phandles(fdto, 0, delta); } /** * overlay_update_local_node_references - Adjust the overlay references * @fdto: Device tree overlay blob * @tree_node: Node offset of the node to operate on * @fixup_node: Node offset of the matching local fixups node * @delta: Offset to shift the phandles of * * overlay_update_local_nodes_references() update the phandles * pointing to a node within the device tree overlay by adding a * constant delta. * * This is mainly used as part of a device tree application process, * where you want the device tree overlays phandles to not conflict * with the ones from the base device tree before merging them. * * returns: * 0 on success * Negative error code on failure */ static int overlay_update_local_node_references(void *fdto, int tree_node, int fixup_node, uint32_t delta) { int fixup_prop; int fixup_child; int ret; fdt_for_each_property_offset(fixup_prop, fdto, fixup_node) { const fdt32_t *fixup_val; const char *tree_val; const char *name; int fixup_len; int tree_len; int i; fixup_val = fdt_getprop_by_offset(fdto, fixup_prop, &name, &fixup_len); if (!fixup_val) return fixup_len; if (fixup_len % sizeof(uint32_t)) return -FDT_ERR_BADOVERLAY; fixup_len /= sizeof(uint32_t); tree_val = fdt_getprop(fdto, tree_node, name, &tree_len); if (!tree_val) { if (tree_len == -FDT_ERR_NOTFOUND) return -FDT_ERR_BADOVERLAY; return tree_len; } for (i = 0; i < fixup_len; i++) { fdt32_t adj_val; uint32_t poffset; poffset = fdt32_to_cpu(fixup_val[i]); /* * phandles to fixup can be unaligned. * * Use a memcpy for the architectures that do * not support unaligned accesses. */ memcpy(&adj_val, tree_val + poffset, sizeof(adj_val)); adj_val = cpu_to_fdt32(fdt32_to_cpu(adj_val) + delta); ret = fdt_setprop_inplace_namelen_partial(fdto, tree_node, name, strlen(name), poffset, &adj_val, sizeof(adj_val)); if (ret == -FDT_ERR_NOSPACE) return -FDT_ERR_BADOVERLAY; if (ret) return ret; } } fdt_for_each_subnode(fixup_child, fdto, fixup_node) { const char *fixup_child_name = fdt_get_name(fdto, fixup_child, NULL); int tree_child; tree_child = fdt_subnode_offset(fdto, tree_node, fixup_child_name); if (tree_child == -FDT_ERR_NOTFOUND) return -FDT_ERR_BADOVERLAY; if (tree_child < 0) return tree_child; ret = overlay_update_local_node_references(fdto, tree_child, fixup_child, delta); if (ret) return ret; } return 0; } /** * overlay_update_local_references - Adjust the overlay references * @fdto: Device tree overlay blob * @delta: Offset to shift the phandles of * * overlay_update_local_references() update all the phandles pointing * to a node within the device tree overlay by adding a constant * delta to not conflict with the base overlay. * * This is mainly used as part of a device tree application process, * where you want the device tree overlays phandles to not conflict * with the ones from the base device tree before merging them. * * returns: * 0 on success * Negative error code on failure */ static int overlay_update_local_references(void *fdto, uint32_t delta) { int fixups; fixups = fdt_path_offset(fdto, "/__local_fixups__"); if (fixups < 0) { /* There's no local phandles to adjust, bail out */ if (fixups == -FDT_ERR_NOTFOUND) return 0; return fixups; } /* * Update our local references from the root of the tree */ return overlay_update_local_node_references(fdto, 0, fixups, delta); } /** * overlay_fixup_one_phandle - Set an overlay phandle to the base one * @fdt: Base Device Tree blob * @fdto: Device tree overlay blob * @symbols_off: Node offset of the symbols node in the base device tree * @path: Path to a node holding a phandle in the overlay * @path_len: number of path characters to consider * @name: Name of the property holding the phandle reference in the overlay * @name_len: number of name characters to consider * @poffset: Offset within the overlay property where the phandle is stored * @label: Label of the node referenced by the phandle * * overlay_fixup_one_phandle() resolves an overlay phandle pointing to * a node in the base device tree. * * This is part of the device tree overlay application process, when * you want all the phandles in the overlay to point to the actual * base dt nodes. * * returns: * 0 on success * Negative error code on failure */ static int overlay_fixup_one_phandle(void *fdt, void *fdto, int symbols_off, const char *path, uint32_t path_len, const char *name, uint32_t name_len, int poffset, const char *label) { const char *symbol_path; uint32_t phandle; fdt32_t phandle_prop; int symbol_off, fixup_off; int prop_len; if (symbols_off < 0) return symbols_off; symbol_path = fdt_getprop(fdt, symbols_off, label, &prop_len); if (!symbol_path) return prop_len; symbol_off = fdt_path_offset(fdt, symbol_path); if (symbol_off < 0) return symbol_off; phandle = fdt_get_phandle(fdt, symbol_off); if (!phandle) return -FDT_ERR_NOTFOUND; fixup_off = fdt_path_offset_namelen(fdto, path, path_len); if (fixup_off == -FDT_ERR_NOTFOUND) return -FDT_ERR_BADOVERLAY; if (fixup_off < 0) return fixup_off; phandle_prop = cpu_to_fdt32(phandle); return fdt_setprop_inplace_namelen_partial(fdto, fixup_off, name, name_len, poffset, &phandle_prop, sizeof(phandle_prop)); }; /** * overlay_fixup_phandle - Set an overlay phandle to the base one * @fdt: Base Device Tree blob * @fdto: Device tree overlay blob * @symbols_off: Node offset of the symbols node in the base device tree * @property: Property offset in the overlay holding the list of fixups * * overlay_fixup_phandle() resolves all the overlay phandles pointed * to in a __fixups__ property, and updates them to match the phandles * in use in the base device tree. * * This is part of the device tree overlay application process, when * you want all the phandles in the overlay to point to the actual * base dt nodes. * * returns: * 0 on success * Negative error code on failure */ static int overlay_fixup_phandle(void *fdt, void *fdto, int symbols_off, int property) { const char *value; const char *label; int len; value = fdt_getprop_by_offset(fdto, property, &label, &len); if (!value) { if (len == -FDT_ERR_NOTFOUND) return -FDT_ERR_INTERNAL; return len; } do { const char *path, *name, *fixup_end; const char *fixup_str = value; uint32_t path_len, name_len; uint32_t fixup_len; char *sep, *endptr; int poffset, ret; fixup_end = memchr(value, '\0', len); if (!fixup_end) return -FDT_ERR_BADOVERLAY; fixup_len = fixup_end - fixup_str; len -= fixup_len + 1; value += fixup_len + 1; path = fixup_str; sep = memchr(fixup_str, ':', fixup_len); if (!sep || *sep != ':') return -FDT_ERR_BADOVERLAY; path_len = sep - path; if (path_len == (fixup_len - 1)) return -FDT_ERR_BADOVERLAY; fixup_len -= path_len + 1; name = sep + 1; sep = memchr(name, ':', fixup_len); if (!sep || *sep != ':') return -FDT_ERR_BADOVERLAY; name_len = sep - name; if (!name_len) return -FDT_ERR_BADOVERLAY; poffset = strtoul(sep + 1, &endptr, 10); if ((*endptr != '\0') || (endptr <= (sep + 1))) return -FDT_ERR_BADOVERLAY; ret = overlay_fixup_one_phandle(fdt, fdto, symbols_off, path, path_len, name, name_len, poffset, label); if (ret) return ret; } while (len > 0); return 0; } /** * overlay_fixup_phandles - Resolve the overlay phandles to the base * device tree * @fdt: Base Device Tree blob * @fdto: Device tree overlay blob * * overlay_fixup_phandles() resolves all the overlay phandles pointing * to nodes in the base device tree. * * This is one of the steps of the device tree overlay application * process, when you want all the phandles in the overlay to point to * the actual base dt nodes. * * returns: * 0 on success * Negative error code on failure */ static int overlay_fixup_phandles(void *fdt, void *fdto) { int fixups_off, symbols_off; int property; /* We can have overlays without any fixups */ fixups_off = fdt_path_offset(fdto, "/__fixups__"); if (fixups_off == -FDT_ERR_NOTFOUND) return 0; /* nothing to do */ if (fixups_off < 0) return fixups_off; /* And base DTs without symbols */ symbols_off = fdt_path_offset(fdt, "/__symbols__"); if ((symbols_off < 0 && (symbols_off != -FDT_ERR_NOTFOUND))) return symbols_off; fdt_for_each_property_offset(property, fdto, fixups_off) { int ret; ret = overlay_fixup_phandle(fdt, fdto, symbols_off, property); if (ret) return ret; } return 0; } /** * overlay_apply_node - Merges a node into the base device tree * @fdt: Base Device Tree blob * @target: Node offset in the base device tree to apply the fragment to * @fdto: Device tree overlay blob * @node: Node offset in the overlay holding the changes to merge * * overlay_apply_node() merges a node into a target base device tree * node pointed. * * This is part of the final step in the device tree overlay * application process, when all the phandles have been adjusted and * resolved and you just have to merge overlay into the base device * tree. * * returns: * 0 on success * Negative error code on failure */ static int overlay_apply_node(void *fdt, int target, void *fdto, int node) { int property; int subnode; fdt_for_each_property_offset(property, fdto, node) { const char *name; const void *prop; int prop_len; int ret; prop = fdt_getprop_by_offset(fdto, property, &name, &prop_len); if (prop_len == -FDT_ERR_NOTFOUND) return -FDT_ERR_INTERNAL; if (prop_len < 0) return prop_len; ret = fdt_setprop(fdt, target, name, prop, prop_len); if (ret) return ret; } fdt_for_each_subnode(subnode, fdto, node) { const char *name = fdt_get_name(fdto, subnode, NULL); int nnode; int ret; nnode = fdt_add_subnode(fdt, target, name); if (nnode == -FDT_ERR_EXISTS) { nnode = fdt_subnode_offset(fdt, target, name); if (nnode == -FDT_ERR_NOTFOUND) return -FDT_ERR_INTERNAL; } if (nnode < 0) return nnode; ret = overlay_apply_node(fdt, nnode, fdto, subnode); if (ret) return ret; } return 0; } /** * overlay_merge - Merge an overlay into its base device tree * @fdt: Base Device Tree blob * @fdto: Device tree overlay blob * * overlay_merge() merges an overlay into its base device tree. * * This is the next to last step in the device tree overlay application * process, when all the phandles have been adjusted and resolved and * you just have to merge overlay into the base device tree. * * returns: * 0 on success * Negative error code on failure */ static int overlay_merge(void *fdt, void *fdto) { int fragment; fdt_for_each_subnode(fragment, fdto, 0) { int overlay; int target; int ret; /* * Each fragments will have an __overlay__ node. If * they don't, it's not supposed to be merged */ overlay = fdt_subnode_offset(fdto, fragment, "__overlay__"); if (overlay == -FDT_ERR_NOTFOUND) continue; if (overlay < 0) return overlay; target = fdt_overlay_target_offset(fdt, fdto, fragment, NULL); if (target < 0) return target; ret = overlay_apply_node(fdt, target, fdto, overlay); if (ret) return ret; } return 0; } static int get_path_len(const void *fdt, int nodeoffset) { int len = 0, namelen; const char *name; FDT_RO_PROBE(fdt); for (;;) { name = fdt_get_name(fdt, nodeoffset, &namelen); if (!name) return namelen; /* root? we're done */ if (namelen == 0) break; nodeoffset = fdt_parent_offset(fdt, nodeoffset); if (nodeoffset < 0) return nodeoffset; len += namelen + 1; } /* in case of root pretend it's "/" */ if (len == 0) len++; return len; } /** * overlay_symbol_update - Update the symbols of base tree after a merge * @fdt: Base Device Tree blob * @fdto: Device tree overlay blob * * overlay_symbol_update() updates the symbols of the base tree with the * symbols of the applied overlay * * This is the last step in the device tree overlay application * process, allowing the reference of overlay symbols by subsequent * overlay operations. * * returns: * 0 on success * Negative error code on failure */ static int overlay_symbol_update(void *fdt, void *fdto) { int root_sym, ov_sym, prop, path_len, fragment, target; int len, frag_name_len, ret, rel_path_len; const char *s, *e; const char *path; const char *name; const char *frag_name; const char *rel_path; const char *target_path; char *buf; void *p; ov_sym = fdt_subnode_offset(fdto, 0, "__symbols__"); /* if no overlay symbols exist no problem */ if (ov_sym < 0) return 0; root_sym = fdt_subnode_offset(fdt, 0, "__symbols__"); /* it no root symbols exist we should create them */ if (root_sym == -FDT_ERR_NOTFOUND) root_sym = fdt_add_subnode(fdt, 0, "__symbols__"); /* any error is fatal now */ if (root_sym < 0) return root_sym; /* iterate over each overlay symbol */ fdt_for_each_property_offset(prop, fdto, ov_sym) { path = fdt_getprop_by_offset(fdto, prop, &name, &path_len); if (!path) return path_len; /* verify it's a string property (terminated by a single \0) */ if (path_len < 1 || memchr(path, '\0', path_len) != &path[path_len - 1]) return -FDT_ERR_BADVALUE; /* keep end marker to avoid strlen() */ e = path + path_len; if (*path != '/') return -FDT_ERR_BADVALUE; /* get fragment name first */ s = strchr(path + 1, '/'); if (!s) { /* Symbol refers to something that won't end * up in the target tree */ continue; } frag_name = path + 1; frag_name_len = s - path - 1; /* verify format; safe since "s" lies in \0 terminated prop */ len = sizeof("/__overlay__/") - 1; if ((e - s) > len && (memcmp(s, "/__overlay__/", len) == 0)) { /* /<fragment-name>/__overlay__/<relative-subnode-path> */ rel_path = s + len; rel_path_len = e - rel_path - 1; } else if ((e - s) == len && (memcmp(s, "/__overlay__", len - 1) == 0)) { /* /<fragment-name>/__overlay__ */ rel_path = ""; rel_path_len = 0; } else { /* Symbol refers to something that won't end * up in the target tree */ continue; } /* find the fragment index in which the symbol lies */ ret = fdt_subnode_offset_namelen(fdto, 0, frag_name, frag_name_len); /* not found? */ if (ret < 0) return -FDT_ERR_BADOVERLAY; fragment = ret; /* an __overlay__ subnode must exist */ ret = fdt_subnode_offset(fdto, fragment, "__overlay__"); if (ret < 0) return -FDT_ERR_BADOVERLAY; /* get the target of the fragment */ ret = fdt_overlay_target_offset(fdt, fdto, fragment, &target_path); if (ret < 0) return ret; target = ret; /* if we have a target path use */ if (!target_path) { ret = get_path_len(fdt, target); if (ret < 0) return ret; len = ret; } else { len = strlen(target_path); } ret = fdt_setprop_placeholder(fdt, root_sym, name, len + (len > 1) + rel_path_len + 1, &p); if (ret < 0) return ret; if (!target_path) { /* again in case setprop_placeholder changed it */ ret = fdt_overlay_target_offset(fdt, fdto, fragment, &target_path); if (ret < 0) return ret; target = ret; } buf = p; if (len > 1) { /* target is not root */ if (!target_path) { ret = fdt_get_path(fdt, target, buf, len + 1); if (ret < 0) return ret; } else memcpy(buf, target_path, len + 1); } else len--; buf[len] = '/'; memcpy(buf + len + 1, rel_path, rel_path_len); buf[len + 1 + rel_path_len] = '\0'; } return 0; } int fdt_overlay_apply(void *fdt, void *fdto) { uint32_t delta; int ret; FDT_RO_PROBE(fdt); FDT_RO_PROBE(fdto); ret = fdt_find_max_phandle(fdt, &delta); if (ret) goto err; ret = overlay_adjust_local_phandles(fdto, delta); if (ret) goto err; ret = overlay_update_local_references(fdto, delta); if (ret) goto err; ret = overlay_fixup_phandles(fdt, fdto); if (ret) goto err; ret = overlay_merge(fdt, fdto); if (ret) goto err; ret = overlay_symbol_update(fdt, fdto); if (ret) goto err; /* * The overlay has been damaged, erase its magic. */ fdt_set_magic(fdto, ~0); return 0; err: /* * The overlay might have been damaged, erase its magic. */ fdt_set_magic(fdto, ~0); /* * The base device tree might have been damaged, erase its * magic. */ fdt_set_magic(fdt, ~0); return ret; }
linux-master
scripts/dtc/libfdt/fdt_overlay.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" /* * Minimal sanity check for a read-only tree. fdt_ro_probe_() checks * that the given buffer contains what appears to be a flattened * device tree with sane information in its header. */ int32_t fdt_ro_probe_(const void *fdt) { uint32_t totalsize = fdt_totalsize(fdt); if (can_assume(VALID_DTB)) return totalsize; /* The device tree must be at an 8-byte aligned address */ if ((uintptr_t)fdt & 7) return -FDT_ERR_ALIGNMENT; if (fdt_magic(fdt) == FDT_MAGIC) { /* Complete tree */ if (!can_assume(LATEST)) { if (fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION) return -FDT_ERR_BADVERSION; if (fdt_last_comp_version(fdt) > FDT_LAST_SUPPORTED_VERSION) return -FDT_ERR_BADVERSION; } } else if (fdt_magic(fdt) == FDT_SW_MAGIC) { /* Unfinished sequential-write blob */ if (!can_assume(VALID_INPUT) && fdt_size_dt_struct(fdt) == 0) return -FDT_ERR_BADSTATE; } else { return -FDT_ERR_BADMAGIC; } if (totalsize < INT32_MAX) return totalsize; else return -FDT_ERR_TRUNCATED; } static int check_off_(uint32_t hdrsize, uint32_t totalsize, uint32_t off) { return (off >= hdrsize) && (off <= totalsize); } static int check_block_(uint32_t hdrsize, uint32_t totalsize, uint32_t base, uint32_t size) { if (!check_off_(hdrsize, totalsize, base)) return 0; /* block start out of bounds */ if ((base + size) < base) return 0; /* overflow */ if (!check_off_(hdrsize, totalsize, base + size)) return 0; /* block end out of bounds */ return 1; } size_t fdt_header_size_(uint32_t version) { if (version <= 1) return FDT_V1_SIZE; else if (version <= 2) return FDT_V2_SIZE; else if (version <= 3) return FDT_V3_SIZE; else if (version <= 16) return FDT_V16_SIZE; else return FDT_V17_SIZE; } size_t fdt_header_size(const void *fdt) { return can_assume(LATEST) ? FDT_V17_SIZE : fdt_header_size_(fdt_version(fdt)); } int fdt_check_header(const void *fdt) { size_t hdrsize; /* The device tree must be at an 8-byte aligned address */ if ((uintptr_t)fdt & 7) return -FDT_ERR_ALIGNMENT; if (fdt_magic(fdt) != FDT_MAGIC) return -FDT_ERR_BADMAGIC; if (!can_assume(LATEST)) { if ((fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION) || (fdt_last_comp_version(fdt) > FDT_LAST_SUPPORTED_VERSION)) return -FDT_ERR_BADVERSION; if (fdt_version(fdt) < fdt_last_comp_version(fdt)) return -FDT_ERR_BADVERSION; } hdrsize = fdt_header_size(fdt); if (!can_assume(VALID_DTB)) { if ((fdt_totalsize(fdt) < hdrsize) || (fdt_totalsize(fdt) > INT_MAX)) return -FDT_ERR_TRUNCATED; /* Bounds check memrsv block */ if (!check_off_(hdrsize, fdt_totalsize(fdt), fdt_off_mem_rsvmap(fdt))) return -FDT_ERR_TRUNCATED; /* Bounds check structure block */ if (!can_assume(LATEST) && fdt_version(fdt) < 17) { if (!check_off_(hdrsize, fdt_totalsize(fdt), fdt_off_dt_struct(fdt))) return -FDT_ERR_TRUNCATED; } else { if (!check_block_(hdrsize, fdt_totalsize(fdt), fdt_off_dt_struct(fdt), fdt_size_dt_struct(fdt))) return -FDT_ERR_TRUNCATED; } /* Bounds check strings block */ if (!check_block_(hdrsize, fdt_totalsize(fdt), fdt_off_dt_strings(fdt), fdt_size_dt_strings(fdt))) return -FDT_ERR_TRUNCATED; } return 0; } const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len) { unsigned int uoffset = offset; unsigned int absoffset = offset + fdt_off_dt_struct(fdt); if (offset < 0) return NULL; if (!can_assume(VALID_INPUT)) if ((absoffset < uoffset) || ((absoffset + len) < absoffset) || (absoffset + len) > fdt_totalsize(fdt)) return NULL; if (can_assume(LATEST) || fdt_version(fdt) >= 0x11) if (((uoffset + len) < uoffset) || ((offset + len) > fdt_size_dt_struct(fdt))) return NULL; return fdt_offset_ptr_(fdt, offset); } uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) { const fdt32_t *tagp, *lenp; uint32_t tag, len, sum; int offset = startoffset; const char *p; *nextoffset = -FDT_ERR_TRUNCATED; tagp = fdt_offset_ptr(fdt, offset, FDT_TAGSIZE); if (!can_assume(VALID_DTB) && !tagp) return FDT_END; /* premature end */ tag = fdt32_to_cpu(*tagp); offset += FDT_TAGSIZE; *nextoffset = -FDT_ERR_BADSTRUCTURE; switch (tag) { case FDT_BEGIN_NODE: /* skip name */ do { p = fdt_offset_ptr(fdt, offset++, 1); } while (p && (*p != '\0')); if (!can_assume(VALID_DTB) && !p) return FDT_END; /* premature end */ break; case FDT_PROP: lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp)); if (!can_assume(VALID_DTB) && !lenp) return FDT_END; /* premature end */ len = fdt32_to_cpu(*lenp); sum = len + offset; if (!can_assume(VALID_DTB) && (INT_MAX <= sum || sum < (uint32_t) offset)) return FDT_END; /* premature end */ /* skip-name offset, length and value */ offset += sizeof(struct fdt_property) - FDT_TAGSIZE + len; if (!can_assume(LATEST) && fdt_version(fdt) < 0x10 && len >= 8 && ((offset - len) % 8) != 0) offset += 4; break; case FDT_END: case FDT_END_NODE: case FDT_NOP: break; default: return FDT_END; } if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset)) return FDT_END; /* premature end */ *nextoffset = FDT_TAGALIGN(offset); return tag; } int fdt_check_node_offset_(const void *fdt, int offset) { if (!can_assume(VALID_INPUT) && ((offset < 0) || (offset % FDT_TAGSIZE))) return -FDT_ERR_BADOFFSET; if (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE) return -FDT_ERR_BADOFFSET; return offset; } int fdt_check_prop_offset_(const void *fdt, int offset) { if (!can_assume(VALID_INPUT) && ((offset < 0) || (offset % FDT_TAGSIZE))) return -FDT_ERR_BADOFFSET; if (fdt_next_tag(fdt, offset, &offset) != FDT_PROP) return -FDT_ERR_BADOFFSET; return offset; } int fdt_next_node(const void *fdt, int offset, int *depth) { int nextoffset = 0; uint32_t tag; if (offset >= 0) if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0) return nextoffset; do { offset = nextoffset; tag = fdt_next_tag(fdt, offset, &nextoffset); switch (tag) { case FDT_PROP: case FDT_NOP: break; case FDT_BEGIN_NODE: if (depth) (*depth)++; break; case FDT_END_NODE: if (depth && ((--(*depth)) < 0)) return nextoffset; break; case FDT_END: if ((nextoffset >= 0) || ((nextoffset == -FDT_ERR_TRUNCATED) && !depth)) return -FDT_ERR_NOTFOUND; else return nextoffset; } } while (tag != FDT_BEGIN_NODE); return offset; } int fdt_first_subnode(const void *fdt, int offset) { int depth = 0; offset = fdt_next_node(fdt, offset, &depth); if (offset < 0 || depth != 1) return -FDT_ERR_NOTFOUND; return offset; } int fdt_next_subnode(const void *fdt, int offset) { int depth = 1; /* * With respect to the parent, the depth of the next subnode will be * the same as the last. */ do { offset = fdt_next_node(fdt, offset, &depth); if (offset < 0 || depth < 1) return -FDT_ERR_NOTFOUND; } while (depth > 1); return offset; } const char *fdt_find_string_(const char *strtab, int tabsize, const char *s) { int len = strlen(s) + 1; const char *last = strtab + tabsize - len; const char *p; for (p = strtab; p <= last; p++) if (memcmp(p, s, len) == 0) return p; return NULL; } int fdt_move(const void *fdt, void *buf, int bufsize) { if (!can_assume(VALID_INPUT) && bufsize < 0) return -FDT_ERR_NOSPACE; FDT_RO_PROBE(fdt); if (fdt_totalsize(fdt) > (unsigned int)bufsize) return -FDT_ERR_NOSPACE; memmove(buf, fdt, fdt_totalsize(fdt)); return 0; }
linux-master
scripts/dtc/libfdt/fdt.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" struct fdt_errtabent { const char *str; }; #define FDT_ERRTABENT(val) \ [(val)] = { .str = #val, } static struct fdt_errtabent fdt_errtable[] = { FDT_ERRTABENT(FDT_ERR_NOTFOUND), FDT_ERRTABENT(FDT_ERR_EXISTS), FDT_ERRTABENT(FDT_ERR_NOSPACE), FDT_ERRTABENT(FDT_ERR_BADOFFSET), FDT_ERRTABENT(FDT_ERR_BADPATH), FDT_ERRTABENT(FDT_ERR_BADPHANDLE), FDT_ERRTABENT(FDT_ERR_BADSTATE), FDT_ERRTABENT(FDT_ERR_TRUNCATED), FDT_ERRTABENT(FDT_ERR_BADMAGIC), FDT_ERRTABENT(FDT_ERR_BADVERSION), FDT_ERRTABENT(FDT_ERR_BADSTRUCTURE), FDT_ERRTABENT(FDT_ERR_BADLAYOUT), FDT_ERRTABENT(FDT_ERR_INTERNAL), FDT_ERRTABENT(FDT_ERR_BADNCELLS), FDT_ERRTABENT(FDT_ERR_BADVALUE), FDT_ERRTABENT(FDT_ERR_BADOVERLAY), FDT_ERRTABENT(FDT_ERR_NOPHANDLES), FDT_ERRTABENT(FDT_ERR_BADFLAGS), FDT_ERRTABENT(FDT_ERR_ALIGNMENT), }; #define FDT_ERRTABSIZE ((int)(sizeof(fdt_errtable) / sizeof(fdt_errtable[0]))) const char *fdt_strerror(int errval) { if (errval > 0) return "<valid offset/length>"; else if (errval == 0) return "<no error>"; else if (-errval < FDT_ERRTABSIZE) { const char *s = fdt_errtable[-errval].str; if (s) return s; } return "<unknown error>"; }
linux-master
scripts/dtc/libfdt/fdt_strerror.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset, const char *name, int namelen, uint32_t idx, const void *val, int len) { void *propval; int proplen; propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen, &proplen); if (!propval) return proplen; if ((unsigned)proplen < (len + idx)) return -FDT_ERR_NOSPACE; memcpy((char *)propval + idx, val, len); return 0; } int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name, const void *val, int len) { const void *propval; int proplen; propval = fdt_getprop(fdt, nodeoffset, name, &proplen); if (!propval) return proplen; if (proplen != len) return -FDT_ERR_NOSPACE; return fdt_setprop_inplace_namelen_partial(fdt, nodeoffset, name, strlen(name), 0, val, len); } static void fdt_nop_region_(void *start, int len) { fdt32_t *p; for (p = start; (char *)p < ((char *)start + len); p++) *p = cpu_to_fdt32(FDT_NOP); } int fdt_nop_property(void *fdt, int nodeoffset, const char *name) { struct fdt_property *prop; int len; prop = fdt_get_property_w(fdt, nodeoffset, name, &len); if (!prop) return len; fdt_nop_region_(prop, len + sizeof(*prop)); return 0; } int fdt_node_end_offset_(void *fdt, int offset) { int depth = 0; while ((offset >= 0) && (depth >= 0)) offset = fdt_next_node(fdt, offset, &depth); return offset; } int fdt_nop_node(void *fdt, int nodeoffset) { int endoffset; endoffset = fdt_node_end_offset_(fdt, nodeoffset); if (endoffset < 0) return endoffset; fdt_nop_region_(fdt_offset_ptr_w(fdt, nodeoffset, 0), endoffset - nodeoffset); return 0; }
linux-master
scripts/dtc/libfdt/fdt_wip.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" static int fdt_blocks_misordered_(const void *fdt, int mem_rsv_size, int struct_size) { return (fdt_off_mem_rsvmap(fdt) < FDT_ALIGN(sizeof(struct fdt_header), 8)) || (fdt_off_dt_struct(fdt) < (fdt_off_mem_rsvmap(fdt) + mem_rsv_size)) || (fdt_off_dt_strings(fdt) < (fdt_off_dt_struct(fdt) + struct_size)) || (fdt_totalsize(fdt) < (fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt))); } static int fdt_rw_probe_(void *fdt) { if (can_assume(VALID_DTB)) return 0; FDT_RO_PROBE(fdt); if (!can_assume(LATEST) && fdt_version(fdt) < 17) return -FDT_ERR_BADVERSION; if (fdt_blocks_misordered_(fdt, sizeof(struct fdt_reserve_entry), fdt_size_dt_struct(fdt))) return -FDT_ERR_BADLAYOUT; if (!can_assume(LATEST) && fdt_version(fdt) > 17) fdt_set_version(fdt, 17); return 0; } #define FDT_RW_PROBE(fdt) \ { \ int err_; \ if ((err_ = fdt_rw_probe_(fdt)) != 0) \ return err_; \ } static inline unsigned int fdt_data_size_(void *fdt) { return fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt); } static int fdt_splice_(void *fdt, void *splicepoint, int oldlen, int newlen) { char *p = splicepoint; unsigned int dsize = fdt_data_size_(fdt); size_t soff = p - (char *)fdt; if ((oldlen < 0) || (soff + oldlen < soff) || (soff + oldlen > dsize)) return -FDT_ERR_BADOFFSET; if ((p < (char *)fdt) || (dsize + newlen < (unsigned)oldlen)) return -FDT_ERR_BADOFFSET; if (dsize - oldlen + newlen > fdt_totalsize(fdt)) return -FDT_ERR_NOSPACE; memmove(p + newlen, p + oldlen, ((char *)fdt + dsize) - (p + oldlen)); return 0; } static int fdt_splice_mem_rsv_(void *fdt, struct fdt_reserve_entry *p, int oldn, int newn) { int delta = (newn - oldn) * sizeof(*p); int err; err = fdt_splice_(fdt, p, oldn * sizeof(*p), newn * sizeof(*p)); if (err) return err; fdt_set_off_dt_struct(fdt, fdt_off_dt_struct(fdt) + delta); fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta); return 0; } static int fdt_splice_struct_(void *fdt, void *p, int oldlen, int newlen) { int delta = newlen - oldlen; int err; if ((err = fdt_splice_(fdt, p, oldlen, newlen))) return err; fdt_set_size_dt_struct(fdt, fdt_size_dt_struct(fdt) + delta); fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta); return 0; } /* Must only be used to roll back in case of error */ static void fdt_del_last_string_(void *fdt, const char *s) { int newlen = strlen(s) + 1; fdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) - newlen); } static int fdt_splice_string_(void *fdt, int newlen) { void *p = (char *)fdt + fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt); int err; if ((err = fdt_splice_(fdt, p, 0, newlen))) return err; fdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) + newlen); return 0; } /** * fdt_find_add_string_() - Find or allocate a string * * @fdt: pointer to the device tree to check/adjust * @s: string to find/add * @allocated: Set to 0 if the string was found, 1 if not found and so * allocated. Ignored if can_assume(NO_ROLLBACK) * @return offset of string in the string table (whether found or added) */ static int fdt_find_add_string_(void *fdt, const char *s, int *allocated) { char *strtab = (char *)fdt + fdt_off_dt_strings(fdt); const char *p; char *new; int len = strlen(s) + 1; int err; if (!can_assume(NO_ROLLBACK)) *allocated = 0; p = fdt_find_string_(strtab, fdt_size_dt_strings(fdt), s); if (p) /* found it */ return (p - strtab); new = strtab + fdt_size_dt_strings(fdt); err = fdt_splice_string_(fdt, len); if (err) return err; if (!can_assume(NO_ROLLBACK)) *allocated = 1; memcpy(new, s, len); return (new - strtab); } int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size) { struct fdt_reserve_entry *re; int err; FDT_RW_PROBE(fdt); re = fdt_mem_rsv_w_(fdt, fdt_num_mem_rsv(fdt)); err = fdt_splice_mem_rsv_(fdt, re, 0, 1); if (err) return err; re->address = cpu_to_fdt64(address); re->size = cpu_to_fdt64(size); return 0; } int fdt_del_mem_rsv(void *fdt, int n) { struct fdt_reserve_entry *re = fdt_mem_rsv_w_(fdt, n); FDT_RW_PROBE(fdt); if (n >= fdt_num_mem_rsv(fdt)) return -FDT_ERR_NOTFOUND; return fdt_splice_mem_rsv_(fdt, re, 1, 0); } static int fdt_resize_property_(void *fdt, int nodeoffset, const char *name, int len, struct fdt_property **prop) { int oldlen; int err; *prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen); if (!*prop) return oldlen; if ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen), FDT_TAGALIGN(len)))) return err; (*prop)->len = cpu_to_fdt32(len); return 0; } static int fdt_add_property_(void *fdt, int nodeoffset, const char *name, int len, struct fdt_property **prop) { int proplen; int nextoffset; int namestroff; int err; int allocated; if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0) return nextoffset; namestroff = fdt_find_add_string_(fdt, name, &allocated); if (namestroff < 0) return namestroff; *prop = fdt_offset_ptr_w_(fdt, nextoffset); proplen = sizeof(**prop) + FDT_TAGALIGN(len); err = fdt_splice_struct_(fdt, *prop, 0, proplen); if (err) { /* Delete the string if we failed to add it */ if (!can_assume(NO_ROLLBACK) && allocated) fdt_del_last_string_(fdt, name); return err; } (*prop)->tag = cpu_to_fdt32(FDT_PROP); (*prop)->nameoff = cpu_to_fdt32(namestroff); (*prop)->len = cpu_to_fdt32(len); return 0; } int fdt_set_name(void *fdt, int nodeoffset, const char *name) { char *namep; int oldlen, newlen; int err; FDT_RW_PROBE(fdt); namep = (char *)(uintptr_t)fdt_get_name(fdt, nodeoffset, &oldlen); if (!namep) return oldlen; newlen = strlen(name); err = fdt_splice_struct_(fdt, namep, FDT_TAGALIGN(oldlen+1), FDT_TAGALIGN(newlen+1)); if (err) return err; memcpy(namep, name, newlen+1); return 0; } int fdt_setprop_placeholder(void *fdt, int nodeoffset, const char *name, int len, void **prop_data) { struct fdt_property *prop; int err; FDT_RW_PROBE(fdt); err = fdt_resize_property_(fdt, nodeoffset, name, len, &prop); if (err == -FDT_ERR_NOTFOUND) err = fdt_add_property_(fdt, nodeoffset, name, len, &prop); if (err) return err; *prop_data = prop->data; return 0; } int fdt_setprop(void *fdt, int nodeoffset, const char *name, const void *val, int len) { void *prop_data; int err; err = fdt_setprop_placeholder(fdt, nodeoffset, name, len, &prop_data); if (err) return err; if (len) memcpy(prop_data, val, len); return 0; } int fdt_appendprop(void *fdt, int nodeoffset, const char *name, const void *val, int len) { struct fdt_property *prop; int err, oldlen, newlen; FDT_RW_PROBE(fdt); prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen); if (prop) { newlen = len + oldlen; err = fdt_splice_struct_(fdt, prop->data, FDT_TAGALIGN(oldlen), FDT_TAGALIGN(newlen)); if (err) return err; prop->len = cpu_to_fdt32(newlen); memcpy(prop->data + oldlen, val, len); } else { err = fdt_add_property_(fdt, nodeoffset, name, len, &prop); if (err) return err; memcpy(prop->data, val, len); } return 0; } int fdt_delprop(void *fdt, int nodeoffset, const char *name) { struct fdt_property *prop; int len, proplen; FDT_RW_PROBE(fdt); prop = fdt_get_property_w(fdt, nodeoffset, name, &len); if (!prop) return len; proplen = sizeof(*prop) + FDT_TAGALIGN(len); return fdt_splice_struct_(fdt, prop, proplen, 0); } int fdt_add_subnode_namelen(void *fdt, int parentoffset, const char *name, int namelen) { struct fdt_node_header *nh; int offset, nextoffset; int nodelen; int err; uint32_t tag; fdt32_t *endtag; FDT_RW_PROBE(fdt); offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen); if (offset >= 0) return -FDT_ERR_EXISTS; else if (offset != -FDT_ERR_NOTFOUND) return offset; /* Try to place the new node after the parent's properties */ tag = fdt_next_tag(fdt, parentoffset, &nextoffset); /* the fdt_subnode_offset_namelen() should ensure this never hits */ if (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE)) return -FDT_ERR_INTERNAL; do { offset = nextoffset; tag = fdt_next_tag(fdt, offset, &nextoffset); } while ((tag == FDT_PROP) || (tag == FDT_NOP)); nh = fdt_offset_ptr_w_(fdt, offset); nodelen = sizeof(*nh) + FDT_TAGALIGN(namelen+1) + FDT_TAGSIZE; err = fdt_splice_struct_(fdt, nh, 0, nodelen); if (err) return err; nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE); memset(nh->name, 0, FDT_TAGALIGN(namelen+1)); memcpy(nh->name, name, namelen); endtag = (fdt32_t *)((char *)nh + nodelen - FDT_TAGSIZE); *endtag = cpu_to_fdt32(FDT_END_NODE); return offset; } int fdt_add_subnode(void *fdt, int parentoffset, const char *name) { return fdt_add_subnode_namelen(fdt, parentoffset, name, strlen(name)); } int fdt_del_node(void *fdt, int nodeoffset) { int endoffset; FDT_RW_PROBE(fdt); endoffset = fdt_node_end_offset_(fdt, nodeoffset); if (endoffset < 0) return endoffset; return fdt_splice_struct_(fdt, fdt_offset_ptr_w_(fdt, nodeoffset), endoffset - nodeoffset, 0); } static void fdt_packblocks_(const char *old, char *new, int mem_rsv_size, int struct_size, int strings_size) { int mem_rsv_off, struct_off, strings_off; mem_rsv_off = FDT_ALIGN(sizeof(struct fdt_header), 8); struct_off = mem_rsv_off + mem_rsv_size; strings_off = struct_off + struct_size; memmove(new + mem_rsv_off, old + fdt_off_mem_rsvmap(old), mem_rsv_size); fdt_set_off_mem_rsvmap(new, mem_rsv_off); memmove(new + struct_off, old + fdt_off_dt_struct(old), struct_size); fdt_set_off_dt_struct(new, struct_off); fdt_set_size_dt_struct(new, struct_size); memmove(new + strings_off, old + fdt_off_dt_strings(old), strings_size); fdt_set_off_dt_strings(new, strings_off); fdt_set_size_dt_strings(new, fdt_size_dt_strings(old)); } int fdt_open_into(const void *fdt, void *buf, int bufsize) { int err; int mem_rsv_size, struct_size; int newsize; const char *fdtstart = fdt; const char *fdtend = fdtstart + fdt_totalsize(fdt); char *tmp; FDT_RO_PROBE(fdt); mem_rsv_size = (fdt_num_mem_rsv(fdt)+1) * sizeof(struct fdt_reserve_entry); if (can_assume(LATEST) || fdt_version(fdt) >= 17) { struct_size = fdt_size_dt_struct(fdt); } else if (fdt_version(fdt) == 16) { struct_size = 0; while (fdt_next_tag(fdt, struct_size, &struct_size) != FDT_END) ; if (struct_size < 0) return struct_size; } else { return -FDT_ERR_BADVERSION; } if (can_assume(LIBFDT_ORDER) || !fdt_blocks_misordered_(fdt, mem_rsv_size, struct_size)) { /* no further work necessary */ err = fdt_move(fdt, buf, bufsize); if (err) return err; fdt_set_version(buf, 17); fdt_set_size_dt_struct(buf, struct_size); fdt_set_totalsize(buf, bufsize); return 0; } /* Need to reorder */ newsize = FDT_ALIGN(sizeof(struct fdt_header), 8) + mem_rsv_size + struct_size + fdt_size_dt_strings(fdt); if (bufsize < newsize) return -FDT_ERR_NOSPACE; /* First attempt to build converted tree at beginning of buffer */ tmp = buf; /* But if that overlaps with the old tree... */ if (((tmp + newsize) > fdtstart) && (tmp < fdtend)) { /* Try right after the old tree instead */ tmp = (char *)(uintptr_t)fdtend; if ((tmp + newsize) > ((char *)buf + bufsize)) return -FDT_ERR_NOSPACE; } fdt_packblocks_(fdt, tmp, mem_rsv_size, struct_size, fdt_size_dt_strings(fdt)); memmove(buf, tmp, newsize); fdt_set_magic(buf, FDT_MAGIC); fdt_set_totalsize(buf, bufsize); fdt_set_version(buf, 17); fdt_set_last_comp_version(buf, 16); fdt_set_boot_cpuid_phys(buf, fdt_boot_cpuid_phys(fdt)); return 0; } int fdt_pack(void *fdt) { int mem_rsv_size; FDT_RW_PROBE(fdt); mem_rsv_size = (fdt_num_mem_rsv(fdt)+1) * sizeof(struct fdt_reserve_entry); fdt_packblocks_(fdt, fdt, mem_rsv_size, fdt_size_dt_struct(fdt), fdt_size_dt_strings(fdt)); fdt_set_totalsize(fdt, fdt_data_size_(fdt)); return 0; }
linux-master
scripts/dtc/libfdt/fdt_rw.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2014 David Gibson <[email protected]> * Copyright (C) 2018 embedded brains GmbH */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" static int fdt_cells(const void *fdt, int nodeoffset, const char *name) { const fdt32_t *c; uint32_t val; int len; c = fdt_getprop(fdt, nodeoffset, name, &len); if (!c) return len; if (len != sizeof(*c)) return -FDT_ERR_BADNCELLS; val = fdt32_to_cpu(*c); if (val > FDT_MAX_NCELLS) return -FDT_ERR_BADNCELLS; return (int)val; } int fdt_address_cells(const void *fdt, int nodeoffset) { int val; val = fdt_cells(fdt, nodeoffset, "#address-cells"); if (val == 0) return -FDT_ERR_BADNCELLS; if (val == -FDT_ERR_NOTFOUND) return 2; return val; } int fdt_size_cells(const void *fdt, int nodeoffset) { int val; val = fdt_cells(fdt, nodeoffset, "#size-cells"); if (val == -FDT_ERR_NOTFOUND) return 1; return val; } /* This function assumes that [address|size]_cells is 1 or 2 */ int fdt_appendprop_addrrange(void *fdt, int parent, int nodeoffset, const char *name, uint64_t addr, uint64_t size) { int addr_cells, size_cells, ret; uint8_t data[sizeof(fdt64_t) * 2], *prop; ret = fdt_address_cells(fdt, parent); if (ret < 0) return ret; addr_cells = ret; ret = fdt_size_cells(fdt, parent); if (ret < 0) return ret; size_cells = ret; /* check validity of address */ prop = data; if (addr_cells == 1) { if ((addr > UINT32_MAX) || (((uint64_t) UINT32_MAX + 1 - addr) < size)) return -FDT_ERR_BADVALUE; fdt32_st(prop, (uint32_t)addr); } else if (addr_cells == 2) { fdt64_st(prop, addr); } else { return -FDT_ERR_BADNCELLS; } /* check validity of size */ prop += addr_cells * sizeof(fdt32_t); if (size_cells == 1) { if (size > UINT32_MAX) return -FDT_ERR_BADVALUE; fdt32_st(prop, (uint32_t)size); } else if (size_cells == 2) { fdt64_st(prop, size); } else { return -FDT_ERR_BADNCELLS; } return fdt_appendprop(fdt, nodeoffset, name, data, (addr_cells + size_cells) * sizeof(fdt32_t)); }
linux-master
scripts/dtc/libfdt/fdt_addresses.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" static int fdt_nodename_eq_(const void *fdt, int offset, const char *s, int len) { int olen; const char *p = fdt_get_name(fdt, offset, &olen); if (!p || olen < len) /* short match */ return 0; if (memcmp(p, s, len) != 0) return 0; if (p[len] == '\0') return 1; else if (!memchr(s, '@', len) && (p[len] == '@')) return 1; else return 0; } const char *fdt_get_string(const void *fdt, int stroffset, int *lenp) { int32_t totalsize; uint32_t absoffset; size_t len; int err; const char *s, *n; if (can_assume(VALID_INPUT)) { s = (const char *)fdt + fdt_off_dt_strings(fdt) + stroffset; if (lenp) *lenp = strlen(s); return s; } totalsize = fdt_ro_probe_(fdt); err = totalsize; if (totalsize < 0) goto fail; err = -FDT_ERR_BADOFFSET; absoffset = stroffset + fdt_off_dt_strings(fdt); if (absoffset >= (unsigned)totalsize) goto fail; len = totalsize - absoffset; if (fdt_magic(fdt) == FDT_MAGIC) { if (stroffset < 0) goto fail; if (can_assume(LATEST) || fdt_version(fdt) >= 17) { if ((unsigned)stroffset >= fdt_size_dt_strings(fdt)) goto fail; if ((fdt_size_dt_strings(fdt) - stroffset) < len) len = fdt_size_dt_strings(fdt) - stroffset; } } else if (fdt_magic(fdt) == FDT_SW_MAGIC) { unsigned int sw_stroffset = -stroffset; if ((stroffset >= 0) || (sw_stroffset > fdt_size_dt_strings(fdt))) goto fail; if (sw_stroffset < len) len = sw_stroffset; } else { err = -FDT_ERR_INTERNAL; goto fail; } s = (const char *)fdt + absoffset; n = memchr(s, '\0', len); if (!n) { /* missing terminating NULL */ err = -FDT_ERR_TRUNCATED; goto fail; } if (lenp) *lenp = n - s; return s; fail: if (lenp) *lenp = err; return NULL; } const char *fdt_string(const void *fdt, int stroffset) { return fdt_get_string(fdt, stroffset, NULL); } static int fdt_string_eq_(const void *fdt, int stroffset, const char *s, int len) { int slen; const char *p = fdt_get_string(fdt, stroffset, &slen); return p && (slen == len) && (memcmp(p, s, len) == 0); } int fdt_find_max_phandle(const void *fdt, uint32_t *phandle) { uint32_t max = 0; int offset = -1; while (true) { uint32_t value; offset = fdt_next_node(fdt, offset, NULL); if (offset < 0) { if (offset == -FDT_ERR_NOTFOUND) break; return offset; } value = fdt_get_phandle(fdt, offset); if (value > max) max = value; } if (phandle) *phandle = max; return 0; } int fdt_generate_phandle(const void *fdt, uint32_t *phandle) { uint32_t max; int err; err = fdt_find_max_phandle(fdt, &max); if (err < 0) return err; if (max == FDT_MAX_PHANDLE) return -FDT_ERR_NOPHANDLES; if (phandle) *phandle = max + 1; return 0; } static const struct fdt_reserve_entry *fdt_mem_rsv(const void *fdt, int n) { unsigned int offset = n * sizeof(struct fdt_reserve_entry); unsigned int absoffset = fdt_off_mem_rsvmap(fdt) + offset; if (!can_assume(VALID_INPUT)) { if (absoffset < fdt_off_mem_rsvmap(fdt)) return NULL; if (absoffset > fdt_totalsize(fdt) - sizeof(struct fdt_reserve_entry)) return NULL; } return fdt_mem_rsv_(fdt, n); } int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size) { const struct fdt_reserve_entry *re; FDT_RO_PROBE(fdt); re = fdt_mem_rsv(fdt, n); if (!can_assume(VALID_INPUT) && !re) return -FDT_ERR_BADOFFSET; *address = fdt64_ld_(&re->address); *size = fdt64_ld_(&re->size); return 0; } int fdt_num_mem_rsv(const void *fdt) { int i; const struct fdt_reserve_entry *re; for (i = 0; (re = fdt_mem_rsv(fdt, i)) != NULL; i++) { if (fdt64_ld_(&re->size) == 0) return i; } return -FDT_ERR_TRUNCATED; } static int nextprop_(const void *fdt, int offset) { uint32_t tag; int nextoffset; do { tag = fdt_next_tag(fdt, offset, &nextoffset); switch (tag) { case FDT_END: if (nextoffset >= 0) return -FDT_ERR_BADSTRUCTURE; else return nextoffset; case FDT_PROP: return offset; } offset = nextoffset; } while (tag == FDT_NOP); return -FDT_ERR_NOTFOUND; } int fdt_subnode_offset_namelen(const void *fdt, int offset, const char *name, int namelen) { int depth; FDT_RO_PROBE(fdt); for (depth = 0; (offset >= 0) && (depth >= 0); offset = fdt_next_node(fdt, offset, &depth)) if ((depth == 1) && fdt_nodename_eq_(fdt, offset, name, namelen)) return offset; if (depth < 0) return -FDT_ERR_NOTFOUND; return offset; /* error */ } int fdt_subnode_offset(const void *fdt, int parentoffset, const char *name) { return fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name)); } int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen) { const char *end = path + namelen; const char *p = path; int offset = 0; FDT_RO_PROBE(fdt); /* see if we have an alias */ if (*path != '/') { const char *q = memchr(path, '/', end - p); if (!q) q = end; p = fdt_get_alias_namelen(fdt, p, q - p); if (!p) return -FDT_ERR_BADPATH; offset = fdt_path_offset(fdt, p); p = q; } while (p < end) { const char *q; while (*p == '/') { p++; if (p == end) return offset; } q = memchr(p, '/', end - p); if (! q) q = end; offset = fdt_subnode_offset_namelen(fdt, offset, p, q-p); if (offset < 0) return offset; p = q; } return offset; } int fdt_path_offset(const void *fdt, const char *path) { return fdt_path_offset_namelen(fdt, path, strlen(path)); } const char *fdt_get_name(const void *fdt, int nodeoffset, int *len) { const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset); const char *nameptr; int err; if (((err = fdt_ro_probe_(fdt)) < 0) || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0)) goto fail; nameptr = nh->name; if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) { /* * For old FDT versions, match the naming conventions of V16: * give only the leaf name (after all /). The actual tree * contents are loosely checked. */ const char *leaf; leaf = strrchr(nameptr, '/'); if (leaf == NULL) { err = -FDT_ERR_BADSTRUCTURE; goto fail; } nameptr = leaf+1; } if (len) *len = strlen(nameptr); return nameptr; fail: if (len) *len = err; return NULL; } int fdt_first_property_offset(const void *fdt, int nodeoffset) { int offset; if ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0) return offset; return nextprop_(fdt, offset); } int fdt_next_property_offset(const void *fdt, int offset) { if ((offset = fdt_check_prop_offset_(fdt, offset)) < 0) return offset; return nextprop_(fdt, offset); } static const struct fdt_property *fdt_get_property_by_offset_(const void *fdt, int offset, int *lenp) { int err; const struct fdt_property *prop; if (!can_assume(VALID_INPUT) && (err = fdt_check_prop_offset_(fdt, offset)) < 0) { if (lenp) *lenp = err; return NULL; } prop = fdt_offset_ptr_(fdt, offset); if (lenp) *lenp = fdt32_ld_(&prop->len); return prop; } const struct fdt_property *fdt_get_property_by_offset(const void *fdt, int offset, int *lenp) { /* Prior to version 16, properties may need realignment * and this API does not work. fdt_getprop_*() will, however. */ if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) { if (lenp) *lenp = -FDT_ERR_BADVERSION; return NULL; } return fdt_get_property_by_offset_(fdt, offset, lenp); } static const struct fdt_property *fdt_get_property_namelen_(const void *fdt, int offset, const char *name, int namelen, int *lenp, int *poffset) { for (offset = fdt_first_property_offset(fdt, offset); (offset >= 0); (offset = fdt_next_property_offset(fdt, offset))) { const struct fdt_property *prop; prop = fdt_get_property_by_offset_(fdt, offset, lenp); if (!can_assume(LIBFDT_FLAWLESS) && !prop) { offset = -FDT_ERR_INTERNAL; break; } if (fdt_string_eq_(fdt, fdt32_ld_(&prop->nameoff), name, namelen)) { if (poffset) *poffset = offset; return prop; } } if (lenp) *lenp = offset; return NULL; } const struct fdt_property *fdt_get_property_namelen(const void *fdt, int offset, const char *name, int namelen, int *lenp) { /* Prior to version 16, properties may need realignment * and this API does not work. fdt_getprop_*() will, however. */ if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) { if (lenp) *lenp = -FDT_ERR_BADVERSION; return NULL; } return fdt_get_property_namelen_(fdt, offset, name, namelen, lenp, NULL); } const struct fdt_property *fdt_get_property(const void *fdt, int nodeoffset, const char *name, int *lenp) { return fdt_get_property_namelen(fdt, nodeoffset, name, strlen(name), lenp); } const void *fdt_getprop_namelen(const void *fdt, int nodeoffset, const char *name, int namelen, int *lenp) { int poffset; const struct fdt_property *prop; prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen, lenp, &poffset); if (!prop) return NULL; /* Handle realignment */ if (!can_assume(LATEST) && fdt_version(fdt) < 0x10 && (poffset + sizeof(*prop)) % 8 && fdt32_ld_(&prop->len) >= 8) return prop->data + 4; return prop->data; } const void *fdt_getprop_by_offset(const void *fdt, int offset, const char **namep, int *lenp) { const struct fdt_property *prop; prop = fdt_get_property_by_offset_(fdt, offset, lenp); if (!prop) return NULL; if (namep) { const char *name; int namelen; if (!can_assume(VALID_INPUT)) { name = fdt_get_string(fdt, fdt32_ld_(&prop->nameoff), &namelen); *namep = name; if (!name) { if (lenp) *lenp = namelen; return NULL; } } else { *namep = fdt_string(fdt, fdt32_ld_(&prop->nameoff)); } } /* Handle realignment */ if (!can_assume(LATEST) && fdt_version(fdt) < 0x10 && (offset + sizeof(*prop)) % 8 && fdt32_ld_(&prop->len) >= 8) return prop->data + 4; return prop->data; } const void *fdt_getprop(const void *fdt, int nodeoffset, const char *name, int *lenp) { return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp); } uint32_t fdt_get_phandle(const void *fdt, int nodeoffset) { const fdt32_t *php; int len; /* FIXME: This is a bit sub-optimal, since we potentially scan * over all the properties twice. */ php = fdt_getprop(fdt, nodeoffset, "phandle", &len); if (!php || (len != sizeof(*php))) { php = fdt_getprop(fdt, nodeoffset, "linux,phandle", &len); if (!php || (len != sizeof(*php))) return 0; } return fdt32_ld_(php); } const char *fdt_get_alias_namelen(const void *fdt, const char *name, int namelen) { int aliasoffset; aliasoffset = fdt_path_offset(fdt, "/aliases"); if (aliasoffset < 0) return NULL; return fdt_getprop_namelen(fdt, aliasoffset, name, namelen, NULL); } const char *fdt_get_alias(const void *fdt, const char *name) { return fdt_get_alias_namelen(fdt, name, strlen(name)); } int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen) { int pdepth = 0, p = 0; int offset, depth, namelen; const char *name; FDT_RO_PROBE(fdt); if (buflen < 2) return -FDT_ERR_NOSPACE; for (offset = 0, depth = 0; (offset >= 0) && (offset <= nodeoffset); offset = fdt_next_node(fdt, offset, &depth)) { while (pdepth > depth) { do { p--; } while (buf[p-1] != '/'); pdepth--; } if (pdepth >= depth) { name = fdt_get_name(fdt, offset, &namelen); if (!name) return namelen; if ((p + namelen + 1) <= buflen) { memcpy(buf + p, name, namelen); p += namelen; buf[p++] = '/'; pdepth++; } } if (offset == nodeoffset) { if (pdepth < (depth + 1)) return -FDT_ERR_NOSPACE; if (p > 1) /* special case so that root path is "/", not "" */ p--; buf[p] = '\0'; return 0; } } if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0)) return -FDT_ERR_BADOFFSET; else if (offset == -FDT_ERR_BADOFFSET) return -FDT_ERR_BADSTRUCTURE; return offset; /* error from fdt_next_node() */ } int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset, int supernodedepth, int *nodedepth) { int offset, depth; int supernodeoffset = -FDT_ERR_INTERNAL; FDT_RO_PROBE(fdt); if (supernodedepth < 0) return -FDT_ERR_NOTFOUND; for (offset = 0, depth = 0; (offset >= 0) && (offset <= nodeoffset); offset = fdt_next_node(fdt, offset, &depth)) { if (depth == supernodedepth) supernodeoffset = offset; if (offset == nodeoffset) { if (nodedepth) *nodedepth = depth; if (supernodedepth > depth) return -FDT_ERR_NOTFOUND; else return supernodeoffset; } } if (!can_assume(VALID_INPUT)) { if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0)) return -FDT_ERR_BADOFFSET; else if (offset == -FDT_ERR_BADOFFSET) return -FDT_ERR_BADSTRUCTURE; } return offset; /* error from fdt_next_node() */ } int fdt_node_depth(const void *fdt, int nodeoffset) { int nodedepth; int err; err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth); if (err) return (can_assume(LIBFDT_FLAWLESS) || err < 0) ? err : -FDT_ERR_INTERNAL; return nodedepth; } int fdt_parent_offset(const void *fdt, int nodeoffset) { int nodedepth = fdt_node_depth(fdt, nodeoffset); if (nodedepth < 0) return nodedepth; return fdt_supernode_atdepth_offset(fdt, nodeoffset, nodedepth - 1, NULL); } int fdt_node_offset_by_prop_value(const void *fdt, int startoffset, const char *propname, const void *propval, int proplen) { int offset; const void *val; int len; FDT_RO_PROBE(fdt); /* FIXME: The algorithm here is pretty horrible: we scan each * property of a node in fdt_getprop(), then if that didn't * find what we want, we scan over them again making our way * to the next node. Still it's the easiest to implement * approach; performance can come later. */ for (offset = fdt_next_node(fdt, startoffset, NULL); offset >= 0; offset = fdt_next_node(fdt, offset, NULL)) { val = fdt_getprop(fdt, offset, propname, &len); if (val && (len == proplen) && (memcmp(val, propval, len) == 0)) return offset; } return offset; /* error from fdt_next_node() */ } int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle) { int offset; if ((phandle == 0) || (phandle == ~0U)) return -FDT_ERR_BADPHANDLE; FDT_RO_PROBE(fdt); /* FIXME: The algorithm here is pretty horrible: we * potentially scan each property of a node in * fdt_get_phandle(), then if that didn't find what * we want, we scan over them again making our way to the next * node. Still it's the easiest to implement approach; * performance can come later. */ for (offset = fdt_next_node(fdt, -1, NULL); offset >= 0; offset = fdt_next_node(fdt, offset, NULL)) { if (fdt_get_phandle(fdt, offset) == phandle) return offset; } return offset; /* error from fdt_next_node() */ } int fdt_stringlist_contains(const char *strlist, int listlen, const char *str) { int len = strlen(str); const char *p; while (listlen >= len) { if (memcmp(str, strlist, len+1) == 0) return 1; p = memchr(strlist, '\0', listlen); if (!p) return 0; /* malformed strlist.. */ listlen -= (p-strlist) + 1; strlist = p + 1; } return 0; } int fdt_stringlist_count(const void *fdt, int nodeoffset, const char *property) { const char *list, *end; int length, count = 0; list = fdt_getprop(fdt, nodeoffset, property, &length); if (!list) return length; end = list + length; while (list < end) { length = strnlen(list, end - list) + 1; /* Abort if the last string isn't properly NUL-terminated. */ if (list + length > end) return -FDT_ERR_BADVALUE; list += length; count++; } return count; } int fdt_stringlist_search(const void *fdt, int nodeoffset, const char *property, const char *string) { int length, len, idx = 0; const char *list, *end; list = fdt_getprop(fdt, nodeoffset, property, &length); if (!list) return length; len = strlen(string) + 1; end = list + length; while (list < end) { length = strnlen(list, end - list) + 1; /* Abort if the last string isn't properly NUL-terminated. */ if (list + length > end) return -FDT_ERR_BADVALUE; if (length == len && memcmp(list, string, length) == 0) return idx; list += length; idx++; } return -FDT_ERR_NOTFOUND; } const char *fdt_stringlist_get(const void *fdt, int nodeoffset, const char *property, int idx, int *lenp) { const char *list, *end; int length; list = fdt_getprop(fdt, nodeoffset, property, &length); if (!list) { if (lenp) *lenp = length; return NULL; } end = list + length; while (list < end) { length = strnlen(list, end - list) + 1; /* Abort if the last string isn't properly NUL-terminated. */ if (list + length > end) { if (lenp) *lenp = -FDT_ERR_BADVALUE; return NULL; } if (idx == 0) { if (lenp) *lenp = length - 1; return list; } list += length; idx--; } if (lenp) *lenp = -FDT_ERR_NOTFOUND; return NULL; } int fdt_node_check_compatible(const void *fdt, int nodeoffset, const char *compatible) { const void *prop; int len; prop = fdt_getprop(fdt, nodeoffset, "compatible", &len); if (!prop) return len; return !fdt_stringlist_contains(prop, len, compatible); } int fdt_node_offset_by_compatible(const void *fdt, int startoffset, const char *compatible) { int offset, err; FDT_RO_PROBE(fdt); /* FIXME: The algorithm here is pretty horrible: we scan each * property of a node in fdt_node_check_compatible(), then if * that didn't find what we want, we scan over them again * making our way to the next node. Still it's the easiest to * implement approach; performance can come later. */ for (offset = fdt_next_node(fdt, startoffset, NULL); offset >= 0; offset = fdt_next_node(fdt, offset, NULL)) { err = fdt_node_check_compatible(fdt, offset, compatible); if ((err < 0) && (err != -FDT_ERR_NOTFOUND)) return err; else if (err == 0) return offset; } return offset; /* error from fdt_next_node() */ }
linux-master
scripts/dtc/libfdt/fdt_ro.c
// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) /* * libfdt - Flat Device Tree manipulation * Copyright (C) 2006 David Gibson, IBM Corporation. */ #include "libfdt_env.h" #include <fdt.h> #include <libfdt.h> #include "libfdt_internal.h" static int fdt_sw_probe_(void *fdt) { if (!can_assume(VALID_INPUT)) { if (fdt_magic(fdt) == FDT_MAGIC) return -FDT_ERR_BADSTATE; else if (fdt_magic(fdt) != FDT_SW_MAGIC) return -FDT_ERR_BADMAGIC; } return 0; } #define FDT_SW_PROBE(fdt) \ { \ int err; \ if ((err = fdt_sw_probe_(fdt)) != 0) \ return err; \ } /* 'memrsv' state: Initial state after fdt_create() * * Allowed functions: * fdt_add_reservemap_entry() * fdt_finish_reservemap() [moves to 'struct' state] */ static int fdt_sw_probe_memrsv_(void *fdt) { int err = fdt_sw_probe_(fdt); if (err) return err; if (!can_assume(VALID_INPUT) && fdt_off_dt_strings(fdt) != 0) return -FDT_ERR_BADSTATE; return 0; } #define FDT_SW_PROBE_MEMRSV(fdt) \ { \ int err; \ if ((err = fdt_sw_probe_memrsv_(fdt)) != 0) \ return err; \ } /* 'struct' state: Enter this state after fdt_finish_reservemap() * * Allowed functions: * fdt_begin_node() * fdt_end_node() * fdt_property*() * fdt_finish() [moves to 'complete' state] */ static int fdt_sw_probe_struct_(void *fdt) { int err = fdt_sw_probe_(fdt); if (err) return err; if (!can_assume(VALID_INPUT) && fdt_off_dt_strings(fdt) != fdt_totalsize(fdt)) return -FDT_ERR_BADSTATE; return 0; } #define FDT_SW_PROBE_STRUCT(fdt) \ { \ int err; \ if ((err = fdt_sw_probe_struct_(fdt)) != 0) \ return err; \ } static inline uint32_t sw_flags(void *fdt) { /* assert: (fdt_magic(fdt) == FDT_SW_MAGIC) */ return fdt_last_comp_version(fdt); } /* 'complete' state: Enter this state after fdt_finish() * * Allowed functions: none */ static void *fdt_grab_space_(void *fdt, size_t len) { unsigned int offset = fdt_size_dt_struct(fdt); unsigned int spaceleft; spaceleft = fdt_totalsize(fdt) - fdt_off_dt_struct(fdt) - fdt_size_dt_strings(fdt); if ((offset + len < offset) || (offset + len > spaceleft)) return NULL; fdt_set_size_dt_struct(fdt, offset + len); return fdt_offset_ptr_w_(fdt, offset); } int fdt_create_with_flags(void *buf, int bufsize, uint32_t flags) { const int hdrsize = FDT_ALIGN(sizeof(struct fdt_header), sizeof(struct fdt_reserve_entry)); void *fdt = buf; if (bufsize < hdrsize) return -FDT_ERR_NOSPACE; if (flags & ~FDT_CREATE_FLAGS_ALL) return -FDT_ERR_BADFLAGS; memset(buf, 0, bufsize); /* * magic and last_comp_version keep intermediate state during the fdt * creation process, which is replaced with the proper FDT format by * fdt_finish(). * * flags should be accessed with sw_flags(). */ fdt_set_magic(fdt, FDT_SW_MAGIC); fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION); fdt_set_last_comp_version(fdt, flags); fdt_set_totalsize(fdt, bufsize); fdt_set_off_mem_rsvmap(fdt, hdrsize); fdt_set_off_dt_struct(fdt, fdt_off_mem_rsvmap(fdt)); fdt_set_off_dt_strings(fdt, 0); return 0; } int fdt_create(void *buf, int bufsize) { return fdt_create_with_flags(buf, bufsize, 0); } int fdt_resize(void *fdt, void *buf, int bufsize) { size_t headsize, tailsize; char *oldtail, *newtail; FDT_SW_PROBE(fdt); if (bufsize < 0) return -FDT_ERR_NOSPACE; headsize = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt); tailsize = fdt_size_dt_strings(fdt); if (!can_assume(VALID_DTB) && headsize + tailsize > fdt_totalsize(fdt)) return -FDT_ERR_INTERNAL; if ((headsize + tailsize) > (unsigned)bufsize) return -FDT_ERR_NOSPACE; oldtail = (char *)fdt + fdt_totalsize(fdt) - tailsize; newtail = (char *)buf + bufsize - tailsize; /* Two cases to avoid clobbering data if the old and new * buffers partially overlap */ if (buf <= fdt) { memmove(buf, fdt, headsize); memmove(newtail, oldtail, tailsize); } else { memmove(newtail, oldtail, tailsize); memmove(buf, fdt, headsize); } fdt_set_totalsize(buf, bufsize); if (fdt_off_dt_strings(buf)) fdt_set_off_dt_strings(buf, bufsize); return 0; } int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size) { struct fdt_reserve_entry *re; int offset; FDT_SW_PROBE_MEMRSV(fdt); offset = fdt_off_dt_struct(fdt); if ((offset + sizeof(*re)) > fdt_totalsize(fdt)) return -FDT_ERR_NOSPACE; re = (struct fdt_reserve_entry *)((char *)fdt + offset); re->address = cpu_to_fdt64(addr); re->size = cpu_to_fdt64(size); fdt_set_off_dt_struct(fdt, offset + sizeof(*re)); return 0; } int fdt_finish_reservemap(void *fdt) { int err = fdt_add_reservemap_entry(fdt, 0, 0); if (err) return err; fdt_set_off_dt_strings(fdt, fdt_totalsize(fdt)); return 0; } int fdt_begin_node(void *fdt, const char *name) { struct fdt_node_header *nh; int namelen; FDT_SW_PROBE_STRUCT(fdt); namelen = strlen(name) + 1; nh = fdt_grab_space_(fdt, sizeof(*nh) + FDT_TAGALIGN(namelen)); if (! nh) return -FDT_ERR_NOSPACE; nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE); memcpy(nh->name, name, namelen); return 0; } int fdt_end_node(void *fdt) { fdt32_t *en; FDT_SW_PROBE_STRUCT(fdt); en = fdt_grab_space_(fdt, FDT_TAGSIZE); if (! en) return -FDT_ERR_NOSPACE; *en = cpu_to_fdt32(FDT_END_NODE); return 0; } static int fdt_add_string_(void *fdt, const char *s) { char *strtab = (char *)fdt + fdt_totalsize(fdt); unsigned int strtabsize = fdt_size_dt_strings(fdt); unsigned int len = strlen(s) + 1; unsigned int struct_top, offset; offset = strtabsize + len; struct_top = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt); if (fdt_totalsize(fdt) - offset < struct_top) return 0; /* no more room :( */ memcpy(strtab - offset, s, len); fdt_set_size_dt_strings(fdt, strtabsize + len); return -offset; } /* Must only be used to roll back in case of error */ static void fdt_del_last_string_(void *fdt, const char *s) { int strtabsize = fdt_size_dt_strings(fdt); int len = strlen(s) + 1; fdt_set_size_dt_strings(fdt, strtabsize - len); } static int fdt_find_add_string_(void *fdt, const char *s, int *allocated) { char *strtab = (char *)fdt + fdt_totalsize(fdt); int strtabsize = fdt_size_dt_strings(fdt); const char *p; *allocated = 0; p = fdt_find_string_(strtab - strtabsize, strtabsize, s); if (p) return p - strtab; *allocated = 1; return fdt_add_string_(fdt, s); } int fdt_property_placeholder(void *fdt, const char *name, int len, void **valp) { struct fdt_property *prop; int nameoff; int allocated; FDT_SW_PROBE_STRUCT(fdt); /* String de-duplication can be slow, _NO_NAME_DEDUP skips it */ if (sw_flags(fdt) & FDT_CREATE_FLAG_NO_NAME_DEDUP) { allocated = 1; nameoff = fdt_add_string_(fdt, name); } else { nameoff = fdt_find_add_string_(fdt, name, &allocated); } if (nameoff == 0) return -FDT_ERR_NOSPACE; prop = fdt_grab_space_(fdt, sizeof(*prop) + FDT_TAGALIGN(len)); if (! prop) { if (allocated) fdt_del_last_string_(fdt, name); return -FDT_ERR_NOSPACE; } prop->tag = cpu_to_fdt32(FDT_PROP); prop->nameoff = cpu_to_fdt32(nameoff); prop->len = cpu_to_fdt32(len); *valp = prop->data; return 0; } int fdt_property(void *fdt, const char *name, const void *val, int len) { void *ptr; int ret; ret = fdt_property_placeholder(fdt, name, len, &ptr); if (ret) return ret; memcpy(ptr, val, len); return 0; } int fdt_finish(void *fdt) { char *p = (char *)fdt; fdt32_t *end; int oldstroffset, newstroffset; uint32_t tag; int offset, nextoffset; FDT_SW_PROBE_STRUCT(fdt); /* Add terminator */ end = fdt_grab_space_(fdt, sizeof(*end)); if (! end) return -FDT_ERR_NOSPACE; *end = cpu_to_fdt32(FDT_END); /* Relocate the string table */ oldstroffset = fdt_totalsize(fdt) - fdt_size_dt_strings(fdt); newstroffset = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt); memmove(p + newstroffset, p + oldstroffset, fdt_size_dt_strings(fdt)); fdt_set_off_dt_strings(fdt, newstroffset); /* Walk the structure, correcting string offsets */ offset = 0; while ((tag = fdt_next_tag(fdt, offset, &nextoffset)) != FDT_END) { if (tag == FDT_PROP) { struct fdt_property *prop = fdt_offset_ptr_w_(fdt, offset); int nameoff; nameoff = fdt32_to_cpu(prop->nameoff); nameoff += fdt_size_dt_strings(fdt); prop->nameoff = cpu_to_fdt32(nameoff); } offset = nextoffset; } if (nextoffset < 0) return nextoffset; /* Finally, adjust the header */ fdt_set_totalsize(fdt, newstroffset + fdt_size_dt_strings(fdt)); /* And fix up fields that were keeping intermediate state. */ fdt_set_last_comp_version(fdt, FDT_LAST_COMPATIBLE_VERSION); fdt_set_magic(fdt, FDT_MAGIC); return 0; }
linux-master
scripts/dtc/libfdt/fdt_sw.c
// SPDX-License-Identifier: GPL-2.0 #include "gcc-common.h" __visible int plugin_is_GPL_compatible; static unsigned int canary_offset; static unsigned int arm_pertask_ssp_rtl_execute(void) { rtx_insn *insn; for (insn = get_insns(); insn; insn = NEXT_INSN(insn)) { const char *sym; rtx body; rtx current; /* * Find a SET insn involving a SYMBOL_REF to __stack_chk_guard */ if (!INSN_P(insn)) continue; body = PATTERN(insn); if (GET_CODE(body) != SET || GET_CODE(SET_SRC(body)) != SYMBOL_REF) continue; sym = XSTR(SET_SRC(body), 0); if (strcmp(sym, "__stack_chk_guard")) continue; /* * Replace the source of the SET insn with an expression that * produces the address of the current task's stack canary value */ current = gen_reg_rtx(Pmode); emit_insn_before(gen_load_tp_hard(current), insn); SET_SRC(body) = gen_rtx_PLUS(Pmode, current, GEN_INT(canary_offset)); } return 0; } #define PASS_NAME arm_pertask_ssp_rtl #define NO_GATE #include "gcc-generate-rtl-pass.h" #if BUILDING_GCC_VERSION >= 9000 static bool no(void) { return false; } static void arm_pertask_ssp_start_unit(void *gcc_data, void *user_data) { targetm.have_stack_protect_combined_set = no; targetm.have_stack_protect_combined_test = no; } #endif __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument *argv = plugin_info->argv; int i; if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } for (i = 0; i < argc; ++i) { if (!strcmp(argv[i].key, "disable")) return 0; /* all remaining options require a value */ if (!argv[i].value) { error(G_("no value supplied for option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); return 1; } if (!strcmp(argv[i].key, "offset")) { canary_offset = atoi(argv[i].value); continue; } error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); return 1; } PASS_INFO(arm_pertask_ssp_rtl, "expand", 1, PASS_POS_INSERT_AFTER); register_callback(plugin_info->base_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &arm_pertask_ssp_rtl_pass_info); #if BUILDING_GCC_VERSION >= 9000 register_callback(plugin_info->base_name, PLUGIN_START_UNIT, arm_pertask_ssp_start_unit, NULL); #endif return 0; }
linux-master
scripts/gcc-plugins/arm_ssp_per_task_plugin.c
/* * Copyright 2011-2016 by Emese Revfy <[email protected]> * Licensed under the GPL v2, or (at your option) v3 * * Homepage: * https://github.com/ephox-gcc-plugins/sancov * * This plugin inserts a __sanitizer_cov_trace_pc() call at the start of basic blocks. * It supports all gcc versions with plugin support (from gcc-4.5 on). * It is based on the commit "Add fuzzing coverage support" by Dmitry Vyukov <[email protected]>. * * You can read about it more here: * https://gcc.gnu.org/viewcvs/gcc?limit_changes=0&view=revision&revision=231296 * https://lwn.net/Articles/674854/ * https://github.com/google/syzkaller * https://lwn.net/Articles/677764/ * * Usage: * make run */ #include "gcc-common.h" __visible int plugin_is_GPL_compatible; tree sancov_fndecl; static struct plugin_info sancov_plugin_info = { .version = PLUGIN_VERSION, .help = "sancov plugin\n", }; static unsigned int sancov_execute(void) { basic_block bb; /* Remove this line when this plugin and kcov will be in the kernel. if (!strcmp(DECL_NAME_POINTER(current_function_decl), DECL_NAME_POINTER(sancov_fndecl))) return 0; */ FOR_EACH_BB_FN(bb, cfun) { const_gimple stmt; gcall *gcall; gimple_stmt_iterator gsi = gsi_after_labels(bb); if (gsi_end_p(gsi)) continue; stmt = gsi_stmt(gsi); gcall = as_a_gcall(gimple_build_call(sancov_fndecl, 0)); gimple_set_location(gcall, gimple_location(stmt)); gsi_insert_before(&gsi, gcall, GSI_SAME_STMT); } return 0; } #define PASS_NAME sancov #define NO_GATE #define TODO_FLAGS_FINISH TODO_dump_func | TODO_verify_stmts | TODO_update_ssa_no_phi | TODO_verify_flow #include "gcc-generate-gimple-pass.h" static void sancov_start_unit(void __unused *gcc_data, void __unused *user_data) { tree leaf_attr, nothrow_attr; tree BT_FN_VOID = build_function_type_list(void_type_node, NULL_TREE); sancov_fndecl = build_fn_decl("__sanitizer_cov_trace_pc", BT_FN_VOID); DECL_ASSEMBLER_NAME(sancov_fndecl); TREE_PUBLIC(sancov_fndecl) = 1; DECL_EXTERNAL(sancov_fndecl) = 1; DECL_ARTIFICIAL(sancov_fndecl) = 1; DECL_PRESERVE_P(sancov_fndecl) = 1; DECL_UNINLINABLE(sancov_fndecl) = 1; TREE_USED(sancov_fndecl) = 1; nothrow_attr = tree_cons(get_identifier("nothrow"), NULL, NULL); decl_attributes(&sancov_fndecl, nothrow_attr, 0); gcc_assert(TREE_NOTHROW(sancov_fndecl)); leaf_attr = tree_cons(get_identifier("leaf"), NULL, NULL); decl_attributes(&sancov_fndecl, leaf_attr, 0); } __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { int i; const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument * const argv = plugin_info->argv; bool enable = true; static const struct ggc_root_tab gt_ggc_r_gt_sancov[] = { { .base = &sancov_fndecl, .nelt = 1, .stride = sizeof(sancov_fndecl), .cb = &gt_ggc_mx_tree_node, .pchw = &gt_pch_nx_tree_node }, LAST_GGC_ROOT_TAB }; /* BBs can be split afterwards?? */ PASS_INFO(sancov, "asan", 0, PASS_POS_INSERT_BEFORE); if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } for (i = 0; i < argc; ++i) { if (!strcmp(argv[i].key, "no-sancov")) { enable = false; continue; } error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); } register_callback(plugin_name, PLUGIN_INFO, NULL, &sancov_plugin_info); if (!enable) return 0; #if BUILDING_GCC_VERSION < 6000 register_callback(plugin_name, PLUGIN_START_UNIT, &sancov_start_unit, NULL); register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS, NULL, (void *)&gt_ggc_r_gt_sancov); register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &sancov_pass_info); #endif return 0; }
linux-master
scripts/gcc-plugins/sancov_plugin.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2012-2016 by the PaX Team <[email protected]> * Copyright 2016 by Emese Revfy <[email protected]> * * Note: the choice of the license means that the compilation process is * NOT 'eligible' as defined by gcc's library exception to the GPL v3, * but for the kernel it doesn't matter since it doesn't link against * any of the gcc libraries * * This gcc plugin helps generate a little bit of entropy from program state, * used throughout the uptime of the kernel. Here is an instrumentation example: * * before: * void __latent_entropy test(int argc, char *argv[]) * { * if (argc <= 1) * printf("%s: no command arguments :(\n", *argv); * else * printf("%s: %d command arguments!\n", *argv, args - 1); * } * * after: * void __latent_entropy test(int argc, char *argv[]) * { * // latent_entropy_execute() 1. * unsigned long local_entropy; * // init_local_entropy() 1. * void *local_entropy_frameaddr; * // init_local_entropy() 3. * unsigned long tmp_latent_entropy; * * // init_local_entropy() 2. * local_entropy_frameaddr = __builtin_frame_address(0); * local_entropy = (unsigned long) local_entropy_frameaddr; * * // init_local_entropy() 4. * tmp_latent_entropy = latent_entropy; * // init_local_entropy() 5. * local_entropy ^= tmp_latent_entropy; * * // latent_entropy_execute() 3. * if (argc <= 1) { * // perturb_local_entropy() * local_entropy += 4623067384293424948; * printf("%s: no command arguments :(\n", *argv); * // perturb_local_entropy() * } else { * local_entropy ^= 3896280633962944730; * printf("%s: %d command arguments!\n", *argv, args - 1); * } * * // latent_entropy_execute() 4. * tmp_latent_entropy = rol(tmp_latent_entropy, local_entropy); * latent_entropy = tmp_latent_entropy; * } * * TODO: * - add ipa pass to identify not explicitly marked candidate functions * - mix in more program state (function arguments/return values, * loop variables, etc) * - more instrumentation control via attribute parameters * * BUGS: * - none known * * Options: * -fplugin-arg-latent_entropy_plugin-disable * * Attribute: __attribute__((latent_entropy)) * The latent_entropy gcc attribute can be only on functions and variables. * If it is on a function then the plugin will instrument it. If the attribute * is on a variable then the plugin will initialize it with a random value. * The variable must be an integer, an integer array type or a structure * with integer fields. */ #include "gcc-common.h" __visible int plugin_is_GPL_compatible; static GTY(()) tree latent_entropy_decl; static struct plugin_info latent_entropy_plugin_info = { .version = PLUGIN_VERSION, .help = "disable\tturn off latent entropy instrumentation\n", }; static unsigned HOST_WIDE_INT deterministic_seed; static unsigned HOST_WIDE_INT rnd_buf[32]; static size_t rnd_idx = ARRAY_SIZE(rnd_buf); static int urandom_fd = -1; static unsigned HOST_WIDE_INT get_random_const(void) { if (deterministic_seed) { unsigned HOST_WIDE_INT w = deterministic_seed; w ^= w << 13; w ^= w >> 7; w ^= w << 17; deterministic_seed = w; return deterministic_seed; } if (urandom_fd < 0) { urandom_fd = open("/dev/urandom", O_RDONLY); gcc_assert(urandom_fd >= 0); } if (rnd_idx >= ARRAY_SIZE(rnd_buf)) { gcc_assert(read(urandom_fd, rnd_buf, sizeof(rnd_buf)) == sizeof(rnd_buf)); rnd_idx = 0; } return rnd_buf[rnd_idx++]; } static tree tree_get_random_const(tree type) { unsigned long long mask; mask = 1ULL << (TREE_INT_CST_LOW(TYPE_SIZE(type)) - 1); mask = 2 * (mask - 1) + 1; if (TYPE_UNSIGNED(type)) return build_int_cstu(type, mask & get_random_const()); return build_int_cst(type, mask & get_random_const()); } static tree handle_latent_entropy_attribute(tree *node, tree name, tree args __unused, int flags __unused, bool *no_add_attrs) { tree type; vec<constructor_elt, va_gc> *vals; switch (TREE_CODE(*node)) { default: *no_add_attrs = true; error("%qE attribute only applies to functions and variables", name); break; case VAR_DECL: if (DECL_INITIAL(*node)) { *no_add_attrs = true; error("variable %qD with %qE attribute must not be initialized", *node, name); break; } if (!TREE_STATIC(*node)) { *no_add_attrs = true; error("variable %qD with %qE attribute must not be local", *node, name); break; } type = TREE_TYPE(*node); switch (TREE_CODE(type)) { default: *no_add_attrs = true; error("variable %qD with %qE attribute must be an integer or a fixed length integer array type or a fixed sized structure with integer fields", *node, name); break; case RECORD_TYPE: { tree fld, lst = TYPE_FIELDS(type); unsigned int nelt = 0; for (fld = lst; fld; nelt++, fld = TREE_CHAIN(fld)) { tree fieldtype; fieldtype = TREE_TYPE(fld); if (TREE_CODE(fieldtype) == INTEGER_TYPE) continue; *no_add_attrs = true; error("structure variable %qD with %qE attribute has a non-integer field %qE", *node, name, fld); break; } if (fld) break; vec_alloc(vals, nelt); for (fld = lst; fld; fld = TREE_CHAIN(fld)) { tree random_const, fld_t = TREE_TYPE(fld); random_const = tree_get_random_const(fld_t); CONSTRUCTOR_APPEND_ELT(vals, fld, random_const); } /* Initialize the fields with random constants */ DECL_INITIAL(*node) = build_constructor(type, vals); break; } /* Initialize the variable with a random constant */ case INTEGER_TYPE: DECL_INITIAL(*node) = tree_get_random_const(type); break; case ARRAY_TYPE: { tree elt_type, array_size, elt_size; unsigned int i, nelt; HOST_WIDE_INT array_size_int, elt_size_int; elt_type = TREE_TYPE(type); elt_size = TYPE_SIZE_UNIT(TREE_TYPE(type)); array_size = TYPE_SIZE_UNIT(type); if (TREE_CODE(elt_type) != INTEGER_TYPE || !array_size || TREE_CODE(array_size) != INTEGER_CST) { *no_add_attrs = true; error("array variable %qD with %qE attribute must be a fixed length integer array type", *node, name); break; } array_size_int = TREE_INT_CST_LOW(array_size); elt_size_int = TREE_INT_CST_LOW(elt_size); nelt = array_size_int / elt_size_int; vec_alloc(vals, nelt); for (i = 0; i < nelt; i++) { tree cst = size_int(i); tree rand_cst = tree_get_random_const(elt_type); CONSTRUCTOR_APPEND_ELT(vals, cst, rand_cst); } /* * Initialize the elements of the array with random * constants */ DECL_INITIAL(*node) = build_constructor(type, vals); break; } } break; case FUNCTION_DECL: break; } return NULL_TREE; } static struct attribute_spec latent_entropy_attr = { }; static void register_attributes(void *event_data __unused, void *data __unused) { latent_entropy_attr.name = "latent_entropy"; latent_entropy_attr.decl_required = true; latent_entropy_attr.handler = handle_latent_entropy_attribute; register_attribute(&latent_entropy_attr); } static bool latent_entropy_gate(void) { tree list; /* don't bother with noreturn functions for now */ if (TREE_THIS_VOLATILE(current_function_decl)) return false; /* gcc-4.5 doesn't discover some trivial noreturn functions */ if (EDGE_COUNT(EXIT_BLOCK_PTR_FOR_FN(cfun)->preds) == 0) return false; list = DECL_ATTRIBUTES(current_function_decl); return lookup_attribute("latent_entropy", list) != NULL_TREE; } static tree create_var(tree type, const char *name) { tree var; var = create_tmp_var(type, name); add_referenced_var(var); mark_sym_for_renaming(var); return var; } /* * Set up the next operation and its constant operand to use in the latent * entropy PRNG. When RHS is specified, the request is for perturbing the * local latent entropy variable, otherwise it is for perturbing the global * latent entropy variable where the two operands are already given by the * local and global latent entropy variables themselves. * * The operation is one of add/xor/rol when instrumenting the local entropy * variable and one of add/xor when perturbing the global entropy variable. * Rotation is not used for the latter case because it would transmit less * entropy to the global variable than the other two operations. */ static enum tree_code get_op(tree *rhs) { static enum tree_code op; unsigned HOST_WIDE_INT random_const; random_const = get_random_const(); switch (op) { case BIT_XOR_EXPR: op = PLUS_EXPR; break; case PLUS_EXPR: if (rhs) { op = LROTATE_EXPR; /* * This code limits the value of random_const to * the size of a long for the rotation */ random_const %= TYPE_PRECISION(long_unsigned_type_node); break; } case LROTATE_EXPR: default: op = BIT_XOR_EXPR; break; } if (rhs) *rhs = build_int_cstu(long_unsigned_type_node, random_const); return op; } static gimple create_assign(enum tree_code code, tree lhs, tree op1, tree op2) { return gimple_build_assign_with_ops(code, lhs, op1, op2); } static void perturb_local_entropy(basic_block bb, tree local_entropy) { gimple_stmt_iterator gsi; gimple assign; tree rhs; enum tree_code op; op = get_op(&rhs); assign = create_assign(op, local_entropy, local_entropy, rhs); gsi = gsi_after_labels(bb); gsi_insert_before(&gsi, assign, GSI_NEW_STMT); update_stmt(assign); } static void __perturb_latent_entropy(gimple_stmt_iterator *gsi, tree local_entropy) { gimple assign; tree temp; enum tree_code op; /* 1. create temporary copy of latent_entropy */ temp = create_var(long_unsigned_type_node, "temp_latent_entropy"); /* 2. read... */ add_referenced_var(latent_entropy_decl); mark_sym_for_renaming(latent_entropy_decl); assign = gimple_build_assign(temp, latent_entropy_decl); gsi_insert_before(gsi, assign, GSI_NEW_STMT); update_stmt(assign); /* 3. ...modify... */ op = get_op(NULL); assign = create_assign(op, temp, temp, local_entropy); gsi_insert_after(gsi, assign, GSI_NEW_STMT); update_stmt(assign); /* 4. ...write latent_entropy */ assign = gimple_build_assign(latent_entropy_decl, temp); gsi_insert_after(gsi, assign, GSI_NEW_STMT); update_stmt(assign); } static bool handle_tail_calls(basic_block bb, tree local_entropy) { gimple_stmt_iterator gsi; for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) { gcall *call; gimple stmt = gsi_stmt(gsi); if (!is_gimple_call(stmt)) continue; call = as_a_gcall(stmt); if (!gimple_call_tail_p(call)) continue; __perturb_latent_entropy(&gsi, local_entropy); return true; } return false; } static void perturb_latent_entropy(tree local_entropy) { edge_iterator ei; edge e, last_bb_e; basic_block last_bb; gcc_assert(single_pred_p(EXIT_BLOCK_PTR_FOR_FN(cfun))); last_bb_e = single_pred_edge(EXIT_BLOCK_PTR_FOR_FN(cfun)); FOR_EACH_EDGE(e, ei, last_bb_e->src->preds) { if (ENTRY_BLOCK_PTR_FOR_FN(cfun) == e->src) continue; if (EXIT_BLOCK_PTR_FOR_FN(cfun) == e->src) continue; handle_tail_calls(e->src, local_entropy); } last_bb = single_pred(EXIT_BLOCK_PTR_FOR_FN(cfun)); if (!handle_tail_calls(last_bb, local_entropy)) { gimple_stmt_iterator gsi = gsi_last_bb(last_bb); __perturb_latent_entropy(&gsi, local_entropy); } } static void init_local_entropy(basic_block bb, tree local_entropy) { gimple assign, call; tree frame_addr, rand_const, tmp, fndecl, udi_frame_addr; enum tree_code op; unsigned HOST_WIDE_INT rand_cst; gimple_stmt_iterator gsi = gsi_after_labels(bb); /* 1. create local_entropy_frameaddr */ frame_addr = create_var(ptr_type_node, "local_entropy_frameaddr"); /* 2. local_entropy_frameaddr = __builtin_frame_address() */ fndecl = builtin_decl_implicit(BUILT_IN_FRAME_ADDRESS); call = gimple_build_call(fndecl, 1, integer_zero_node); gimple_call_set_lhs(call, frame_addr); gsi_insert_before(&gsi, call, GSI_NEW_STMT); update_stmt(call); udi_frame_addr = fold_convert(long_unsigned_type_node, frame_addr); assign = gimple_build_assign(local_entropy, udi_frame_addr); gsi_insert_after(&gsi, assign, GSI_NEW_STMT); update_stmt(assign); /* 3. create temporary copy of latent_entropy */ tmp = create_var(long_unsigned_type_node, "temp_latent_entropy"); /* 4. read the global entropy variable into local entropy */ add_referenced_var(latent_entropy_decl); mark_sym_for_renaming(latent_entropy_decl); assign = gimple_build_assign(tmp, latent_entropy_decl); gsi_insert_after(&gsi, assign, GSI_NEW_STMT); update_stmt(assign); /* 5. mix local_entropy_frameaddr into local entropy */ assign = create_assign(BIT_XOR_EXPR, local_entropy, local_entropy, tmp); gsi_insert_after(&gsi, assign, GSI_NEW_STMT); update_stmt(assign); rand_cst = get_random_const(); rand_const = build_int_cstu(long_unsigned_type_node, rand_cst); op = get_op(NULL); assign = create_assign(op, local_entropy, local_entropy, rand_const); gsi_insert_after(&gsi, assign, GSI_NEW_STMT); update_stmt(assign); } static bool create_latent_entropy_decl(void) { varpool_node_ptr node; if (latent_entropy_decl != NULL_TREE) return true; FOR_EACH_VARIABLE(node) { tree name, var = NODE_DECL(node); if (DECL_NAME_LENGTH(var) < sizeof("latent_entropy") - 1) continue; name = DECL_NAME(var); if (strcmp(IDENTIFIER_POINTER(name), "latent_entropy")) continue; latent_entropy_decl = var; break; } return latent_entropy_decl != NULL_TREE; } static unsigned int latent_entropy_execute(void) { basic_block bb; tree local_entropy; if (!create_latent_entropy_decl()) return 0; /* prepare for step 2 below */ gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); if (!single_pred_p(bb)) { split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun))); gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); } /* 1. create the local entropy variable */ local_entropy = create_var(long_unsigned_type_node, "local_entropy"); /* 2. initialize the local entropy variable */ init_local_entropy(bb, local_entropy); bb = bb->next_bb; /* * 3. instrument each BB with an operation on the * local entropy variable */ while (bb != EXIT_BLOCK_PTR_FOR_FN(cfun)) { perturb_local_entropy(bb, local_entropy); bb = bb->next_bb; } /* 4. mix local entropy into the global entropy variable */ perturb_latent_entropy(local_entropy); return 0; } static void latent_entropy_start_unit(void *gcc_data __unused, void *user_data __unused) { tree type, id; int quals; if (in_lto_p) return; /* extern volatile unsigned long latent_entropy */ quals = TYPE_QUALS(long_unsigned_type_node) | TYPE_QUAL_VOLATILE; type = build_qualified_type(long_unsigned_type_node, quals); id = get_identifier("latent_entropy"); latent_entropy_decl = build_decl(UNKNOWN_LOCATION, VAR_DECL, id, type); TREE_STATIC(latent_entropy_decl) = 1; TREE_PUBLIC(latent_entropy_decl) = 1; TREE_USED(latent_entropy_decl) = 1; DECL_PRESERVE_P(latent_entropy_decl) = 1; TREE_THIS_VOLATILE(latent_entropy_decl) = 1; DECL_EXTERNAL(latent_entropy_decl) = 1; DECL_ARTIFICIAL(latent_entropy_decl) = 1; lang_hooks.decls.pushdecl(latent_entropy_decl); } #define PASS_NAME latent_entropy #define PROPERTIES_REQUIRED PROP_gimple_leh | PROP_cfg #define TODO_FLAGS_FINISH TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func \ | TODO_update_ssa #include "gcc-generate-gimple-pass.h" __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { bool enabled = true; const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument * const argv = plugin_info->argv; int i; /* * Call get_random_seed() with noinit=true, so that this returns * 0 in the case where no seed has been passed via -frandom-seed. */ deterministic_seed = get_random_seed(true); static const struct ggc_root_tab gt_ggc_r_gt_latent_entropy[] = { { .base = &latent_entropy_decl, .nelt = 1, .stride = sizeof(latent_entropy_decl), .cb = &gt_ggc_mx_tree_node, .pchw = &gt_pch_nx_tree_node }, LAST_GGC_ROOT_TAB }; PASS_INFO(latent_entropy, "optimized", 1, PASS_POS_INSERT_BEFORE); if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } for (i = 0; i < argc; ++i) { if (!(strcmp(argv[i].key, "disable"))) { enabled = false; continue; } error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); } register_callback(plugin_name, PLUGIN_INFO, NULL, &latent_entropy_plugin_info); if (enabled) { register_callback(plugin_name, PLUGIN_START_UNIT, &latent_entropy_start_unit, NULL); register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS, NULL, (void *)&gt_ggc_r_gt_latent_entropy); register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &latent_entropy_pass_info); } register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL); return 0; }
linux-master
scripts/gcc-plugins/latent_entropy_plugin.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2013-2017 by PaX Team <[email protected]> * * Note: the choice of the license means that the compilation process is * NOT 'eligible' as defined by gcc's library exception to the GPL v3, * but for the kernel it doesn't matter since it doesn't link against * any of the gcc libraries * * gcc plugin to forcibly initialize certain local variables that could * otherwise leak kernel stack to userland if they aren't properly initialized * by later code * * Homepage: https://pax.grsecurity.net/ * * Options: * -fplugin-arg-structleak_plugin-disable * -fplugin-arg-structleak_plugin-verbose * -fplugin-arg-structleak_plugin-byref * -fplugin-arg-structleak_plugin-byref-all * * Usage: * $ # for 4.5/4.6/C based 4.7 * $ gcc -I`gcc -print-file-name=plugin`/include -I`gcc -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o structleak_plugin.so structleak_plugin.c * $ # for C++ based 4.7/4.8+ * $ g++ -I`g++ -print-file-name=plugin`/include -I`g++ -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o structleak_plugin.so structleak_plugin.c * $ gcc -fplugin=./structleak_plugin.so test.c -O2 * * TODO: eliminate redundant initializers */ #include "gcc-common.h" /* unused C type flag in all versions 4.5-6 */ #define TYPE_USERSPACE(TYPE) TYPE_LANG_FLAG_5(TYPE) __visible int plugin_is_GPL_compatible; static struct plugin_info structleak_plugin_info = { .version = PLUGIN_VERSION, .help = "disable\tdo not activate plugin\n" "byref\tinit structs passed by reference\n" "byref-all\tinit anything passed by reference\n" "verbose\tprint all initialized variables\n", }; #define BYREF_STRUCT 1 #define BYREF_ALL 2 static bool verbose; static int byref; static tree handle_user_attribute(tree *node, tree name, tree args, int flags, bool *no_add_attrs) { *no_add_attrs = true; /* check for types? for now accept everything linux has to offer */ if (TREE_CODE(*node) != FIELD_DECL) return NULL_TREE; *no_add_attrs = false; return NULL_TREE; } static struct attribute_spec user_attr = { }; static void register_attributes(void *event_data, void *data) { user_attr.name = "user"; user_attr.handler = handle_user_attribute; user_attr.affects_type_identity = true; register_attribute(&user_attr); } static tree get_field_type(tree field) { return strip_array_types(TREE_TYPE(field)); } static bool is_userspace_type(tree type) { tree field; for (field = TYPE_FIELDS(type); field; field = TREE_CHAIN(field)) { tree fieldtype = get_field_type(field); enum tree_code code = TREE_CODE(fieldtype); if (code == RECORD_TYPE || code == UNION_TYPE) if (is_userspace_type(fieldtype)) return true; if (lookup_attribute("user", DECL_ATTRIBUTES(field))) return true; } return false; } static void finish_type(void *event_data, void *data) { tree type = (tree)event_data; if (type == NULL_TREE || type == error_mark_node) return; if (TREE_CODE(type) == ENUMERAL_TYPE) return; if (TYPE_USERSPACE(type)) return; if (is_userspace_type(type)) TYPE_USERSPACE(type) = 1; } static void initialize(tree var) { basic_block bb; gimple_stmt_iterator gsi; tree initializer; gimple init_stmt; tree type; /* this is the original entry bb before the forced split */ bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); /* first check if variable is already initialized, warn otherwise */ for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) { gimple stmt = gsi_stmt(gsi); tree rhs1; /* we're looking for an assignment of a single rhs... */ if (!gimple_assign_single_p(stmt)) continue; rhs1 = gimple_assign_rhs1(stmt); /* ... of a non-clobbering expression... */ if (TREE_CLOBBER_P(rhs1)) continue; /* ... to our variable... */ if (gimple_get_lhs(stmt) != var) continue; /* if it's an initializer then we're good */ if (TREE_CODE(rhs1) == CONSTRUCTOR) return; } /* these aren't the 0days you're looking for */ if (verbose) inform(DECL_SOURCE_LOCATION(var), "%s variable will be forcibly initialized", (byref && TREE_ADDRESSABLE(var)) ? "byref" : "userspace"); /* build the initializer expression */ type = TREE_TYPE(var); if (AGGREGATE_TYPE_P(type)) initializer = build_constructor(type, NULL); else initializer = fold_convert(type, integer_zero_node); /* build the initializer stmt */ init_stmt = gimple_build_assign(var, initializer); gsi = gsi_after_labels(single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun))); gsi_insert_before(&gsi, init_stmt, GSI_NEW_STMT); update_stmt(init_stmt); } static unsigned int structleak_execute(void) { basic_block bb; tree var; unsigned int i; /* split the first bb where we can put the forced initializers */ gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); if (!single_pred_p(bb)) { split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun))); gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); } /* enumerate all local variables and forcibly initialize our targets */ FOR_EACH_LOCAL_DECL(cfun, i, var) { tree type = TREE_TYPE(var); gcc_assert(DECL_P(var)); if (!auto_var_in_fn_p(var, current_function_decl)) continue; /* only care about structure types unless byref-all */ if (byref != BYREF_ALL && TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE) continue; /* if the type is of interest, examine the variable */ if (TYPE_USERSPACE(type) || (byref && TREE_ADDRESSABLE(var))) initialize(var); } return 0; } #define PASS_NAME structleak #define NO_GATE #define PROPERTIES_REQUIRED PROP_cfg #define TODO_FLAGS_FINISH TODO_verify_il | TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func | TODO_remove_unused_locals | TODO_update_ssa | TODO_ggc_collect | TODO_verify_flow #include "gcc-generate-gimple-pass.h" __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { int i; const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument * const argv = plugin_info->argv; bool enable = true; PASS_INFO(structleak, "early_optimizations", 1, PASS_POS_INSERT_BEFORE); if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) { inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name); enable = false; } for (i = 0; i < argc; ++i) { if (!strcmp(argv[i].key, "disable")) { enable = false; continue; } if (!strcmp(argv[i].key, "verbose")) { verbose = true; continue; } if (!strcmp(argv[i].key, "byref")) { byref = BYREF_STRUCT; continue; } if (!strcmp(argv[i].key, "byref-all")) { byref = BYREF_ALL; continue; } error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); } register_callback(plugin_name, PLUGIN_INFO, NULL, &structleak_plugin_info); if (enable) { register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &structleak_pass_info); register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL); } register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL); return 0; }
linux-master
scripts/gcc-plugins/structleak_plugin.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2011-2017 by the PaX Team <[email protected]> * Modified by Alexander Popov <[email protected]> * * Note: the choice of the license means that the compilation process is * NOT 'eligible' as defined by gcc's library exception to the GPL v3, * but for the kernel it doesn't matter since it doesn't link against * any of the gcc libraries * * This gcc plugin is needed for tracking the lowest border of the kernel stack. * It instruments the kernel code inserting stackleak_track_stack() calls: * - after alloca(); * - for the functions with a stack frame size greater than or equal * to the "track-min-size" plugin parameter. * * This plugin is ported from grsecurity/PaX. For more information see: * https://grsecurity.net/ * https://pax.grsecurity.net/ * * Debugging: * - use fprintf() to stderr, debug_generic_expr(), debug_gimple_stmt(), * print_rtl_single() and debug_rtx(); * - add "-fdump-tree-all -fdump-rtl-all" to the plugin CFLAGS in * Makefile.gcc-plugins to see the verbose dumps of the gcc passes; * - use gcc -E to understand the preprocessing shenanigans; * - use gcc with enabled CFG/GIMPLE/SSA verification (--enable-checking). */ #include "gcc-common.h" __visible int plugin_is_GPL_compatible; static int track_frame_size = -1; static bool build_for_x86 = false; static const char track_function[] = "stackleak_track_stack"; static bool disable = false; static bool verbose = false; /* * Mark these global variables (roots) for gcc garbage collector since * they point to the garbage-collected memory. */ static GTY(()) tree track_function_decl; static struct plugin_info stackleak_plugin_info = { .version = PLUGIN_VERSION, .help = "track-min-size=nn\ttrack stack for functions with a stack frame size >= nn bytes\n" "arch=target_arch\tspecify target build arch\n" "disable\t\tdo not activate the plugin\n" "verbose\t\tprint info about the instrumentation\n" }; static void add_stack_tracking_gcall(gimple_stmt_iterator *gsi, bool after) { gimple stmt; gcall *gimple_call; cgraph_node_ptr node; basic_block bb; /* Insert calling stackleak_track_stack() */ stmt = gimple_build_call(track_function_decl, 0); gimple_call = as_a_gcall(stmt); if (after) gsi_insert_after(gsi, gimple_call, GSI_CONTINUE_LINKING); else gsi_insert_before(gsi, gimple_call, GSI_SAME_STMT); /* Update the cgraph */ bb = gimple_bb(gimple_call); node = cgraph_get_create_node(track_function_decl); gcc_assert(node); cgraph_create_edge(cgraph_get_node(current_function_decl), node, gimple_call, bb->count, compute_call_stmt_bb_frequency(current_function_decl, bb)); } static bool is_alloca(gimple stmt) { if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA)) return true; if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA_WITH_ALIGN)) return true; return false; } static tree get_current_stack_pointer_decl(void) { varpool_node_ptr node; FOR_EACH_VARIABLE(node) { tree var = NODE_DECL(node); tree name = DECL_NAME(var); if (DECL_NAME_LENGTH(var) != sizeof("current_stack_pointer") - 1) continue; if (strcmp(IDENTIFIER_POINTER(name), "current_stack_pointer")) continue; return var; } if (verbose) { fprintf(stderr, "stackleak: missing current_stack_pointer in %s()\n", DECL_NAME_POINTER(current_function_decl)); } return NULL_TREE; } static void add_stack_tracking_gasm(gimple_stmt_iterator *gsi, bool after) { gasm *asm_call = NULL; tree sp_decl, input; vec<tree, va_gc> *inputs = NULL; /* 'no_caller_saved_registers' is currently supported only for x86 */ gcc_assert(build_for_x86); /* * Insert calling stackleak_track_stack() in asm: * asm volatile("call stackleak_track_stack" * :: "r" (current_stack_pointer)) * Use ASM_CALL_CONSTRAINT trick from arch/x86/include/asm/asm.h. * This constraint is taken into account during gcc shrink-wrapping * optimization. It is needed to be sure that stackleak_track_stack() * call is inserted after the prologue of the containing function, * when the stack frame is prepared. */ sp_decl = get_current_stack_pointer_decl(); if (sp_decl == NULL_TREE) { add_stack_tracking_gcall(gsi, after); return; } input = build_tree_list(NULL_TREE, build_const_char_string(2, "r")); input = chainon(NULL_TREE, build_tree_list(input, sp_decl)); vec_safe_push(inputs, input); asm_call = gimple_build_asm_vec("call stackleak_track_stack", inputs, NULL, NULL, NULL); gimple_asm_set_volatile(asm_call, true); if (after) gsi_insert_after(gsi, asm_call, GSI_CONTINUE_LINKING); else gsi_insert_before(gsi, asm_call, GSI_SAME_STMT); update_stmt(asm_call); } static void add_stack_tracking(gimple_stmt_iterator *gsi, bool after) { /* * The 'no_caller_saved_registers' attribute is used for * stackleak_track_stack(). If the compiler supports this attribute for * the target arch, we can add calling stackleak_track_stack() in asm. * That improves performance: we avoid useless operations with the * caller-saved registers in the functions from which we will remove * stackleak_track_stack() call during the stackleak_cleanup pass. */ if (lookup_attribute_spec(get_identifier("no_caller_saved_registers"))) add_stack_tracking_gasm(gsi, after); else add_stack_tracking_gcall(gsi, after); } /* * Work with the GIMPLE representation of the code. Insert the * stackleak_track_stack() call after alloca() and into the beginning * of the function if it is not instrumented. */ static unsigned int stackleak_instrument_execute(void) { basic_block bb, entry_bb; bool prologue_instrumented = false, is_leaf = true; gimple_stmt_iterator gsi = { 0 }; /* * ENTRY_BLOCK_PTR is a basic block which represents possible entry * point of a function. This block does not contain any code and * has a CFG edge to its successor. */ gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); entry_bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); /* * Loop through the GIMPLE statements in each of cfun basic blocks. * cfun is a global variable which represents the function that is * currently processed. */ FOR_EACH_BB_FN(bb, cfun) { for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) { gimple stmt; stmt = gsi_stmt(gsi); /* Leaf function is a function which makes no calls */ if (is_gimple_call(stmt)) is_leaf = false; if (!is_alloca(stmt)) continue; if (verbose) { fprintf(stderr, "stackleak: be careful, alloca() in %s()\n", DECL_NAME_POINTER(current_function_decl)); } /* Insert stackleak_track_stack() call after alloca() */ add_stack_tracking(&gsi, true); if (bb == entry_bb) prologue_instrumented = true; } } if (prologue_instrumented) return 0; /* * Special cases to skip the instrumentation. * * Taking the address of static inline functions materializes them, * but we mustn't instrument some of them as the resulting stack * alignment required by the function call ABI will break other * assumptions regarding the expected (but not otherwise enforced) * register clobbering ABI. * * Case in point: native_save_fl on amd64 when optimized for size * clobbers rdx if it were instrumented here. * * TODO: any more special cases? */ if (is_leaf && !TREE_PUBLIC(current_function_decl) && DECL_DECLARED_INLINE_P(current_function_decl)) { return 0; } if (is_leaf && !strncmp(IDENTIFIER_POINTER(DECL_NAME(current_function_decl)), "_paravirt_", 10)) { return 0; } /* Insert stackleak_track_stack() call at the function beginning */ bb = entry_bb; if (!single_pred_p(bb)) { /* gcc_assert(bb_loop_depth(bb) || (bb->flags & BB_IRREDUCIBLE_LOOP)); */ split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun))); gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun))); bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)); } gsi = gsi_after_labels(bb); add_stack_tracking(&gsi, false); return 0; } static bool large_stack_frame(void) { #if BUILDING_GCC_VERSION >= 8000 return maybe_ge(get_frame_size(), track_frame_size); #else return (get_frame_size() >= track_frame_size); #endif } static void remove_stack_tracking_gcall(void) { rtx_insn *insn, *next; /* * Find stackleak_track_stack() calls. Loop through the chain of insns, * which is an RTL representation of the code for a function. * * The example of a matching insn: * (call_insn 8 4 10 2 (call (mem (symbol_ref ("stackleak_track_stack") * [flags 0x41] <function_decl 0x7f7cd3302a80 stackleak_track_stack>) * [0 stackleak_track_stack S1 A8]) (0)) 675 {*call} (expr_list * (symbol_ref ("stackleak_track_stack") [flags 0x41] <function_decl * 0x7f7cd3302a80 stackleak_track_stack>) (expr_list (0) (nil))) (nil)) */ for (insn = get_insns(); insn; insn = next) { rtx body; next = NEXT_INSN(insn); /* Check the expression code of the insn */ if (!CALL_P(insn)) continue; /* * Check the expression code of the insn body, which is an RTL * Expression (RTX) describing the side effect performed by * that insn. */ body = PATTERN(insn); if (GET_CODE(body) == PARALLEL) body = XVECEXP(body, 0, 0); if (GET_CODE(body) != CALL) continue; /* * Check the first operand of the call expression. It should * be a mem RTX describing the needed subroutine with a * symbol_ref RTX. */ body = XEXP(body, 0); if (GET_CODE(body) != MEM) continue; body = XEXP(body, 0); if (GET_CODE(body) != SYMBOL_REF) continue; if (SYMBOL_REF_DECL(body) != track_function_decl) continue; /* Delete the stackleak_track_stack() call */ delete_insn_and_edges(insn); #if BUILDING_GCC_VERSION < 8000 if (GET_CODE(next) == NOTE && NOTE_KIND(next) == NOTE_INSN_CALL_ARG_LOCATION) { insn = next; next = NEXT_INSN(insn); delete_insn_and_edges(insn); } #endif } } static bool remove_stack_tracking_gasm(void) { bool removed = false; rtx_insn *insn, *next; /* 'no_caller_saved_registers' is currently supported only for x86 */ gcc_assert(build_for_x86); /* * Find stackleak_track_stack() asm calls. Loop through the chain of * insns, which is an RTL representation of the code for a function. * * The example of a matching insn: * (insn 11 5 12 2 (parallel [ (asm_operands/v * ("call stackleak_track_stack") ("") 0 * [ (reg/v:DI 7 sp [ current_stack_pointer ]) ] * [ (asm_input:DI ("r")) ] []) * (clobber (reg:CC 17 flags)) ]) -1 (nil)) */ for (insn = get_insns(); insn; insn = next) { rtx body; next = NEXT_INSN(insn); /* Check the expression code of the insn */ if (!NONJUMP_INSN_P(insn)) continue; /* * Check the expression code of the insn body, which is an RTL * Expression (RTX) describing the side effect performed by * that insn. */ body = PATTERN(insn); if (GET_CODE(body) != PARALLEL) continue; body = XVECEXP(body, 0, 0); if (GET_CODE(body) != ASM_OPERANDS) continue; if (strcmp(ASM_OPERANDS_TEMPLATE(body), "call stackleak_track_stack")) { continue; } delete_insn_and_edges(insn); gcc_assert(!removed); removed = true; } return removed; } /* * Work with the RTL representation of the code. * Remove the unneeded stackleak_track_stack() calls from the functions * which don't call alloca() and don't have a large enough stack frame size. */ static unsigned int stackleak_cleanup_execute(void) { const char *fn = DECL_NAME_POINTER(current_function_decl); bool removed = false; /* * Leave stack tracking in functions that call alloca(). * Additional case: * gcc before version 7 called allocate_dynamic_stack_space() from * expand_stack_vars() for runtime alignment of constant-sized stack * variables. That caused cfun->calls_alloca to be set for functions * that in fact don't use alloca(). * For more info see gcc commit 7072df0aae0c59ae437e. * Let's leave such functions instrumented as well. */ if (cfun->calls_alloca) { if (verbose) fprintf(stderr, "stackleak: instrument %s(): calls_alloca\n", fn); return 0; } /* Leave stack tracking in functions with large stack frame */ if (large_stack_frame()) { if (verbose) fprintf(stderr, "stackleak: instrument %s()\n", fn); return 0; } if (lookup_attribute_spec(get_identifier("no_caller_saved_registers"))) removed = remove_stack_tracking_gasm(); if (!removed) remove_stack_tracking_gcall(); return 0; } /* * STRING_CST may or may not be NUL terminated: * https://gcc.gnu.org/onlinedocs/gccint/Constant-expressions.html */ static inline bool string_equal(tree node, const char *string, int length) { if (TREE_STRING_LENGTH(node) < length) return false; if (TREE_STRING_LENGTH(node) > length + 1) return false; if (TREE_STRING_LENGTH(node) == length + 1 && TREE_STRING_POINTER(node)[length] != '\0') return false; return !memcmp(TREE_STRING_POINTER(node), string, length); } #define STRING_EQUAL(node, str) string_equal(node, str, strlen(str)) static bool stackleak_gate(void) { tree section; section = lookup_attribute("section", DECL_ATTRIBUTES(current_function_decl)); if (section && TREE_VALUE(section)) { section = TREE_VALUE(TREE_VALUE(section)); if (STRING_EQUAL(section, ".init.text")) return false; if (STRING_EQUAL(section, ".devinit.text")) return false; if (STRING_EQUAL(section, ".cpuinit.text")) return false; if (STRING_EQUAL(section, ".meminit.text")) return false; if (STRING_EQUAL(section, ".noinstr.text")) return false; if (STRING_EQUAL(section, ".entry.text")) return false; } return track_frame_size >= 0; } /* Build the function declaration for stackleak_track_stack() */ static void stackleak_start_unit(void *gcc_data __unused, void *user_data __unused) { tree fntype; /* void stackleak_track_stack(void) */ fntype = build_function_type_list(void_type_node, NULL_TREE); track_function_decl = build_fn_decl(track_function, fntype); DECL_ASSEMBLER_NAME(track_function_decl); /* for LTO */ TREE_PUBLIC(track_function_decl) = 1; TREE_USED(track_function_decl) = 1; DECL_EXTERNAL(track_function_decl) = 1; DECL_ARTIFICIAL(track_function_decl) = 1; DECL_PRESERVE_P(track_function_decl) = 1; } /* * Pass gate function is a predicate function that gets executed before the * corresponding pass. If the return value is 'true' the pass gets executed, * otherwise, it is skipped. */ static bool stackleak_instrument_gate(void) { return stackleak_gate(); } #define PASS_NAME stackleak_instrument #define PROPERTIES_REQUIRED PROP_gimple_leh | PROP_cfg #define TODO_FLAGS_START TODO_verify_ssa | TODO_verify_flow | TODO_verify_stmts #define TODO_FLAGS_FINISH TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func \ | TODO_update_ssa | TODO_rebuild_cgraph_edges #include "gcc-generate-gimple-pass.h" static bool stackleak_cleanup_gate(void) { return stackleak_gate(); } #define PASS_NAME stackleak_cleanup #define TODO_FLAGS_FINISH TODO_dump_func #include "gcc-generate-rtl-pass.h" /* * Every gcc plugin exports a plugin_init() function that is called right * after the plugin is loaded. This function is responsible for registering * the plugin callbacks and doing other required initialization. */ __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument * const argv = plugin_info->argv; int i = 0; /* Extra GGC root tables describing our GTY-ed data */ static const struct ggc_root_tab gt_ggc_r_gt_stackleak[] = { { .base = &track_function_decl, .nelt = 1, .stride = sizeof(track_function_decl), .cb = &gt_ggc_mx_tree_node, .pchw = &gt_pch_nx_tree_node }, LAST_GGC_ROOT_TAB }; /* * The stackleak_instrument pass should be executed before the * "optimized" pass, which is the control flow graph cleanup that is * performed just before expanding gcc trees to the RTL. In former * versions of the plugin this new pass was inserted before the * "tree_profile" pass, which is currently called "profile". */ PASS_INFO(stackleak_instrument, "optimized", 1, PASS_POS_INSERT_BEFORE); /* * The stackleak_cleanup pass should be executed before the "*free_cfg" * pass. It's the moment when the stack frame size is already final, * function prologues and epilogues are generated, and the * machine-dependent code transformations are not done. */ PASS_INFO(stackleak_cleanup, "*free_cfg", 1, PASS_POS_INSERT_BEFORE); if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } /* Parse the plugin arguments */ for (i = 0; i < argc; i++) { if (!strcmp(argv[i].key, "track-min-size")) { if (!argv[i].value) { error(G_("no value supplied for option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); return 1; } track_frame_size = atoi(argv[i].value); if (track_frame_size < 0) { error(G_("invalid option argument '-fplugin-arg-%s-%s=%s'"), plugin_name, argv[i].key, argv[i].value); return 1; } } else if (!strcmp(argv[i].key, "arch")) { if (!argv[i].value) { error(G_("no value supplied for option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); return 1; } if (!strcmp(argv[i].value, "x86")) build_for_x86 = true; } else if (!strcmp(argv[i].key, "disable")) { disable = true; } else if (!strcmp(argv[i].key, "verbose")) { verbose = true; } else { error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); return 1; } } if (disable) { if (verbose) fprintf(stderr, "stackleak: disabled for this translation unit\n"); return 0; } /* Give the information about the plugin */ register_callback(plugin_name, PLUGIN_INFO, NULL, &stackleak_plugin_info); /* Register to be called before processing a translation unit */ register_callback(plugin_name, PLUGIN_START_UNIT, &stackleak_start_unit, NULL); /* Register an extra GCC garbage collector (GGC) root table */ register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS, NULL, (void *)&gt_ggc_r_gt_stackleak); /* * Hook into the Pass Manager to register new gcc passes. * * The stack frame size info is available only at the last RTL pass, * when it's too late to insert complex code like a function call. * So we register two gcc passes to instrument every function at first * and remove the unneeded instrumentation later. */ register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &stackleak_instrument_pass_info); register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &stackleak_cleanup_pass_info); return 0; }
linux-master
scripts/gcc-plugins/stackleak_plugin.c
/* * Copyright 2014-2016 by Open Source Security, Inc., Brad Spengler <[email protected]> * and PaX Team <[email protected]> * Licensed under the GPL v2 * * Note: the choice of the license means that the compilation process is * NOT 'eligible' as defined by gcc's library exception to the GPL v3, * but for the kernel it doesn't matter since it doesn't link against * any of the gcc libraries * * Usage: * $ # for 4.5/4.6/C based 4.7 * $ gcc -I`gcc -print-file-name=plugin`/include -I`gcc -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o randomize_layout_plugin.so randomize_layout_plugin.c * $ # for C++ based 4.7/4.8+ * $ g++ -I`g++ -print-file-name=plugin`/include -I`g++ -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o randomize_layout_plugin.so randomize_layout_plugin.c * $ gcc -fplugin=./randomize_layout_plugin.so test.c -O2 */ #include "gcc-common.h" #include "randomize_layout_seed.h" #if BUILDING_GCC_MAJOR < 4 || (BUILDING_GCC_MAJOR == 4 && BUILDING_GCC_MINOR < 7) #error "The RANDSTRUCT plugin requires GCC 4.7 or newer." #endif #define ORIG_TYPE_NAME(node) \ (TYPE_NAME(TYPE_MAIN_VARIANT(node)) != NULL_TREE ? ((const unsigned char *)IDENTIFIER_POINTER(TYPE_NAME(TYPE_MAIN_VARIANT(node)))) : (const unsigned char *)"anonymous") #define INFORM(loc, msg, ...) inform(loc, "randstruct: " msg, ##__VA_ARGS__) #define MISMATCH(loc, how, ...) INFORM(loc, "casting between randomized structure pointer types (" how "): %qT and %qT\n", __VA_ARGS__) __visible int plugin_is_GPL_compatible; static int performance_mode; static struct plugin_info randomize_layout_plugin_info = { .version = PLUGIN_VERSION, .help = "disable\t\t\tdo not activate plugin\n" "performance-mode\tenable cacheline-aware layout randomization\n" }; /* from old Linux dcache.h */ static inline unsigned long partial_name_hash(unsigned long c, unsigned long prevhash) { return (prevhash + (c << 4) + (c >> 4)) * 11; } static inline unsigned int name_hash(const unsigned char *name) { unsigned long hash = 0; unsigned int len = strlen((const char *)name); while (len--) hash = partial_name_hash(*name++, hash); return (unsigned int)hash; } static tree handle_randomize_layout_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs) { tree type; *no_add_attrs = true; if (TREE_CODE(*node) == FUNCTION_DECL) { error("%qE attribute does not apply to functions (%qF)", name, *node); return NULL_TREE; } if (TREE_CODE(*node) == PARM_DECL) { error("%qE attribute does not apply to function parameters (%qD)", name, *node); return NULL_TREE; } if (TREE_CODE(*node) == VAR_DECL) { error("%qE attribute does not apply to variables (%qD)", name, *node); return NULL_TREE; } if (TYPE_P(*node)) { type = *node; } else { gcc_assert(TREE_CODE(*node) == TYPE_DECL); type = TREE_TYPE(*node); } if (TREE_CODE(type) != RECORD_TYPE) { error("%qE attribute used on %qT applies to struct types only", name, type); return NULL_TREE; } if (lookup_attribute(IDENTIFIER_POINTER(name), TYPE_ATTRIBUTES(type))) { error("%qE attribute is already applied to the type %qT", name, type); return NULL_TREE; } *no_add_attrs = false; return NULL_TREE; } /* set on complete types that we don't need to inspect further at all */ static tree handle_randomize_considered_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs) { *no_add_attrs = false; return NULL_TREE; } /* * set on types that we've performed a shuffle on, to prevent re-shuffling * this does not preclude us from inspecting its fields for potential shuffles */ static tree handle_randomize_performed_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs) { *no_add_attrs = false; return NULL_TREE; } /* * 64bit variant of Bob Jenkins' public domain PRNG * 256 bits of internal state */ typedef unsigned long long u64; typedef struct ranctx { u64 a; u64 b; u64 c; u64 d; } ranctx; #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) static u64 ranval(ranctx *x) { u64 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; } static void raninit(ranctx *x, u64 *seed) { int i; x->a = seed[0]; x->b = seed[1]; x->c = seed[2]; x->d = seed[3]; for (i=0; i < 30; ++i) (void)ranval(x); } static u64 shuffle_seed[4]; struct partition_group { tree tree_start; unsigned long start; unsigned long length; }; static void partition_struct(tree *fields, unsigned long length, struct partition_group *size_groups, unsigned long *num_groups) { unsigned long i; unsigned long accum_size = 0; unsigned long accum_length = 0; unsigned long group_idx = 0; gcc_assert(length < INT_MAX); memset(size_groups, 0, sizeof(struct partition_group) * length); for (i = 0; i < length; i++) { if (size_groups[group_idx].tree_start == NULL_TREE) { size_groups[group_idx].tree_start = fields[i]; size_groups[group_idx].start = i; accum_length = 0; accum_size = 0; } accum_size += (unsigned long)int_size_in_bytes(TREE_TYPE(fields[i])); accum_length++; if (accum_size >= 64) { size_groups[group_idx].length = accum_length; accum_length = 0; group_idx++; } } if (size_groups[group_idx].tree_start != NULL_TREE && !size_groups[group_idx].length) { size_groups[group_idx].length = accum_length; group_idx++; } *num_groups = group_idx; } static void performance_shuffle(tree *newtree, unsigned long length, ranctx *prng_state) { unsigned long i, x; struct partition_group size_group[length]; unsigned long num_groups = 0; unsigned long randnum; partition_struct(newtree, length, (struct partition_group *)&size_group, &num_groups); for (i = num_groups - 1; i > 0; i--) { struct partition_group tmp; randnum = ranval(prng_state) % (i + 1); tmp = size_group[i]; size_group[i] = size_group[randnum]; size_group[randnum] = tmp; } for (x = 0; x < num_groups; x++) { for (i = size_group[x].start + size_group[x].length - 1; i > size_group[x].start; i--) { tree tmp; if (DECL_BIT_FIELD_TYPE(newtree[i])) continue; randnum = ranval(prng_state) % (i + 1); // we could handle this case differently if desired if (DECL_BIT_FIELD_TYPE(newtree[randnum])) continue; tmp = newtree[i]; newtree[i] = newtree[randnum]; newtree[randnum] = tmp; } } } static void full_shuffle(tree *newtree, unsigned long length, ranctx *prng_state) { unsigned long i, randnum; for (i = length - 1; i > 0; i--) { tree tmp; randnum = ranval(prng_state) % (i + 1); tmp = newtree[i]; newtree[i] = newtree[randnum]; newtree[randnum] = tmp; } } /* modern in-place Fisher-Yates shuffle */ static void shuffle(const_tree type, tree *newtree, unsigned long length) { unsigned long i; u64 seed[4]; ranctx prng_state; const unsigned char *structname; if (length == 0) return; gcc_assert(TREE_CODE(type) == RECORD_TYPE); structname = ORIG_TYPE_NAME(type); #ifdef __DEBUG_PLUGIN fprintf(stderr, "Shuffling struct %s %p\n", (const char *)structname, type); #ifdef __DEBUG_VERBOSE debug_tree((tree)type); #endif #endif for (i = 0; i < 4; i++) { seed[i] = shuffle_seed[i]; seed[i] ^= name_hash(structname); } raninit(&prng_state, (u64 *)&seed); if (performance_mode) performance_shuffle(newtree, length, &prng_state); else full_shuffle(newtree, length, &prng_state); } static bool is_flexible_array(const_tree field) { const_tree fieldtype; const_tree typesize; const_tree elemtype; const_tree elemsize; fieldtype = TREE_TYPE(field); typesize = TYPE_SIZE(fieldtype); if (TREE_CODE(fieldtype) != ARRAY_TYPE) return false; elemtype = TREE_TYPE(fieldtype); elemsize = TYPE_SIZE(elemtype); /* size of type is represented in bits */ if (typesize == NULL_TREE && TYPE_DOMAIN(fieldtype) != NULL_TREE && TYPE_MAX_VALUE(TYPE_DOMAIN(fieldtype)) == NULL_TREE) return true; if (typesize != NULL_TREE && (TREE_CONSTANT(typesize) && (!tree_to_uhwi(typesize) || tree_to_uhwi(typesize) == tree_to_uhwi(elemsize)))) return true; return false; } static int relayout_struct(tree type) { unsigned long num_fields = (unsigned long)list_length(TYPE_FIELDS(type)); unsigned long shuffle_length = num_fields; tree field; tree newtree[num_fields]; unsigned long i; tree list; tree variant; tree main_variant; expanded_location xloc; bool has_flexarray = false; if (TYPE_FIELDS(type) == NULL_TREE) return 0; if (num_fields < 2) return 0; gcc_assert(TREE_CODE(type) == RECORD_TYPE); gcc_assert(num_fields < INT_MAX); if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)) || lookup_attribute("no_randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type)))) return 0; /* Workaround for 3rd-party VirtualBox source that we can't modify ourselves */ if (!strcmp((const char *)ORIG_TYPE_NAME(type), "INTNETTRUNKFACTORY") || !strcmp((const char *)ORIG_TYPE_NAME(type), "RAWPCIFACTORY")) return 0; /* throw out any structs in uapi */ xloc = expand_location(DECL_SOURCE_LOCATION(TYPE_FIELDS(type))); if (strstr(xloc.file, "/uapi/")) error(G_("attempted to randomize userland API struct %s"), ORIG_TYPE_NAME(type)); for (field = TYPE_FIELDS(type), i = 0; field; field = TREE_CHAIN(field), i++) { gcc_assert(TREE_CODE(field) == FIELD_DECL); newtree[i] = field; } /* * enforce that we don't randomize the layout of the last * element of a struct if it's a 0 or 1-length array * or a proper flexible array */ if (is_flexible_array(newtree[num_fields - 1])) { has_flexarray = true; shuffle_length--; } shuffle(type, (tree *)newtree, shuffle_length); /* * set up a bogus anonymous struct field designed to error out on unnamed struct initializers * as gcc provides no other way to detect such code */ list = make_node(FIELD_DECL); TREE_CHAIN(list) = newtree[0]; TREE_TYPE(list) = void_type_node; DECL_SIZE(list) = bitsize_zero_node; DECL_NONADDRESSABLE_P(list) = 1; DECL_FIELD_BIT_OFFSET(list) = bitsize_zero_node; DECL_SIZE_UNIT(list) = size_zero_node; DECL_FIELD_OFFSET(list) = size_zero_node; DECL_CONTEXT(list) = type; // to satisfy the constify plugin TREE_READONLY(list) = 1; for (i = 0; i < num_fields - 1; i++) TREE_CHAIN(newtree[i]) = newtree[i+1]; TREE_CHAIN(newtree[num_fields - 1]) = NULL_TREE; main_variant = TYPE_MAIN_VARIANT(type); for (variant = main_variant; variant; variant = TYPE_NEXT_VARIANT(variant)) { TYPE_FIELDS(variant) = list; TYPE_ATTRIBUTES(variant) = copy_list(TYPE_ATTRIBUTES(variant)); TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("randomize_performed"), NULL_TREE, TYPE_ATTRIBUTES(variant)); TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("designated_init"), NULL_TREE, TYPE_ATTRIBUTES(variant)); if (has_flexarray) TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("has_flexarray"), NULL_TREE, TYPE_ATTRIBUTES(type)); } /* * force a re-layout of the main variant * the TYPE_SIZE for all variants will be recomputed * by finalize_type_size() */ TYPE_SIZE(main_variant) = NULL_TREE; layout_type(main_variant); gcc_assert(TYPE_SIZE(main_variant) != NULL_TREE); return 1; } /* from constify plugin */ static const_tree get_field_type(const_tree field) { return strip_array_types(TREE_TYPE(field)); } /* from constify plugin */ static bool is_fptr(const_tree fieldtype) { if (TREE_CODE(fieldtype) != POINTER_TYPE) return false; return TREE_CODE(TREE_TYPE(fieldtype)) == FUNCTION_TYPE; } /* derived from constify plugin */ static int is_pure_ops_struct(const_tree node) { const_tree field; gcc_assert(TREE_CODE(node) == RECORD_TYPE || TREE_CODE(node) == UNION_TYPE); for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) { const_tree fieldtype = get_field_type(field); enum tree_code code = TREE_CODE(fieldtype); if (node == fieldtype) continue; if (code == RECORD_TYPE || code == UNION_TYPE) { if (!is_pure_ops_struct(fieldtype)) return 0; continue; } if (!is_fptr(fieldtype)) return 0; } return 1; } static void randomize_type(tree type) { tree variant; gcc_assert(TREE_CODE(type) == RECORD_TYPE); if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type))) return; if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type)) relayout_struct(type); for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) { TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type)); TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type)); } #ifdef __DEBUG_PLUGIN fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type)); #ifdef __DEBUG_VERBOSE debug_tree(type); #endif #endif } static void update_decl_size(tree decl) { tree lastval, lastidx, field, init, type, flexsize; unsigned HOST_WIDE_INT len; type = TREE_TYPE(decl); if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type))) return; init = DECL_INITIAL(decl); if (init == NULL_TREE || init == error_mark_node) return; if (TREE_CODE(init) != CONSTRUCTOR) return; len = CONSTRUCTOR_NELTS(init); if (!len) return; lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value; lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index; for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field)) ; if (lastidx != field) return; if (TREE_CODE(lastval) != STRING_CST) { error("Only string constants are supported as initializers " "for randomized structures with flexible arrays"); return; } flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) * tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval))))); DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize); return; } static void randomize_layout_finish_decl(void *event_data, void *data) { tree decl = (tree)event_data; tree type; if (decl == NULL_TREE || decl == error_mark_node) return; type = TREE_TYPE(decl); if (TREE_CODE(decl) != VAR_DECL) return; if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE) return; if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type))) return; DECL_SIZE(decl) = 0; DECL_SIZE_UNIT(decl) = 0; SET_DECL_ALIGN(decl, 0); SET_DECL_MODE (decl, VOIDmode); SET_DECL_RTL(decl, 0); update_decl_size(decl); layout_decl(decl, 0); } static void finish_type(void *event_data, void *data) { tree type = (tree)event_data; if (type == NULL_TREE || type == error_mark_node) return; if (TREE_CODE(type) != RECORD_TYPE) return; if (TYPE_FIELDS(type) == NULL_TREE) return; if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type))) return; #ifdef __DEBUG_PLUGIN fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type)); #endif #ifdef __DEBUG_VERBOSE debug_tree(type); #endif randomize_type(type); return; } static struct attribute_spec randomize_layout_attr = { }; static struct attribute_spec no_randomize_layout_attr = { }; static struct attribute_spec randomize_considered_attr = { }; static struct attribute_spec randomize_performed_attr = { }; static void register_attributes(void *event_data, void *data) { randomize_layout_attr.name = "randomize_layout"; randomize_layout_attr.type_required = true; randomize_layout_attr.handler = handle_randomize_layout_attr; randomize_layout_attr.affects_type_identity = true; no_randomize_layout_attr.name = "no_randomize_layout"; no_randomize_layout_attr.type_required = true; no_randomize_layout_attr.handler = handle_randomize_layout_attr; no_randomize_layout_attr.affects_type_identity = true; randomize_considered_attr.name = "randomize_considered"; randomize_considered_attr.type_required = true; randomize_considered_attr.handler = handle_randomize_considered_attr; randomize_performed_attr.name = "randomize_performed"; randomize_performed_attr.type_required = true; randomize_performed_attr.handler = handle_randomize_performed_attr; register_attribute(&randomize_layout_attr); register_attribute(&no_randomize_layout_attr); register_attribute(&randomize_considered_attr); register_attribute(&randomize_performed_attr); } static void check_bad_casts_in_constructor(tree var, tree init) { unsigned HOST_WIDE_INT idx; tree field, val; tree field_type, val_type; FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) { if (TREE_CODE(val) == CONSTRUCTOR) { check_bad_casts_in_constructor(var, val); continue; } /* pipacs' plugin creates franken-arrays that differ from those produced by normal code which all have valid 'field' trees. work around this */ if (field == NULL_TREE) continue; field_type = TREE_TYPE(field); val_type = TREE_TYPE(val); if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE) continue; if (field_type == val_type) continue; field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type)))); val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type)))); if (field_type == void_type_node) continue; if (field_type == val_type) continue; if (TREE_CODE(val_type) != RECORD_TYPE) continue; if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type))) continue; MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type)); } } /* derived from the constify plugin */ static void check_global_variables(void *event_data, void *data) { struct varpool_node *node; tree init; FOR_EACH_VARIABLE(node) { tree var = NODE_DECL(node); init = DECL_INITIAL(var); if (init == NULL_TREE) continue; if (TREE_CODE(init) != CONSTRUCTOR) continue; check_bad_casts_in_constructor(var, init); } } static bool dominated_by_is_err(const_tree rhs, basic_block bb) { basic_block dom; gimple dom_stmt; gimple call_stmt; const_tree dom_lhs; const_tree poss_is_err_cond; const_tree poss_is_err_func; const_tree is_err_arg; dom = get_immediate_dominator(CDI_DOMINATORS, bb); if (!dom) return false; dom_stmt = last_stmt(dom); if (!dom_stmt) return false; if (gimple_code(dom_stmt) != GIMPLE_COND) return false; if (gimple_cond_code(dom_stmt) != NE_EXPR) return false; if (!integer_zerop(gimple_cond_rhs(dom_stmt))) return false; poss_is_err_cond = gimple_cond_lhs(dom_stmt); if (TREE_CODE(poss_is_err_cond) != SSA_NAME) return false; call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond); if (gimple_code(call_stmt) != GIMPLE_CALL) return false; dom_lhs = gimple_get_lhs(call_stmt); poss_is_err_func = gimple_call_fndecl(call_stmt); if (!poss_is_err_func) return false; if (dom_lhs != poss_is_err_cond) return false; if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR")) return false; is_err_arg = gimple_call_arg(call_stmt, 0); if (!is_err_arg) return false; if (is_err_arg != rhs) return false; return true; } static void handle_local_var_initializers(void) { tree var; unsigned int i; FOR_EACH_LOCAL_DECL(cfun, i, var) { tree init = DECL_INITIAL(var); if (!init) continue; if (TREE_CODE(init) != CONSTRUCTOR) continue; check_bad_casts_in_constructor(var, init); } } /* * iterate over all statements to find "bad" casts: * those where the address of the start of a structure is cast * to a pointer of a structure of a different type, or a * structure pointer type is cast to a different structure pointer type */ static unsigned int find_bad_casts_execute(void) { basic_block bb; handle_local_var_initializers(); FOR_EACH_BB_FN(bb, cfun) { gimple_stmt_iterator gsi; for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) { gimple stmt; const_tree lhs; const_tree lhs_type; const_tree rhs1; const_tree rhs_type; const_tree ptr_lhs_type; const_tree ptr_rhs_type; const_tree op0; const_tree op0_type; enum tree_code rhs_code; stmt = gsi_stmt(gsi); #ifdef __DEBUG_PLUGIN #ifdef __DEBUG_VERBOSE debug_gimple_stmt(stmt); debug_tree(gimple_get_lhs(stmt)); #endif #endif if (gimple_code(stmt) != GIMPLE_ASSIGN) continue; #ifdef __DEBUG_PLUGIN #ifdef __DEBUG_VERBOSE debug_tree(gimple_assign_rhs1(stmt)); #endif #endif rhs_code = gimple_assign_rhs_code(stmt); if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME) continue; lhs = gimple_get_lhs(stmt); lhs_type = TREE_TYPE(lhs); rhs1 = gimple_assign_rhs1(stmt); rhs_type = TREE_TYPE(rhs1); if (TREE_CODE(rhs_type) != POINTER_TYPE || TREE_CODE(lhs_type) != POINTER_TYPE) continue; ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type)))); ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type)))); if (ptr_rhs_type == void_type_node) continue; if (ptr_lhs_type == void_type_node) continue; if (dominated_by_is_err(rhs1, bb)) continue; if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) { #ifndef __DEBUG_PLUGIN if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type))) #endif MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type); continue; } if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type) continue; if (rhs_code == ADDR_EXPR) { op0 = TREE_OPERAND(rhs1, 0); if (op0 == NULL_TREE) continue; if (TREE_CODE(op0) != VAR_DECL) continue; op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0)))); if (op0_type == ptr_lhs_type) continue; #ifndef __DEBUG_PLUGIN if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type))) #endif MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type); } else { const_tree ssa_name_var = SSA_NAME_VAR(rhs1); /* skip bogus type casts introduced by container_of */ if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) && !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr")) continue; #ifndef __DEBUG_PLUGIN if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type))) #endif MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type); } } } return 0; } #define PASS_NAME find_bad_casts #define NO_GATE #define TODO_FLAGS_FINISH TODO_dump_func #include "gcc-generate-gimple-pass.h" __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version) { int i; const char * const plugin_name = plugin_info->base_name; const int argc = plugin_info->argc; const struct plugin_argument * const argv = plugin_info->argv; bool enable = true; int obtained_seed = 0; struct register_pass_info find_bad_casts_pass_info; find_bad_casts_pass_info.pass = make_find_bad_casts_pass(); find_bad_casts_pass_info.reference_pass_name = "ssa"; find_bad_casts_pass_info.ref_pass_instance_number = 1; find_bad_casts_pass_info.pos_op = PASS_POS_INSERT_AFTER; if (!plugin_default_version_check(version, &gcc_version)) { error(G_("incompatible gcc/plugin versions")); return 1; } if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) { inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name); enable = false; } for (i = 0; i < argc; ++i) { if (!strcmp(argv[i].key, "disable")) { enable = false; continue; } if (!strcmp(argv[i].key, "performance-mode")) { performance_mode = 1; continue; } error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key); } if (strlen(randstruct_seed) != 64) { error(G_("invalid seed value supplied for %s plugin"), plugin_name); return 1; } obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx", &shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]); if (obtained_seed != 4) { error(G_("Invalid seed supplied for %s plugin"), plugin_name); return 1; } register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info); if (enable) { register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL); register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info); register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL); register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL); } register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL); return 0; }
linux-master
scripts/gcc-plugins/randomize_layout_plugin.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * * mdp - make dummy policy * * When pointed at a kernel tree, builds a dummy policy for that kernel * with exactly one type with full rights to itself. * * Copyright (C) IBM Corporation, 2006 * * Authors: Serge E. Hallyn <[email protected]> */ /* NOTE: we really do want to use the kernel headers here */ #define __EXPORTED_HEADERS__ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <linux/kconfig.h> static void usage(char *name) { printf("usage: %s [-m] policy_file context_file\n", name); exit(1); } /* Class/perm mapping support */ struct security_class_mapping { const char *name; const char *perms[sizeof(unsigned) * 8 + 1]; }; #include "classmap.h" #include "initial_sid_to_string.h" #include "policycap_names.h" #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) int main(int argc, char *argv[]) { int i, j, mls = 0; int initial_sid_to_string_len; char **arg, *polout, *ctxout; FILE *fout; if (argc < 3) usage(argv[0]); arg = argv+1; if (argc==4 && strcmp(argv[1], "-m") == 0) { mls = 1; arg++; } polout = *arg++; ctxout = *arg; fout = fopen(polout, "w"); if (!fout) { printf("Could not open %s for writing\n", polout); usage(argv[0]); } /* print out the classes */ for (i = 0; secclass_map[i].name; i++) fprintf(fout, "class %s\n", secclass_map[i].name); fprintf(fout, "\n"); initial_sid_to_string_len = sizeof(initial_sid_to_string) / sizeof (char *); /* print out the sids */ for (i = 1; i < initial_sid_to_string_len; i++) { const char *name = initial_sid_to_string[i]; if (name) fprintf(fout, "sid %s\n", name); else fprintf(fout, "sid unused%d\n", i); } fprintf(fout, "\n"); /* print out the class permissions */ for (i = 0; secclass_map[i].name; i++) { const struct security_class_mapping *map = &secclass_map[i]; fprintf(fout, "class %s\n", map->name); fprintf(fout, "{\n"); for (j = 0; map->perms[j]; j++) fprintf(fout, "\t%s\n", map->perms[j]); fprintf(fout, "}\n\n"); } fprintf(fout, "\n"); /* print out mls declarations and constraints */ if (mls) { fprintf(fout, "sensitivity s0;\n"); fprintf(fout, "sensitivity s1;\n"); fprintf(fout, "dominance { s0 s1 }\n"); fprintf(fout, "category c0;\n"); fprintf(fout, "category c1;\n"); fprintf(fout, "level s0:c0.c1;\n"); fprintf(fout, "level s1:c0.c1;\n"); #define SYSTEMLOW "s0" #define SYSTEMHIGH "s1:c0.c1" for (i = 0; secclass_map[i].name; i++) { const struct security_class_mapping *map = &secclass_map[i]; fprintf(fout, "mlsconstrain %s {\n", map->name); for (j = 0; map->perms[j]; j++) fprintf(fout, "\t%s\n", map->perms[j]); /* * This requires all subjects and objects to be * single-level (l2 eq h2), and that the subject * level dominate the object level (h1 dom h2) * in order to have any permissions to it. */ fprintf(fout, "} (l2 eq h2 and h1 dom h2);\n\n"); } } /* enable all policy capabilities */ for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++) fprintf(fout, "policycap %s;\n", selinux_policycap_names[i]); /* types, roles, and allows */ fprintf(fout, "type base_t;\n"); fprintf(fout, "role base_r;\n"); fprintf(fout, "role base_r types { base_t };\n"); for (i = 0; secclass_map[i].name; i++) fprintf(fout, "allow base_t base_t:%s *;\n", secclass_map[i].name); fprintf(fout, "user user_u roles { base_r }"); if (mls) fprintf(fout, " level %s range %s - %s", SYSTEMLOW, SYSTEMLOW, SYSTEMHIGH); fprintf(fout, ";\n"); #define SUBJUSERROLETYPE "user_u:base_r:base_t" #define OBJUSERROLETYPE "user_u:object_r:base_t" /* default sids */ for (i = 1; i < initial_sid_to_string_len; i++) { const char *name = initial_sid_to_string[i]; if (name) fprintf(fout, "sid %s ", name); else fprintf(fout, "sid unused%d\n", i); fprintf(fout, SUBJUSERROLETYPE "%s\n", mls ? ":" SYSTEMLOW : ""); } fprintf(fout, "\n"); #define FS_USE(behavior, fstype) \ fprintf(fout, "fs_use_%s %s " OBJUSERROLETYPE "%s;\n", \ behavior, fstype, mls ? ":" SYSTEMLOW : "") /* * Filesystems whose inode labels can be fetched via getxattr. */ #ifdef CONFIG_EXT2_FS_SECURITY FS_USE("xattr", "ext2"); #endif #ifdef CONFIG_EXT4_FS_SECURITY #ifdef CONFIG_EXT4_USE_FOR_EXT2 FS_USE("xattr", "ext2"); #endif FS_USE("xattr", "ext3"); FS_USE("xattr", "ext4"); #endif #ifdef CONFIG_JFS_SECURITY FS_USE("xattr", "jfs"); #endif #ifdef CONFIG_REISERFS_FS_SECURITY FS_USE("xattr", "reiserfs"); #endif #ifdef CONFIG_JFFS2_FS_SECURITY FS_USE("xattr", "jffs2"); #endif #ifdef CONFIG_XFS_FS FS_USE("xattr", "xfs"); #endif #ifdef CONFIG_GFS2_FS FS_USE("xattr", "gfs2"); #endif #ifdef CONFIG_BTRFS_FS FS_USE("xattr", "btrfs"); #endif #ifdef CONFIG_F2FS_FS_SECURITY FS_USE("xattr", "f2fs"); #endif #ifdef CONFIG_OCFS2_FS FS_USE("xattr", "ocsfs2"); #endif #ifdef CONFIG_OVERLAY_FS FS_USE("xattr", "overlay"); #endif #ifdef CONFIG_SQUASHFS_XATTR FS_USE("xattr", "squashfs"); #endif /* * Filesystems whose inodes are labeled from allocating task. */ FS_USE("task", "pipefs"); FS_USE("task", "sockfs"); /* * Filesystems whose inode labels are computed from both * the allocating task and the superblock label. */ #ifdef CONFIG_UNIX98_PTYS FS_USE("trans", "devpts"); #endif #ifdef CONFIG_HUGETLBFS FS_USE("trans", "hugetlbfs"); #endif #ifdef CONFIG_TMPFS FS_USE("trans", "tmpfs"); #endif #ifdef CONFIG_DEVTMPFS FS_USE("trans", "devtmpfs"); #endif #ifdef CONFIG_POSIX_MQUEUE FS_USE("trans", "mqueue"); #endif #define GENFSCON(fstype, prefix) \ fprintf(fout, "genfscon %s %s " OBJUSERROLETYPE "%s\n", \ fstype, prefix, mls ? ":" SYSTEMLOW : "") /* * Filesystems whose inodes are labeled from path prefix match * relative to the filesystem root. Depending on the filesystem, * only a single label for all inodes may be supported. Here * we list the filesystem types for which per-file labeling is * supported using genfscon; any other filesystem type can also * be added by only with a single entry for all of its inodes. */ #ifdef CONFIG_PROC_FS GENFSCON("proc", "/"); #endif #ifdef CONFIG_SECURITY_SELINUX GENFSCON("selinuxfs", "/"); #endif #ifdef CONFIG_SYSFS GENFSCON("sysfs", "/"); #endif #ifdef CONFIG_DEBUG_FS GENFSCON("debugfs", "/"); #endif #ifdef CONFIG_TRACING GENFSCON("tracefs", "/"); #endif #ifdef CONFIG_PSTORE GENFSCON("pstore", "/"); #endif GENFSCON("cgroup", "/"); GENFSCON("cgroup2", "/"); fclose(fout); fout = fopen(ctxout, "w"); if (!fout) { printf("Wrote policy, but cannot open %s for writing\n", ctxout); usage(argv[0]); } fprintf(fout, "/ " OBJUSERROLETYPE "%s\n", mls ? ":" SYSTEMLOW : ""); fprintf(fout, "/.* " OBJUSERROLETYPE "%s\n", mls ? ":" SYSTEMLOW : ""); fclose(fout); return 0; }
linux-master
scripts/selinux/mdp/mdp.c
// SPDX-License-Identifier: GPL-2.0 /* NOTE: we really do want to use the kernel headers here */ #define __EXPORTED_HEADERS__ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <ctype.h> struct security_class_mapping { const char *name; const char *perms[sizeof(unsigned) * 8 + 1]; }; #include "classmap.h" #include "initial_sid_to_string.h" const char *progname; static void usage(void) { printf("usage: %s flask.h av_permissions.h\n", progname); exit(1); } static char *stoupperx(const char *s) { char *s2 = strdup(s); char *p; if (!s2) { fprintf(stderr, "%s: out of memory\n", progname); exit(3); } for (p = s2; *p; p++) *p = toupper(*p); return s2; } int main(int argc, char *argv[]) { int i, j; int isids_len; FILE *fout; progname = argv[0]; if (argc < 3) usage(); fout = fopen(argv[1], "w"); if (!fout) { fprintf(stderr, "Could not open %s for writing: %s\n", argv[1], strerror(errno)); exit(2); } fprintf(fout, "/* This file is automatically generated. Do not edit. */\n"); fprintf(fout, "#ifndef _SELINUX_FLASK_H_\n#define _SELINUX_FLASK_H_\n\n"); for (i = 0; secclass_map[i].name; i++) { char *name = stoupperx(secclass_map[i].name); fprintf(fout, "#define SECCLASS_%-39s %2d\n", name, i+1); free(name); } fprintf(fout, "\n"); isids_len = sizeof(initial_sid_to_string) / sizeof(char *); for (i = 1; i < isids_len; i++) { const char *s = initial_sid_to_string[i]; if (s) { char *sidname = stoupperx(s); fprintf(fout, "#define SECINITSID_%-39s %2d\n", sidname, i); free(sidname); } } fprintf(fout, "\n#define SECINITSID_NUM %d\n", i-1); fprintf(fout, "\nstatic inline bool security_is_socket_class(u16 kern_tclass)\n"); fprintf(fout, "{\n"); fprintf(fout, "\tbool sock = false;\n\n"); fprintf(fout, "\tswitch (kern_tclass) {\n"); for (i = 0; secclass_map[i].name; i++) { static char s[] = "SOCKET"; int len, l; char *name = stoupperx(secclass_map[i].name); len = strlen(name); l = sizeof(s) - 1; if (len >= l && memcmp(name + len - l, s, l) == 0) fprintf(fout, "\tcase SECCLASS_%s:\n", name); free(name); } fprintf(fout, "\t\tsock = true;\n"); fprintf(fout, "\t\tbreak;\n"); fprintf(fout, "\tdefault:\n"); fprintf(fout, "\t\tbreak;\n"); fprintf(fout, "\t}\n\n"); fprintf(fout, "\treturn sock;\n"); fprintf(fout, "}\n"); fprintf(fout, "\n#endif\n"); if (fclose(fout) != 0) { fprintf(stderr, "Could not successfully close %s: %s\n", argv[1], strerror(errno)); exit(4); } fout = fopen(argv[2], "w"); if (!fout) { fprintf(stderr, "Could not open %s for writing: %s\n", argv[2], strerror(errno)); exit(5); } fprintf(fout, "/* This file is automatically generated. Do not edit. */\n"); fprintf(fout, "#ifndef _SELINUX_AV_PERMISSIONS_H_\n#define _SELINUX_AV_PERMISSIONS_H_\n\n"); for (i = 0; secclass_map[i].name; i++) { const struct security_class_mapping *map = &secclass_map[i]; int len; char *name = stoupperx(map->name); len = strlen(name); for (j = 0; map->perms[j]; j++) { char *permname; if (j >= 32) { fprintf(stderr, "Too many permissions to fit into an access vector at (%s, %s).\n", map->name, map->perms[j]); exit(5); } permname = stoupperx(map->perms[j]); fprintf(fout, "#define %s__%-*s 0x%08xU\n", name, 39-len, permname, 1U<<j); free(permname); } free(name); } fprintf(fout, "\n#endif\n"); if (fclose(fout) != 0) { fprintf(stderr, "Could not successfully close %s: %s\n", argv[2], strerror(errno)); exit(6); } exit(0); }
linux-master
scripts/selinux/genheaders/genheaders.c
#include <netinet/in.h> #ifdef __sun__ #include <inttypes.h> #else #include <stdint.h> #endif #include <ctype.h> #include <errno.h> #include <string.h> #include <limits.h> #include "modpost.h" /* * Stolen form Cryptographic API. * * MD4 Message Digest Algorithm (RFC1320). * * Implementation derived from Andrew Tridgell and Steve French's * CIFS MD4 implementation, and the cryptoapi implementation * originally based on the public domain implementation written * by Colin Plumb in 1993. * * Copyright (c) Andrew Tridgell 1997-1998. * Modified by Steve French ([email protected]) 2002 * Copyright (c) Cryptoapi developers. * Copyright (c) 2002 David S. Miller ([email protected]) * Copyright (c) 2002 James Morris <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ #define MD4_DIGEST_SIZE 16 #define MD4_HMAC_BLOCK_SIZE 64 #define MD4_BLOCK_WORDS 16 #define MD4_HASH_WORDS 4 struct md4_ctx { uint32_t hash[MD4_HASH_WORDS]; uint32_t block[MD4_BLOCK_WORDS]; uint64_t byte_count; }; static inline uint32_t lshift(uint32_t x, unsigned int s) { x &= 0xFFFFFFFF; return ((x << s) & 0xFFFFFFFF) | (x >> (32 - s)); } static inline uint32_t F(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | ((~x) & z); } static inline uint32_t G(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (x & z) | (y & z); } static inline uint32_t H(uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; } #define ROUND1(a,b,c,d,k,s) (a = lshift(a + F(b,c,d) + k, s)) #define ROUND2(a,b,c,d,k,s) (a = lshift(a + G(b,c,d) + k + (uint32_t)0x5A827999,s)) #define ROUND3(a,b,c,d,k,s) (a = lshift(a + H(b,c,d) + k + (uint32_t)0x6ED9EBA1,s)) /* XXX: this stuff can be optimized */ static inline void le32_to_cpu_array(uint32_t *buf, unsigned int words) { while (words--) { *buf = ntohl(*buf); buf++; } } static inline void cpu_to_le32_array(uint32_t *buf, unsigned int words) { while (words--) { *buf = htonl(*buf); buf++; } } static void md4_transform(uint32_t *hash, uint32_t const *in) { uint32_t a, b, c, d; a = hash[0]; b = hash[1]; c = hash[2]; d = hash[3]; ROUND1(a, b, c, d, in[0], 3); ROUND1(d, a, b, c, in[1], 7); ROUND1(c, d, a, b, in[2], 11); ROUND1(b, c, d, a, in[3], 19); ROUND1(a, b, c, d, in[4], 3); ROUND1(d, a, b, c, in[5], 7); ROUND1(c, d, a, b, in[6], 11); ROUND1(b, c, d, a, in[7], 19); ROUND1(a, b, c, d, in[8], 3); ROUND1(d, a, b, c, in[9], 7); ROUND1(c, d, a, b, in[10], 11); ROUND1(b, c, d, a, in[11], 19); ROUND1(a, b, c, d, in[12], 3); ROUND1(d, a, b, c, in[13], 7); ROUND1(c, d, a, b, in[14], 11); ROUND1(b, c, d, a, in[15], 19); ROUND2(a, b, c, d,in[ 0], 3); ROUND2(d, a, b, c, in[4], 5); ROUND2(c, d, a, b, in[8], 9); ROUND2(b, c, d, a, in[12], 13); ROUND2(a, b, c, d, in[1], 3); ROUND2(d, a, b, c, in[5], 5); ROUND2(c, d, a, b, in[9], 9); ROUND2(b, c, d, a, in[13], 13); ROUND2(a, b, c, d, in[2], 3); ROUND2(d, a, b, c, in[6], 5); ROUND2(c, d, a, b, in[10], 9); ROUND2(b, c, d, a, in[14], 13); ROUND2(a, b, c, d, in[3], 3); ROUND2(d, a, b, c, in[7], 5); ROUND2(c, d, a, b, in[11], 9); ROUND2(b, c, d, a, in[15], 13); ROUND3(a, b, c, d,in[ 0], 3); ROUND3(d, a, b, c, in[8], 9); ROUND3(c, d, a, b, in[4], 11); ROUND3(b, c, d, a, in[12], 15); ROUND3(a, b, c, d, in[2], 3); ROUND3(d, a, b, c, in[10], 9); ROUND3(c, d, a, b, in[6], 11); ROUND3(b, c, d, a, in[14], 15); ROUND3(a, b, c, d, in[1], 3); ROUND3(d, a, b, c, in[9], 9); ROUND3(c, d, a, b, in[5], 11); ROUND3(b, c, d, a, in[13], 15); ROUND3(a, b, c, d, in[3], 3); ROUND3(d, a, b, c, in[11], 9); ROUND3(c, d, a, b, in[7], 11); ROUND3(b, c, d, a, in[15], 15); hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; } static inline void md4_transform_helper(struct md4_ctx *ctx) { le32_to_cpu_array(ctx->block, ARRAY_SIZE(ctx->block)); md4_transform(ctx->hash, ctx->block); } static void md4_init(struct md4_ctx *mctx) { mctx->hash[0] = 0x67452301; mctx->hash[1] = 0xefcdab89; mctx->hash[2] = 0x98badcfe; mctx->hash[3] = 0x10325476; mctx->byte_count = 0; } static void md4_update(struct md4_ctx *mctx, const unsigned char *data, unsigned int len) { const uint32_t avail = sizeof(mctx->block) - (mctx->byte_count & 0x3f); mctx->byte_count += len; if (avail > len) { memcpy((char *)mctx->block + (sizeof(mctx->block) - avail), data, len); return; } memcpy((char *)mctx->block + (sizeof(mctx->block) - avail), data, avail); md4_transform_helper(mctx); data += avail; len -= avail; while (len >= sizeof(mctx->block)) { memcpy(mctx->block, data, sizeof(mctx->block)); md4_transform_helper(mctx); data += sizeof(mctx->block); len -= sizeof(mctx->block); } memcpy(mctx->block, data, len); } static void md4_final_ascii(struct md4_ctx *mctx, char *out, unsigned int len) { const unsigned int offset = mctx->byte_count & 0x3f; char *p = (char *)mctx->block + offset; int padding = 56 - (offset + 1); *p++ = 0x80; if (padding < 0) { memset(p, 0x00, padding + sizeof (uint64_t)); md4_transform_helper(mctx); p = (char *)mctx->block; padding = 56; } memset(p, 0, padding); mctx->block[14] = mctx->byte_count << 3; mctx->block[15] = mctx->byte_count >> 29; le32_to_cpu_array(mctx->block, (sizeof(mctx->block) - sizeof(uint64_t)) / sizeof(uint32_t)); md4_transform(mctx->hash, mctx->block); cpu_to_le32_array(mctx->hash, ARRAY_SIZE(mctx->hash)); snprintf(out, len, "%08X%08X%08X%08X", mctx->hash[0], mctx->hash[1], mctx->hash[2], mctx->hash[3]); } static inline void add_char(unsigned char c, struct md4_ctx *md) { md4_update(md, &c, 1); } static int parse_string(const char *file, unsigned long len, struct md4_ctx *md) { unsigned long i; add_char(file[0], md); for (i = 1; i < len; i++) { add_char(file[i], md); if (file[i] == '"' && file[i-1] != '\\') break; } return i; } static int parse_comment(const char *file, unsigned long len) { unsigned long i; for (i = 2; i < len; i++) { if (file[i-1] == '*' && file[i] == '/') break; } return i; } /* FIXME: Handle .s files differently (eg. # starts comments) --RR */ static int parse_file(const char *fname, struct md4_ctx *md) { char *file; unsigned long i, len; file = read_text_file(fname); len = strlen(file); for (i = 0; i < len; i++) { /* Collapse and ignore \ and CR. */ if (file[i] == '\\' && (i+1 < len) && file[i+1] == '\n') { i++; continue; } /* Ignore whitespace */ if (isspace(file[i])) continue; /* Handle strings as whole units */ if (file[i] == '"') { i += parse_string(file+i, len - i, md); continue; } /* Comments: ignore */ if (file[i] == '/' && file[i+1] == '*') { i += parse_comment(file+i, len - i); continue; } add_char(file[i], md); } free(file); return 1; } /* Check whether the file is a static library or not */ static bool is_static_library(const char *objfile) { int len = strlen(objfile); return objfile[len - 2] == '.' && objfile[len - 1] == 'a'; } /* We have dir/file.o. Open dir/.file.o.cmd, look for source_ and deps_ line * to figure out source files. */ static int parse_source_files(const char *objfile, struct md4_ctx *md) { char *cmd, *file, *line, *dir, *pos; const char *base; int dirlen, ret = 0, check_files = 0; cmd = NOFAIL(malloc(strlen(objfile) + sizeof("..cmd"))); base = strrchr(objfile, '/'); if (base) { base++; dirlen = base - objfile; sprintf(cmd, "%.*s.%s.cmd", dirlen, objfile, base); } else { dirlen = 0; sprintf(cmd, ".%s.cmd", objfile); } dir = NOFAIL(malloc(dirlen + 1)); strncpy(dir, objfile, dirlen); dir[dirlen] = '\0'; file = read_text_file(cmd); pos = file; /* Sum all files in the same dir or subdirs. */ while ((line = get_line(&pos))) { char* p = line; if (strncmp(line, "source_", sizeof("source_")-1) == 0) { p = strrchr(line, ' '); if (!p) { warn("malformed line: %s\n", line); goto out_file; } p++; if (!parse_file(p, md)) { warn("could not open %s: %s\n", p, strerror(errno)); goto out_file; } continue; } if (strncmp(line, "deps_", sizeof("deps_")-1) == 0) { check_files = 1; continue; } if (!check_files) continue; /* Continue until line does not end with '\' */ if ( *(p + strlen(p)-1) != '\\') break; /* Terminate line at first space, to get rid of final ' \' */ while (*p) { if (isspace(*p)) { *p = '\0'; break; } p++; } /* Check if this file is in same dir as objfile */ if ((strstr(line, dir)+strlen(dir)-1) == strrchr(line, '/')) { if (!parse_file(line, md)) { warn("could not open %s: %s\n", line, strerror(errno)); goto out_file; } } } /* Everyone parsed OK */ ret = 1; out_file: free(file); free(dir); free(cmd); return ret; } /* Calc and record src checksum. */ void get_src_version(const char *modname, char sum[], unsigned sumlen) { char *buf; struct md4_ctx md; char *fname; char filelist[PATH_MAX + 1]; /* objects for a module are listed in the first line of *.mod file. */ snprintf(filelist, sizeof(filelist), "%s.mod", modname); buf = read_text_file(filelist); md4_init(&md); while ((fname = strsep(&buf, "\n"))) { if (!*fname) continue; if (!(is_static_library(fname)) && !parse_source_files(fname, &md)) goto free; } md4_final_ascii(&md, sum, sumlen); free: free(buf); }
linux-master
scripts/mod/sumversion.c
/* Simple code to turn various tables in an ELF file into alias definitions. * This deals with kernel datastructures where they should be * dealt with: in the kernel source. * * Copyright 2002-2003 Rusty Russell, IBM Corporation * 2003 Kai Germaschewski * * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. */ #include "modpost.h" #include "devicetable-offsets.h" /* We use the ELF typedefs for kernel_ulong_t but bite the bullet and * use either stdint.h or inttypes.h for the rest. */ #if KERNEL_ELFCLASS == ELFCLASS32 typedef Elf32_Addr kernel_ulong_t; #define BITS_PER_LONG 32 #else typedef Elf64_Addr kernel_ulong_t; #define BITS_PER_LONG 64 #endif #ifdef __sun__ #include <inttypes.h> #else #include <stdint.h> #endif #include <ctype.h> #include <stdbool.h> typedef uint32_t __u32; typedef uint16_t __u16; typedef unsigned char __u8; /* UUID types for backward compatibility, don't use in new code */ typedef struct { __u8 b[16]; } guid_t; typedef struct { __u8 b[16]; } uuid_t; #define UUID_STRING_LEN 36 /* MEI UUID type, don't use anywhere else */ typedef struct { __u8 b[16]; } uuid_le; /* Big exception to the "don't include kernel headers into userspace, which * even potentially has different endianness and word sizes, since * we handle those differences explicitly below */ #include "../../include/linux/mod_devicetable.h" /* This array collects all instances that use the generic do_table */ struct devtable { const char *device_id; /* name of table, __mod_<name>__*_device_table. */ unsigned long id_size; int (*do_entry)(const char *filename, void *symval, char *alias); }; /* Size of alias provided to do_entry functions */ #define ALIAS_SIZE 500 /* Define a variable f that holds the value of field f of struct devid * based at address m. */ #define DEF_FIELD(m, devid, f) \ typeof(((struct devid *)0)->f) f = TO_NATIVE(*(typeof(f) *)((m) + OFF_##devid##_##f)) /* Define a variable v that holds the address of field f of struct devid * based at address m. Due to the way typeof works, for a field of type * T[N] the variable has type T(*)[N], _not_ T*. */ #define DEF_FIELD_ADDR_VAR(m, devid, f, v) \ typeof(((struct devid *)0)->f) *v = ((m) + OFF_##devid##_##f) /* Define a variable f that holds the address of field f of struct devid * based at address m. Due to the way typeof works, for a field of type * T[N] the variable has type T(*)[N], _not_ T*. */ #define DEF_FIELD_ADDR(m, devid, f) \ DEF_FIELD_ADDR_VAR(m, devid, f, f) #define ADD(str, sep, cond, field) \ do { \ strcat(str, sep); \ if (cond) \ sprintf(str + strlen(str), \ sizeof(field) == 1 ? "%02X" : \ sizeof(field) == 2 ? "%04X" : \ sizeof(field) == 4 ? "%08X" : "", \ field); \ else \ sprintf(str + strlen(str), "*"); \ } while(0) /* End in a wildcard, for future extension */ static inline void add_wildcard(char *str) { int len = strlen(str); if (str[len - 1] != '*') strcat(str + len, "*"); } static inline void add_uuid(char *str, uuid_le uuid) { int len = strlen(str); sprintf(str + len, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid.b[3], uuid.b[2], uuid.b[1], uuid.b[0], uuid.b[5], uuid.b[4], uuid.b[7], uuid.b[6], uuid.b[8], uuid.b[9], uuid.b[10], uuid.b[11], uuid.b[12], uuid.b[13], uuid.b[14], uuid.b[15]); } static inline void add_guid(char *str, guid_t guid) { int len = strlen(str); sprintf(str + len, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid.b[3], guid.b[2], guid.b[1], guid.b[0], guid.b[5], guid.b[4], guid.b[7], guid.b[6], guid.b[8], guid.b[9], guid.b[10], guid.b[11], guid.b[12], guid.b[13], guid.b[14], guid.b[15]); } /** * Check that sizeof(device_id type) are consistent with size of section * in .o file. If in-consistent then userspace and kernel does not agree * on actual size which is a bug. * Also verify that the final entry in the table is all zeros. * Ignore both checks if build host differ from target host and size differs. **/ static void device_id_check(const char *modname, const char *device_id, unsigned long size, unsigned long id_size, void *symval) { int i; if (size % id_size || size < id_size) { fatal("%s: sizeof(struct %s_device_id)=%lu is not a modulo of the size of section __mod_%s__<identifier>_device_table=%lu.\n" "Fix definition of struct %s_device_id in mod_devicetable.h\n", modname, device_id, id_size, device_id, size, device_id); } /* Verify last one is a terminator */ for (i = 0; i < id_size; i++ ) { if (*(uint8_t*)(symval+size-id_size+i)) { fprintf(stderr, "%s: struct %s_device_id is %lu bytes. The last of %lu is:\n", modname, device_id, id_size, size / id_size); for (i = 0; i < id_size; i++ ) fprintf(stderr,"0x%02x ", *(uint8_t*)(symval+size-id_size+i) ); fprintf(stderr,"\n"); fatal("%s: struct %s_device_id is not terminated with a NULL entry!\n", modname, device_id); } } } /* USB is special because the bcdDevice can be matched against a numeric range */ /* Looks like "usb:vNpNdNdcNdscNdpNicNiscNipNinN" */ static void do_usb_entry(void *symval, unsigned int bcdDevice_initial, int bcdDevice_initial_digits, unsigned char range_lo, unsigned char range_hi, unsigned char max, struct module *mod) { char alias[500]; DEF_FIELD(symval, usb_device_id, match_flags); DEF_FIELD(symval, usb_device_id, idVendor); DEF_FIELD(symval, usb_device_id, idProduct); DEF_FIELD(symval, usb_device_id, bcdDevice_lo); DEF_FIELD(symval, usb_device_id, bDeviceClass); DEF_FIELD(symval, usb_device_id, bDeviceSubClass); DEF_FIELD(symval, usb_device_id, bDeviceProtocol); DEF_FIELD(symval, usb_device_id, bInterfaceClass); DEF_FIELD(symval, usb_device_id, bInterfaceSubClass); DEF_FIELD(symval, usb_device_id, bInterfaceProtocol); DEF_FIELD(symval, usb_device_id, bInterfaceNumber); strcpy(alias, "usb:"); ADD(alias, "v", match_flags&USB_DEVICE_ID_MATCH_VENDOR, idVendor); ADD(alias, "p", match_flags&USB_DEVICE_ID_MATCH_PRODUCT, idProduct); strcat(alias, "d"); if (bcdDevice_initial_digits) sprintf(alias + strlen(alias), "%0*X", bcdDevice_initial_digits, bcdDevice_initial); if (range_lo == range_hi) sprintf(alias + strlen(alias), "%X", range_lo); else if (range_lo > 0 || range_hi < max) { if (range_lo > 0x9 || range_hi < 0xA) sprintf(alias + strlen(alias), "[%X-%X]", range_lo, range_hi); else { sprintf(alias + strlen(alias), range_lo < 0x9 ? "[%X-9" : "[%X", range_lo); sprintf(alias + strlen(alias), range_hi > 0xA ? "A-%X]" : "%X]", range_hi); } } if (bcdDevice_initial_digits < (sizeof(bcdDevice_lo) * 2 - 1)) strcat(alias, "*"); ADD(alias, "dc", match_flags&USB_DEVICE_ID_MATCH_DEV_CLASS, bDeviceClass); ADD(alias, "dsc", match_flags&USB_DEVICE_ID_MATCH_DEV_SUBCLASS, bDeviceSubClass); ADD(alias, "dp", match_flags&USB_DEVICE_ID_MATCH_DEV_PROTOCOL, bDeviceProtocol); ADD(alias, "ic", match_flags&USB_DEVICE_ID_MATCH_INT_CLASS, bInterfaceClass); ADD(alias, "isc", match_flags&USB_DEVICE_ID_MATCH_INT_SUBCLASS, bInterfaceSubClass); ADD(alias, "ip", match_flags&USB_DEVICE_ID_MATCH_INT_PROTOCOL, bInterfaceProtocol); ADD(alias, "in", match_flags&USB_DEVICE_ID_MATCH_INT_NUMBER, bInterfaceNumber); add_wildcard(alias); buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"%s\");\n", alias); } /* Handles increment/decrement of BCD formatted integers */ /* Returns the previous value, so it works like i++ or i-- */ static unsigned int incbcd(unsigned int *bcd, int inc, unsigned char max, size_t chars) { unsigned int init = *bcd, i, j; unsigned long long c, dec = 0; /* If bcd is not in BCD format, just increment */ if (max > 0x9) { *bcd += inc; return init; } /* Convert BCD to Decimal */ for (i=0 ; i < chars ; i++) { c = (*bcd >> (i << 2)) & 0xf; c = c > 9 ? 9 : c; /* force to bcd just in case */ for (j=0 ; j < i ; j++) c = c * 10; dec += c; } /* Do our increment/decrement */ dec += inc; *bcd = 0; /* Convert back to BCD */ for (i=0 ; i < chars ; i++) { for (c=1,j=0 ; j < i ; j++) c = c * 10; c = (dec / c) % 10; *bcd += c << (i << 2); } return init; } static void do_usb_entry_multi(void *symval, struct module *mod) { unsigned int devlo, devhi; unsigned char chi, clo, max; int ndigits; DEF_FIELD(symval, usb_device_id, match_flags); DEF_FIELD(symval, usb_device_id, idVendor); DEF_FIELD(symval, usb_device_id, idProduct); DEF_FIELD(symval, usb_device_id, bcdDevice_lo); DEF_FIELD(symval, usb_device_id, bcdDevice_hi); DEF_FIELD(symval, usb_device_id, bDeviceClass); DEF_FIELD(symval, usb_device_id, bInterfaceClass); devlo = match_flags & USB_DEVICE_ID_MATCH_DEV_LO ? bcdDevice_lo : 0x0U; devhi = match_flags & USB_DEVICE_ID_MATCH_DEV_HI ? bcdDevice_hi : ~0x0U; /* Figure out if this entry is in bcd or hex format */ max = 0x9; /* Default to decimal format */ for (ndigits = 0 ; ndigits < sizeof(bcdDevice_lo) * 2 ; ndigits++) { clo = (devlo >> (ndigits << 2)) & 0xf; chi = ((devhi > 0x9999 ? 0x9999 : devhi) >> (ndigits << 2)) & 0xf; if (clo > max || chi > max) { max = 0xf; break; } } /* * Some modules (visor) have empty slots as placeholder for * run-time specification that results in catch-all alias */ if (!(idVendor | idProduct | bDeviceClass | bInterfaceClass)) return; /* Convert numeric bcdDevice range into fnmatch-able pattern(s) */ for (ndigits = sizeof(bcdDevice_lo) * 2 - 1; devlo <= devhi; ndigits--) { clo = devlo & 0xf; chi = devhi & 0xf; if (chi > max) /* If we are in bcd mode, truncate if necessary */ chi = max; devlo >>= 4; devhi >>= 4; if (devlo == devhi || !ndigits) { do_usb_entry(symval, devlo, ndigits, clo, chi, max, mod); break; } if (clo > 0x0) do_usb_entry(symval, incbcd(&devlo, 1, max, sizeof(bcdDevice_lo) * 2), ndigits, clo, max, max, mod); if (chi < max) do_usb_entry(symval, incbcd(&devhi, -1, max, sizeof(bcdDevice_lo) * 2), ndigits, 0x0, chi, max, mod); } } static void do_usb_table(void *symval, unsigned long size, struct module *mod) { unsigned int i; const unsigned long id_size = SIZE_usb_device_id; device_id_check(mod->name, "usb", size, id_size, symval); /* Leave last one: it's the terminator. */ size -= id_size; for (i = 0; i < size; i += id_size) do_usb_entry_multi(symval + i, mod); } static void do_of_entry_multi(void *symval, struct module *mod) { char alias[500]; int len; char *tmp; DEF_FIELD_ADDR(symval, of_device_id, name); DEF_FIELD_ADDR(symval, of_device_id, type); DEF_FIELD_ADDR(symval, of_device_id, compatible); len = sprintf(alias, "of:N%sT%s", (*name)[0] ? *name : "*", (*type)[0] ? *type : "*"); if ((*compatible)[0]) sprintf(&alias[len], "%sC%s", (*type)[0] ? "*" : "", *compatible); /* Replace all whitespace with underscores */ for (tmp = alias; tmp && *tmp; tmp++) if (isspace(*tmp)) *tmp = '_'; buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"%s\");\n", alias); strcat(alias, "C"); add_wildcard(alias); buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"%s\");\n", alias); } static void do_of_table(void *symval, unsigned long size, struct module *mod) { unsigned int i; const unsigned long id_size = SIZE_of_device_id; device_id_check(mod->name, "of", size, id_size, symval); /* Leave last one: it's the terminator. */ size -= id_size; for (i = 0; i < size; i += id_size) do_of_entry_multi(symval + i, mod); } /* Looks like: hid:bNvNpN */ static int do_hid_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, hid_device_id, bus); DEF_FIELD(symval, hid_device_id, group); DEF_FIELD(symval, hid_device_id, vendor); DEF_FIELD(symval, hid_device_id, product); sprintf(alias, "hid:"); ADD(alias, "b", bus != HID_BUS_ANY, bus); ADD(alias, "g", group != HID_GROUP_ANY, group); ADD(alias, "v", vendor != HID_ANY_ID, vendor); ADD(alias, "p", product != HID_ANY_ID, product); return 1; } /* Looks like: ieee1394:venNmoNspNverN */ static int do_ieee1394_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ieee1394_device_id, match_flags); DEF_FIELD(symval, ieee1394_device_id, vendor_id); DEF_FIELD(symval, ieee1394_device_id, model_id); DEF_FIELD(symval, ieee1394_device_id, specifier_id); DEF_FIELD(symval, ieee1394_device_id, version); strcpy(alias, "ieee1394:"); ADD(alias, "ven", match_flags & IEEE1394_MATCH_VENDOR_ID, vendor_id); ADD(alias, "mo", match_flags & IEEE1394_MATCH_MODEL_ID, model_id); ADD(alias, "sp", match_flags & IEEE1394_MATCH_SPECIFIER_ID, specifier_id); ADD(alias, "ver", match_flags & IEEE1394_MATCH_VERSION, version); add_wildcard(alias); return 1; } /* Looks like: pci:vNdNsvNsdNbcNscNiN or <prefix>_pci:vNdNsvNsdNbcNscNiN. */ static int do_pci_entry(const char *filename, void *symval, char *alias) { /* Class field can be divided into these three. */ unsigned char baseclass, subclass, interface, baseclass_mask, subclass_mask, interface_mask; DEF_FIELD(symval, pci_device_id, vendor); DEF_FIELD(symval, pci_device_id, device); DEF_FIELD(symval, pci_device_id, subvendor); DEF_FIELD(symval, pci_device_id, subdevice); DEF_FIELD(symval, pci_device_id, class); DEF_FIELD(symval, pci_device_id, class_mask); DEF_FIELD(symval, pci_device_id, override_only); switch (override_only) { case 0: strcpy(alias, "pci:"); break; case PCI_ID_F_VFIO_DRIVER_OVERRIDE: strcpy(alias, "vfio_pci:"); break; default: warn("Unknown PCI driver_override alias %08X\n", override_only); return 0; } ADD(alias, "v", vendor != PCI_ANY_ID, vendor); ADD(alias, "d", device != PCI_ANY_ID, device); ADD(alias, "sv", subvendor != PCI_ANY_ID, subvendor); ADD(alias, "sd", subdevice != PCI_ANY_ID, subdevice); baseclass = (class) >> 16; baseclass_mask = (class_mask) >> 16; subclass = (class) >> 8; subclass_mask = (class_mask) >> 8; interface = class; interface_mask = class_mask; if ((baseclass_mask != 0 && baseclass_mask != 0xFF) || (subclass_mask != 0 && subclass_mask != 0xFF) || (interface_mask != 0 && interface_mask != 0xFF)) { warn("Can't handle masks in %s:%04X\n", filename, class_mask); return 0; } ADD(alias, "bc", baseclass_mask == 0xFF, baseclass); ADD(alias, "sc", subclass_mask == 0xFF, subclass); ADD(alias, "i", interface_mask == 0xFF, interface); add_wildcard(alias); return 1; } /* looks like: "ccw:tNmNdtNdmN" */ static int do_ccw_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ccw_device_id, match_flags); DEF_FIELD(symval, ccw_device_id, cu_type); DEF_FIELD(symval, ccw_device_id, cu_model); DEF_FIELD(symval, ccw_device_id, dev_type); DEF_FIELD(symval, ccw_device_id, dev_model); strcpy(alias, "ccw:"); ADD(alias, "t", match_flags&CCW_DEVICE_ID_MATCH_CU_TYPE, cu_type); ADD(alias, "m", match_flags&CCW_DEVICE_ID_MATCH_CU_MODEL, cu_model); ADD(alias, "dt", match_flags&CCW_DEVICE_ID_MATCH_DEVICE_TYPE, dev_type); ADD(alias, "dm", match_flags&CCW_DEVICE_ID_MATCH_DEVICE_MODEL, dev_model); add_wildcard(alias); return 1; } /* looks like: "ap:tN" */ static int do_ap_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ap_device_id, dev_type); sprintf(alias, "ap:t%02X*", dev_type); return 1; } /* looks like: "css:tN" */ static int do_css_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, css_device_id, type); sprintf(alias, "css:t%01X", type); return 1; } /* Looks like: "serio:tyNprNidNexN" */ static int do_serio_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, serio_device_id, type); DEF_FIELD(symval, serio_device_id, proto); DEF_FIELD(symval, serio_device_id, id); DEF_FIELD(symval, serio_device_id, extra); strcpy(alias, "serio:"); ADD(alias, "ty", type != SERIO_ANY, type); ADD(alias, "pr", proto != SERIO_ANY, proto); ADD(alias, "id", id != SERIO_ANY, id); ADD(alias, "ex", extra != SERIO_ANY, extra); add_wildcard(alias); return 1; } /* looks like: "acpi:ACPI0003" or "acpi:PNP0C0B" or "acpi:LNXVIDEO" or * "acpi:bbsspp" (bb=base-class, ss=sub-class, pp=prog-if) * * NOTE: Each driver should use one of the following : _HID, _CIDs * or _CLS. Also, bb, ss, and pp can be substituted with ?? * as don't care byte. */ static int do_acpi_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, acpi_device_id, id); DEF_FIELD_ADDR(symval, acpi_device_id, cls); DEF_FIELD_ADDR(symval, acpi_device_id, cls_msk); if (id && strlen((const char *)*id)) sprintf(alias, "acpi*:%s:*", *id); else if (cls) { int i, byte_shift, cnt = 0; unsigned int msk; sprintf(&alias[cnt], "acpi*:"); cnt = 6; for (i = 1; i <= 3; i++) { byte_shift = 8 * (3-i); msk = (*cls_msk >> byte_shift) & 0xFF; if (msk) sprintf(&alias[cnt], "%02x", (*cls >> byte_shift) & 0xFF); else sprintf(&alias[cnt], "??"); cnt += 2; } sprintf(&alias[cnt], ":*"); } return 1; } /* looks like: "pnp:dD" */ static void do_pnp_device_entry(void *symval, unsigned long size, struct module *mod) { const unsigned long id_size = SIZE_pnp_device_id; const unsigned int count = (size / id_size)-1; unsigned int i; device_id_check(mod->name, "pnp", size, id_size, symval); for (i = 0; i < count; i++) { DEF_FIELD_ADDR(symval + i*id_size, pnp_device_id, id); char acpi_id[sizeof(*id)]; int j; buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"pnp:d%s*\");\n", *id); /* fix broken pnp bus lowercasing */ for (j = 0; j < sizeof(acpi_id); j++) acpi_id[j] = toupper((*id)[j]); buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"acpi*:%s:*\");\n", acpi_id); } } /* looks like: "pnp:dD" for every device of the card */ static void do_pnp_card_entries(void *symval, unsigned long size, struct module *mod) { const unsigned long id_size = SIZE_pnp_card_device_id; const unsigned int count = (size / id_size)-1; unsigned int i; device_id_check(mod->name, "pnp", size, id_size, symval); for (i = 0; i < count; i++) { unsigned int j; DEF_FIELD_ADDR(symval + i * id_size, pnp_card_device_id, devs); for (j = 0; j < PNP_MAX_DEVICES; j++) { const char *id = (char *)(*devs)[j].id; int i2, j2; int dup = 0; if (!id[0]) break; /* find duplicate, already added value */ for (i2 = 0; i2 < i && !dup; i2++) { DEF_FIELD_ADDR_VAR(symval + i2 * id_size, pnp_card_device_id, devs, devs_dup); for (j2 = 0; j2 < PNP_MAX_DEVICES; j2++) { const char *id2 = (char *)(*devs_dup)[j2].id; if (!id2[0]) break; if (!strcmp(id, id2)) { dup = 1; break; } } } /* add an individual alias for every device entry */ if (!dup) { char acpi_id[PNP_ID_LEN]; int k; buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"pnp:d%s*\");\n", id); /* fix broken pnp bus lowercasing */ for (k = 0; k < sizeof(acpi_id); k++) acpi_id[k] = toupper(id[k]); buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"acpi*:%s:*\");\n", acpi_id); } } } } /* Looks like: pcmcia:mNcNfNfnNpfnNvaNvbNvcNvdN. */ static int do_pcmcia_entry(const char *filename, void *symval, char *alias) { unsigned int i; DEF_FIELD(symval, pcmcia_device_id, match_flags); DEF_FIELD(symval, pcmcia_device_id, manf_id); DEF_FIELD(symval, pcmcia_device_id, card_id); DEF_FIELD(symval, pcmcia_device_id, func_id); DEF_FIELD(symval, pcmcia_device_id, function); DEF_FIELD(symval, pcmcia_device_id, device_no); DEF_FIELD_ADDR(symval, pcmcia_device_id, prod_id_hash); for (i=0; i<4; i++) { (*prod_id_hash)[i] = TO_NATIVE((*prod_id_hash)[i]); } strcpy(alias, "pcmcia:"); ADD(alias, "m", match_flags & PCMCIA_DEV_ID_MATCH_MANF_ID, manf_id); ADD(alias, "c", match_flags & PCMCIA_DEV_ID_MATCH_CARD_ID, card_id); ADD(alias, "f", match_flags & PCMCIA_DEV_ID_MATCH_FUNC_ID, func_id); ADD(alias, "fn", match_flags & PCMCIA_DEV_ID_MATCH_FUNCTION, function); ADD(alias, "pfn", match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO, device_no); ADD(alias, "pa", match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID1, (*prod_id_hash)[0]); ADD(alias, "pb", match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID2, (*prod_id_hash)[1]); ADD(alias, "pc", match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID3, (*prod_id_hash)[2]); ADD(alias, "pd", match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID4, (*prod_id_hash)[3]); add_wildcard(alias); return 1; } static int do_vio_entry(const char *filename, void *symval, char *alias) { char *tmp; DEF_FIELD_ADDR(symval, vio_device_id, type); DEF_FIELD_ADDR(symval, vio_device_id, compat); sprintf(alias, "vio:T%sS%s", (*type)[0] ? *type : "*", (*compat)[0] ? *compat : "*"); /* Replace all whitespace with underscores */ for (tmp = alias; tmp && *tmp; tmp++) if (isspace (*tmp)) *tmp = '_'; add_wildcard(alias); return 1; } static void do_input(char *alias, kernel_ulong_t *arr, unsigned int min, unsigned int max) { unsigned int i; for (i = min / BITS_PER_LONG; i < max / BITS_PER_LONG + 1; i++) arr[i] = TO_NATIVE(arr[i]); for (i = min; i < max; i++) if (arr[i / BITS_PER_LONG] & (1L << (i%BITS_PER_LONG))) sprintf(alias + strlen(alias), "%X,*", i); } /* input:b0v0p0e0-eXkXrXaXmXlXsXfXwX where X is comma-separated %02X. */ static int do_input_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, input_device_id, flags); DEF_FIELD(symval, input_device_id, bustype); DEF_FIELD(symval, input_device_id, vendor); DEF_FIELD(symval, input_device_id, product); DEF_FIELD(symval, input_device_id, version); DEF_FIELD_ADDR(symval, input_device_id, evbit); DEF_FIELD_ADDR(symval, input_device_id, keybit); DEF_FIELD_ADDR(symval, input_device_id, relbit); DEF_FIELD_ADDR(symval, input_device_id, absbit); DEF_FIELD_ADDR(symval, input_device_id, mscbit); DEF_FIELD_ADDR(symval, input_device_id, ledbit); DEF_FIELD_ADDR(symval, input_device_id, sndbit); DEF_FIELD_ADDR(symval, input_device_id, ffbit); DEF_FIELD_ADDR(symval, input_device_id, swbit); sprintf(alias, "input:"); ADD(alias, "b", flags & INPUT_DEVICE_ID_MATCH_BUS, bustype); ADD(alias, "v", flags & INPUT_DEVICE_ID_MATCH_VENDOR, vendor); ADD(alias, "p", flags & INPUT_DEVICE_ID_MATCH_PRODUCT, product); ADD(alias, "e", flags & INPUT_DEVICE_ID_MATCH_VERSION, version); sprintf(alias + strlen(alias), "-e*"); if (flags & INPUT_DEVICE_ID_MATCH_EVBIT) do_input(alias, *evbit, 0, INPUT_DEVICE_ID_EV_MAX); sprintf(alias + strlen(alias), "k*"); if (flags & INPUT_DEVICE_ID_MATCH_KEYBIT) do_input(alias, *keybit, INPUT_DEVICE_ID_KEY_MIN_INTERESTING, INPUT_DEVICE_ID_KEY_MAX); sprintf(alias + strlen(alias), "r*"); if (flags & INPUT_DEVICE_ID_MATCH_RELBIT) do_input(alias, *relbit, 0, INPUT_DEVICE_ID_REL_MAX); sprintf(alias + strlen(alias), "a*"); if (flags & INPUT_DEVICE_ID_MATCH_ABSBIT) do_input(alias, *absbit, 0, INPUT_DEVICE_ID_ABS_MAX); sprintf(alias + strlen(alias), "m*"); if (flags & INPUT_DEVICE_ID_MATCH_MSCIT) do_input(alias, *mscbit, 0, INPUT_DEVICE_ID_MSC_MAX); sprintf(alias + strlen(alias), "l*"); if (flags & INPUT_DEVICE_ID_MATCH_LEDBIT) do_input(alias, *ledbit, 0, INPUT_DEVICE_ID_LED_MAX); sprintf(alias + strlen(alias), "s*"); if (flags & INPUT_DEVICE_ID_MATCH_SNDBIT) do_input(alias, *sndbit, 0, INPUT_DEVICE_ID_SND_MAX); sprintf(alias + strlen(alias), "f*"); if (flags & INPUT_DEVICE_ID_MATCH_FFBIT) do_input(alias, *ffbit, 0, INPUT_DEVICE_ID_FF_MAX); sprintf(alias + strlen(alias), "w*"); if (flags & INPUT_DEVICE_ID_MATCH_SWBIT) do_input(alias, *swbit, 0, INPUT_DEVICE_ID_SW_MAX); return 1; } static int do_eisa_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, eisa_device_id, sig); if (sig[0]) sprintf(alias, EISA_DEVICE_MODALIAS_FMT "*", *sig); else strcat(alias, "*"); return 1; } /* Looks like: parisc:tNhvNrevNsvN */ static int do_parisc_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, parisc_device_id, hw_type); DEF_FIELD(symval, parisc_device_id, hversion); DEF_FIELD(symval, parisc_device_id, hversion_rev); DEF_FIELD(symval, parisc_device_id, sversion); strcpy(alias, "parisc:"); ADD(alias, "t", hw_type != PA_HWTYPE_ANY_ID, hw_type); ADD(alias, "hv", hversion != PA_HVERSION_ANY_ID, hversion); ADD(alias, "rev", hversion_rev != PA_HVERSION_REV_ANY_ID, hversion_rev); ADD(alias, "sv", sversion != PA_SVERSION_ANY_ID, sversion); add_wildcard(alias); return 1; } /* Looks like: sdio:cNvNdN. */ static int do_sdio_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, sdio_device_id, class); DEF_FIELD(symval, sdio_device_id, vendor); DEF_FIELD(symval, sdio_device_id, device); strcpy(alias, "sdio:"); ADD(alias, "c", class != (__u8)SDIO_ANY_ID, class); ADD(alias, "v", vendor != (__u16)SDIO_ANY_ID, vendor); ADD(alias, "d", device != (__u16)SDIO_ANY_ID, device); add_wildcard(alias); return 1; } /* Looks like: ssb:vNidNrevN. */ static int do_ssb_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ssb_device_id, vendor); DEF_FIELD(symval, ssb_device_id, coreid); DEF_FIELD(symval, ssb_device_id, revision); strcpy(alias, "ssb:"); ADD(alias, "v", vendor != SSB_ANY_VENDOR, vendor); ADD(alias, "id", coreid != SSB_ANY_ID, coreid); ADD(alias, "rev", revision != SSB_ANY_REV, revision); add_wildcard(alias); return 1; } /* Looks like: bcma:mNidNrevNclN. */ static int do_bcma_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, bcma_device_id, manuf); DEF_FIELD(symval, bcma_device_id, id); DEF_FIELD(symval, bcma_device_id, rev); DEF_FIELD(symval, bcma_device_id, class); strcpy(alias, "bcma:"); ADD(alias, "m", manuf != BCMA_ANY_MANUF, manuf); ADD(alias, "id", id != BCMA_ANY_ID, id); ADD(alias, "rev", rev != BCMA_ANY_REV, rev); ADD(alias, "cl", class != BCMA_ANY_CLASS, class); add_wildcard(alias); return 1; } /* Looks like: virtio:dNvN */ static int do_virtio_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, virtio_device_id, device); DEF_FIELD(symval, virtio_device_id, vendor); strcpy(alias, "virtio:"); ADD(alias, "d", device != VIRTIO_DEV_ANY_ID, device); ADD(alias, "v", vendor != VIRTIO_DEV_ANY_ID, vendor); add_wildcard(alias); return 1; } /* * Looks like: vmbus:guid * Each byte of the guid will be represented by two hex characters * in the name. */ static int do_vmbus_entry(const char *filename, void *symval, char *alias) { int i; DEF_FIELD_ADDR(symval, hv_vmbus_device_id, guid); char guid_name[(sizeof(*guid) + 1) * 2]; for (i = 0; i < (sizeof(*guid) * 2); i += 2) sprintf(&guid_name[i], "%02x", TO_NATIVE((guid->b)[i/2])); strcpy(alias, "vmbus:"); strcat(alias, guid_name); return 1; } /* Looks like: rpmsg:S */ static int do_rpmsg_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, rpmsg_device_id, name); sprintf(alias, RPMSG_DEVICE_MODALIAS_FMT, *name); return 1; } /* Looks like: i2c:S */ static int do_i2c_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, i2c_device_id, name); sprintf(alias, I2C_MODULE_PREFIX "%s", *name); return 1; } static int do_i3c_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, i3c_device_id, match_flags); DEF_FIELD(symval, i3c_device_id, dcr); DEF_FIELD(symval, i3c_device_id, manuf_id); DEF_FIELD(symval, i3c_device_id, part_id); DEF_FIELD(symval, i3c_device_id, extra_info); strcpy(alias, "i3c:"); ADD(alias, "dcr", match_flags & I3C_MATCH_DCR, dcr); ADD(alias, "manuf", match_flags & I3C_MATCH_MANUF, manuf_id); ADD(alias, "part", match_flags & I3C_MATCH_PART, part_id); ADD(alias, "ext", match_flags & I3C_MATCH_EXTRA_INFO, extra_info); return 1; } /* Looks like: spi:S */ static int do_spi_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, spi_device_id, name); sprintf(alias, SPI_MODULE_PREFIX "%s", *name); return 1; } static const struct dmifield { const char *prefix; int field; } dmi_fields[] = { { "bvn", DMI_BIOS_VENDOR }, { "bvr", DMI_BIOS_VERSION }, { "bd", DMI_BIOS_DATE }, { "br", DMI_BIOS_RELEASE }, { "efr", DMI_EC_FIRMWARE_RELEASE }, { "svn", DMI_SYS_VENDOR }, { "pn", DMI_PRODUCT_NAME }, { "pvr", DMI_PRODUCT_VERSION }, { "rvn", DMI_BOARD_VENDOR }, { "rn", DMI_BOARD_NAME }, { "rvr", DMI_BOARD_VERSION }, { "cvn", DMI_CHASSIS_VENDOR }, { "ct", DMI_CHASSIS_TYPE }, { "cvr", DMI_CHASSIS_VERSION }, { NULL, DMI_NONE } }; static void dmi_ascii_filter(char *d, const char *s) { /* Filter out characters we don't want to see in the modalias string */ for (; *s; s++) if (*s > ' ' && *s < 127 && *s != ':') *(d++) = *s; *d = 0; } static int do_dmi_entry(const char *filename, void *symval, char *alias) { int i, j; DEF_FIELD_ADDR(symval, dmi_system_id, matches); sprintf(alias, "dmi*"); for (i = 0; i < ARRAY_SIZE(dmi_fields); i++) { for (j = 0; j < 4; j++) { if ((*matches)[j].slot && (*matches)[j].slot == dmi_fields[i].field) { sprintf(alias + strlen(alias), ":%s*", dmi_fields[i].prefix); dmi_ascii_filter(alias + strlen(alias), (*matches)[j].substr); strcat(alias, "*"); } } } strcat(alias, ":"); return 1; } static int do_platform_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, platform_device_id, name); sprintf(alias, PLATFORM_MODULE_PREFIX "%s", *name); return 1; } static int do_mdio_entry(const char *filename, void *symval, char *alias) { int i; DEF_FIELD(symval, mdio_device_id, phy_id); DEF_FIELD(symval, mdio_device_id, phy_id_mask); alias += sprintf(alias, MDIO_MODULE_PREFIX); for (i = 0; i < 32; i++) { if (!((phy_id_mask >> (31-i)) & 1)) *(alias++) = '?'; else if ((phy_id >> (31-i)) & 1) *(alias++) = '1'; else *(alias++) = '0'; } /* Terminate the string */ *alias = 0; return 1; } /* Looks like: zorro:iN. */ static int do_zorro_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, zorro_device_id, id); strcpy(alias, "zorro:"); ADD(alias, "i", id != ZORRO_WILDCARD, id); return 1; } /* looks like: "pnp:dD" */ static int do_isapnp_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, isapnp_device_id, vendor); DEF_FIELD(symval, isapnp_device_id, function); sprintf(alias, "pnp:d%c%c%c%x%x%x%x*", 'A' + ((vendor >> 2) & 0x3f) - 1, 'A' + (((vendor & 3) << 3) | ((vendor >> 13) & 7)) - 1, 'A' + ((vendor >> 8) & 0x1f) - 1, (function >> 4) & 0x0f, function & 0x0f, (function >> 12) & 0x0f, (function >> 8) & 0x0f); return 1; } /* Looks like: "ipack:fNvNdN". */ static int do_ipack_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ipack_device_id, format); DEF_FIELD(symval, ipack_device_id, vendor); DEF_FIELD(symval, ipack_device_id, device); strcpy(alias, "ipack:"); ADD(alias, "f", format != IPACK_ANY_FORMAT, format); ADD(alias, "v", vendor != IPACK_ANY_ID, vendor); ADD(alias, "d", device != IPACK_ANY_ID, device); add_wildcard(alias); return 1; } /* * Append a match expression for a single masked hex digit. * outp points to a pointer to the character at which to append. * *outp is updated on return to point just after the appended text, * to facilitate further appending. */ static void append_nibble_mask(char **outp, unsigned int nibble, unsigned int mask) { char *p = *outp; unsigned int i; switch (mask) { case 0: *p++ = '?'; break; case 0xf: p += sprintf(p, "%X", nibble); break; default: /* * Dumbly emit a match pattern for all possible matching * digits. This could be improved in some cases using ranges, * but it has the advantage of being trivially correct, and is * often optimal. */ *p++ = '['; for (i = 0; i < 0x10; i++) if ((i & mask) == nibble) p += sprintf(p, "%X", i); *p++ = ']'; } /* Ensure that the string remains NUL-terminated: */ *p = '\0'; /* Advance the caller's end-of-string pointer: */ *outp = p; } /* * looks like: "amba:dN" * * N is exactly 8 digits, where each is an upper-case hex digit, or * a ? or [] pattern matching exactly one digit. */ static int do_amba_entry(const char *filename, void *symval, char *alias) { unsigned int digit; char *p = alias; DEF_FIELD(symval, amba_id, id); DEF_FIELD(symval, amba_id, mask); if ((id & mask) != id) fatal("%s: Masked-off bit(s) of AMBA device ID are non-zero: id=0x%08X, mask=0x%08X. Please fix this driver.\n", filename, id, mask); p += sprintf(alias, "amba:d"); for (digit = 0; digit < 8; digit++) append_nibble_mask(&p, (id >> (4 * (7 - digit))) & 0xf, (mask >> (4 * (7 - digit))) & 0xf); return 1; } /* * looks like: "mipscdmm:tN" * * N is exactly 2 digits, where each is an upper-case hex digit, or * a ? or [] pattern matching exactly one digit. */ static int do_mips_cdmm_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, mips_cdmm_device_id, type); sprintf(alias, "mipscdmm:t%02X*", type); return 1; } /* LOOKS like cpu:type:x86,venVVVVfamFFFFmodMMMM:feature:*,FEAT,* * All fields are numbers. It would be nicer to use strings for vendor * and feature, but getting those out of the build system here is too * complicated. */ static int do_x86cpu_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, x86_cpu_id, feature); DEF_FIELD(symval, x86_cpu_id, family); DEF_FIELD(symval, x86_cpu_id, model); DEF_FIELD(symval, x86_cpu_id, vendor); strcpy(alias, "cpu:type:x86,"); ADD(alias, "ven", vendor != X86_VENDOR_ANY, vendor); ADD(alias, "fam", family != X86_FAMILY_ANY, family); ADD(alias, "mod", model != X86_MODEL_ANY, model); strcat(alias, ":feature:*"); if (feature != X86_FEATURE_ANY) sprintf(alias + strlen(alias), "%04X*", feature); return 1; } /* LOOKS like cpu:type:*:feature:*FEAT* */ static int do_cpu_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, cpu_feature, feature); sprintf(alias, "cpu:type:*:feature:*%04X*", feature); return 1; } /* Looks like: mei:S:uuid:N:* */ static int do_mei_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, mei_cl_device_id, name); DEF_FIELD_ADDR(symval, mei_cl_device_id, uuid); DEF_FIELD(symval, mei_cl_device_id, version); sprintf(alias, MEI_CL_MODULE_PREFIX); sprintf(alias + strlen(alias), "%s:", (*name)[0] ? *name : "*"); add_uuid(alias, *uuid); ADD(alias, ":", version != MEI_CL_VERSION_ANY, version); strcat(alias, ":*"); return 1; } /* Looks like: rapidio:vNdNavNadN */ static int do_rio_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, rio_device_id, did); DEF_FIELD(symval, rio_device_id, vid); DEF_FIELD(symval, rio_device_id, asm_did); DEF_FIELD(symval, rio_device_id, asm_vid); strcpy(alias, "rapidio:"); ADD(alias, "v", vid != RIO_ANY_ID, vid); ADD(alias, "d", did != RIO_ANY_ID, did); ADD(alias, "av", asm_vid != RIO_ANY_ID, asm_vid); ADD(alias, "ad", asm_did != RIO_ANY_ID, asm_did); add_wildcard(alias); return 1; } /* Looks like: ulpi:vNpN */ static int do_ulpi_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ulpi_device_id, vendor); DEF_FIELD(symval, ulpi_device_id, product); sprintf(alias, "ulpi:v%04xp%04x", vendor, product); return 1; } /* Looks like: hdaudio:vNrNaN */ static int do_hda_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, hda_device_id, vendor_id); DEF_FIELD(symval, hda_device_id, rev_id); DEF_FIELD(symval, hda_device_id, api_version); strcpy(alias, "hdaudio:"); ADD(alias, "v", vendor_id != 0, vendor_id); ADD(alias, "r", rev_id != 0, rev_id); ADD(alias, "a", api_version != 0, api_version); add_wildcard(alias); return 1; } /* Looks like: sdw:mNpNvNcN */ static int do_sdw_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, sdw_device_id, mfg_id); DEF_FIELD(symval, sdw_device_id, part_id); DEF_FIELD(symval, sdw_device_id, sdw_version); DEF_FIELD(symval, sdw_device_id, class_id); strcpy(alias, "sdw:"); ADD(alias, "m", mfg_id != 0, mfg_id); ADD(alias, "p", part_id != 0, part_id); ADD(alias, "v", sdw_version != 0, sdw_version); ADD(alias, "c", class_id != 0, class_id); add_wildcard(alias); return 1; } /* Looks like: fsl-mc:vNdN */ static int do_fsl_mc_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, fsl_mc_device_id, vendor); DEF_FIELD_ADDR(symval, fsl_mc_device_id, obj_type); sprintf(alias, "fsl-mc:v%08Xd%s", vendor, *obj_type); return 1; } /* Looks like: tbsvc:kSpNvNrN */ static int do_tbsvc_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, tb_service_id, match_flags); DEF_FIELD_ADDR(symval, tb_service_id, protocol_key); DEF_FIELD(symval, tb_service_id, protocol_id); DEF_FIELD(symval, tb_service_id, protocol_version); DEF_FIELD(symval, tb_service_id, protocol_revision); strcpy(alias, "tbsvc:"); if (match_flags & TBSVC_MATCH_PROTOCOL_KEY) sprintf(alias + strlen(alias), "k%s", *protocol_key); else strcat(alias + strlen(alias), "k*"); ADD(alias, "p", match_flags & TBSVC_MATCH_PROTOCOL_ID, protocol_id); ADD(alias, "v", match_flags & TBSVC_MATCH_PROTOCOL_VERSION, protocol_version); ADD(alias, "r", match_flags & TBSVC_MATCH_PROTOCOL_REVISION, protocol_revision); add_wildcard(alias); return 1; } /* Looks like: typec:idNmN */ static int do_typec_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, typec_device_id, svid); DEF_FIELD(symval, typec_device_id, mode); sprintf(alias, "typec:id%04X", svid); ADD(alias, "m", mode != TYPEC_ANY_MODE, mode); return 1; } /* Looks like: tee:uuid */ static int do_tee_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, tee_client_device_id, uuid); sprintf(alias, "tee:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid.b[0], uuid.b[1], uuid.b[2], uuid.b[3], uuid.b[4], uuid.b[5], uuid.b[6], uuid.b[7], uuid.b[8], uuid.b[9], uuid.b[10], uuid.b[11], uuid.b[12], uuid.b[13], uuid.b[14], uuid.b[15]); add_wildcard(alias); return 1; } /* Looks like: wmi:guid */ static int do_wmi_entry(const char *filename, void *symval, char *alias) { int len; DEF_FIELD_ADDR(symval, wmi_device_id, guid_string); if (strlen(*guid_string) != UUID_STRING_LEN) { warn("Invalid WMI device id 'wmi:%s' in '%s'\n", *guid_string, filename); return 0; } len = snprintf(alias, ALIAS_SIZE, WMI_MODULE_PREFIX "%s", *guid_string); if (len < 0 || len >= ALIAS_SIZE) { warn("Could not generate all MODULE_ALIAS's in '%s'\n", filename); return 0; } return 1; } /* Looks like: mhi:S */ static int do_mhi_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, mhi_device_id, chan); sprintf(alias, MHI_DEVICE_MODALIAS_FMT, *chan); return 1; } /* Looks like: mhi_ep:S */ static int do_mhi_ep_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, mhi_device_id, chan); sprintf(alias, MHI_EP_DEVICE_MODALIAS_FMT, *chan); return 1; } /* Looks like: ishtp:{guid} */ static int do_ishtp_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ishtp_device_id, guid); strcpy(alias, ISHTP_MODULE_PREFIX "{"); add_guid(alias, guid); strcat(alias, "}"); return 1; } static int do_auxiliary_entry(const char *filename, void *symval, char *alias) { DEF_FIELD_ADDR(symval, auxiliary_device_id, name); sprintf(alias, AUXILIARY_MODULE_PREFIX "%s", *name); return 1; } /* * Looks like: ssam:dNcNtNiNfN * * N is exactly 2 digits, where each is an upper-case hex digit. */ static int do_ssam_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, ssam_device_id, match_flags); DEF_FIELD(symval, ssam_device_id, domain); DEF_FIELD(symval, ssam_device_id, category); DEF_FIELD(symval, ssam_device_id, target); DEF_FIELD(symval, ssam_device_id, instance); DEF_FIELD(symval, ssam_device_id, function); sprintf(alias, "ssam:d%02Xc%02X", domain, category); ADD(alias, "t", match_flags & SSAM_MATCH_TARGET, target); ADD(alias, "i", match_flags & SSAM_MATCH_INSTANCE, instance); ADD(alias, "f", match_flags & SSAM_MATCH_FUNCTION, function); return 1; } /* Looks like: dfl:tNfN */ static int do_dfl_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, dfl_device_id, type); DEF_FIELD(symval, dfl_device_id, feature_id); sprintf(alias, "dfl:t%04Xf%04X", type, feature_id); add_wildcard(alias); return 1; } /* Looks like: cdx:vNdN */ static int do_cdx_entry(const char *filename, void *symval, char *alias) { DEF_FIELD(symval, cdx_device_id, vendor); DEF_FIELD(symval, cdx_device_id, device); DEF_FIELD(symval, cdx_device_id, override_only); switch (override_only) { case 0: strcpy(alias, "cdx:"); break; case CDX_ID_F_VFIO_DRIVER_OVERRIDE: strcpy(alias, "vfio_cdx:"); break; default: warn("Unknown CDX driver_override alias %08X\n", override_only); return 0; } ADD(alias, "v", vendor != CDX_ANY_ID, vendor); ADD(alias, "d", device != CDX_ANY_ID, device); return 1; } /* Does namelen bytes of name exactly match the symbol? */ static bool sym_is(const char *name, unsigned namelen, const char *symbol) { if (namelen != strlen(symbol)) return false; return memcmp(name, symbol, namelen) == 0; } static void do_table(void *symval, unsigned long size, unsigned long id_size, const char *device_id, int (*do_entry)(const char *filename, void *symval, char *alias), struct module *mod) { unsigned int i; char alias[ALIAS_SIZE]; device_id_check(mod->name, device_id, size, id_size, symval); /* Leave last one: it's the terminator. */ size -= id_size; for (i = 0; i < size; i += id_size) { if (do_entry(mod->name, symval+i, alias)) { buf_printf(&mod->dev_table_buf, "MODULE_ALIAS(\"%s\");\n", alias); } } } static const struct devtable devtable[] = { {"hid", SIZE_hid_device_id, do_hid_entry}, {"ieee1394", SIZE_ieee1394_device_id, do_ieee1394_entry}, {"pci", SIZE_pci_device_id, do_pci_entry}, {"ccw", SIZE_ccw_device_id, do_ccw_entry}, {"ap", SIZE_ap_device_id, do_ap_entry}, {"css", SIZE_css_device_id, do_css_entry}, {"serio", SIZE_serio_device_id, do_serio_entry}, {"acpi", SIZE_acpi_device_id, do_acpi_entry}, {"pcmcia", SIZE_pcmcia_device_id, do_pcmcia_entry}, {"vio", SIZE_vio_device_id, do_vio_entry}, {"input", SIZE_input_device_id, do_input_entry}, {"eisa", SIZE_eisa_device_id, do_eisa_entry}, {"parisc", SIZE_parisc_device_id, do_parisc_entry}, {"sdio", SIZE_sdio_device_id, do_sdio_entry}, {"ssb", SIZE_ssb_device_id, do_ssb_entry}, {"bcma", SIZE_bcma_device_id, do_bcma_entry}, {"virtio", SIZE_virtio_device_id, do_virtio_entry}, {"vmbus", SIZE_hv_vmbus_device_id, do_vmbus_entry}, {"rpmsg", SIZE_rpmsg_device_id, do_rpmsg_entry}, {"i2c", SIZE_i2c_device_id, do_i2c_entry}, {"i3c", SIZE_i3c_device_id, do_i3c_entry}, {"spi", SIZE_spi_device_id, do_spi_entry}, {"dmi", SIZE_dmi_system_id, do_dmi_entry}, {"platform", SIZE_platform_device_id, do_platform_entry}, {"mdio", SIZE_mdio_device_id, do_mdio_entry}, {"zorro", SIZE_zorro_device_id, do_zorro_entry}, {"isapnp", SIZE_isapnp_device_id, do_isapnp_entry}, {"ipack", SIZE_ipack_device_id, do_ipack_entry}, {"amba", SIZE_amba_id, do_amba_entry}, {"mipscdmm", SIZE_mips_cdmm_device_id, do_mips_cdmm_entry}, {"x86cpu", SIZE_x86_cpu_id, do_x86cpu_entry}, {"cpu", SIZE_cpu_feature, do_cpu_entry}, {"mei", SIZE_mei_cl_device_id, do_mei_entry}, {"rapidio", SIZE_rio_device_id, do_rio_entry}, {"ulpi", SIZE_ulpi_device_id, do_ulpi_entry}, {"hdaudio", SIZE_hda_device_id, do_hda_entry}, {"sdw", SIZE_sdw_device_id, do_sdw_entry}, {"fslmc", SIZE_fsl_mc_device_id, do_fsl_mc_entry}, {"tbsvc", SIZE_tb_service_id, do_tbsvc_entry}, {"typec", SIZE_typec_device_id, do_typec_entry}, {"tee", SIZE_tee_client_device_id, do_tee_entry}, {"wmi", SIZE_wmi_device_id, do_wmi_entry}, {"mhi", SIZE_mhi_device_id, do_mhi_entry}, {"mhi_ep", SIZE_mhi_device_id, do_mhi_ep_entry}, {"auxiliary", SIZE_auxiliary_device_id, do_auxiliary_entry}, {"ssam", SIZE_ssam_device_id, do_ssam_entry}, {"dfl", SIZE_dfl_device_id, do_dfl_entry}, {"ishtp", SIZE_ishtp_device_id, do_ishtp_entry}, {"cdx", SIZE_cdx_device_id, do_cdx_entry}, }; /* Create MODULE_ALIAS() statements. * At this time, we cannot write the actual output C source yet, * so we write into the mod->dev_table_buf buffer. */ void handle_moddevtable(struct module *mod, struct elf_info *info, Elf_Sym *sym, const char *symname) { void *symval; char *zeros = NULL; const char *name, *identifier; unsigned int namelen; /* We're looking for a section relative symbol */ if (!sym->st_shndx || get_secindex(info, sym) >= info->num_sections) return; /* We're looking for an object */ if (ELF_ST_TYPE(sym->st_info) != STT_OBJECT) return; /* All our symbols are of form __mod_<name>__<identifier>_device_table. */ if (strncmp(symname, "__mod_", strlen("__mod_"))) return; name = symname + strlen("__mod_"); namelen = strlen(name); if (namelen < strlen("_device_table")) return; if (strcmp(name + namelen - strlen("_device_table"), "_device_table")) return; identifier = strstr(name, "__"); if (!identifier) return; namelen = identifier - name; /* Handle all-NULL symbols allocated into .bss */ if (info->sechdrs[get_secindex(info, sym)].sh_type & SHT_NOBITS) { zeros = calloc(1, sym->st_size); symval = zeros; } else { symval = sym_get_data(info, sym); } /* First handle the "special" cases */ if (sym_is(name, namelen, "usb")) do_usb_table(symval, sym->st_size, mod); if (sym_is(name, namelen, "of")) do_of_table(symval, sym->st_size, mod); else if (sym_is(name, namelen, "pnp")) do_pnp_device_entry(symval, sym->st_size, mod); else if (sym_is(name, namelen, "pnp_card")) do_pnp_card_entries(symval, sym->st_size, mod); else { int i; for (i = 0; i < ARRAY_SIZE(devtable); i++) { const struct devtable *p = &devtable[i]; if (sym_is(name, namelen, p->device_id)) { do_table(symval, sym->st_size, p->id_size, p->device_id, p->do_entry, mod); break; } } } free(zeros); } /* Now add out buffered information to the generated C source */ void add_moddevtable(struct buffer *buf, struct module *mod) { buf_printf(buf, "\n"); buf_write(buf, mod->dev_table_buf.p, mod->dev_table_buf.pos); free(mod->dev_table_buf.p); }
linux-master
scripts/mod/file2alias.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/kbuild.h> #include <linux/mod_devicetable.h> #define DEVID(devid) DEFINE(SIZE_##devid, sizeof(struct devid)) #define DEVID_FIELD(devid, field) \ DEFINE(OFF_##devid##_##field, offsetof(struct devid, field)) int main(void) { DEVID(usb_device_id); DEVID_FIELD(usb_device_id, match_flags); DEVID_FIELD(usb_device_id, idVendor); DEVID_FIELD(usb_device_id, idProduct); DEVID_FIELD(usb_device_id, bcdDevice_lo); DEVID_FIELD(usb_device_id, bcdDevice_hi); DEVID_FIELD(usb_device_id, bDeviceClass); DEVID_FIELD(usb_device_id, bDeviceSubClass); DEVID_FIELD(usb_device_id, bDeviceProtocol); DEVID_FIELD(usb_device_id, bInterfaceClass); DEVID_FIELD(usb_device_id, bInterfaceSubClass); DEVID_FIELD(usb_device_id, bInterfaceProtocol); DEVID_FIELD(usb_device_id, bInterfaceNumber); DEVID(hid_device_id); DEVID_FIELD(hid_device_id, bus); DEVID_FIELD(hid_device_id, group); DEVID_FIELD(hid_device_id, vendor); DEVID_FIELD(hid_device_id, product); DEVID(ieee1394_device_id); DEVID_FIELD(ieee1394_device_id, match_flags); DEVID_FIELD(ieee1394_device_id, vendor_id); DEVID_FIELD(ieee1394_device_id, model_id); DEVID_FIELD(ieee1394_device_id, specifier_id); DEVID_FIELD(ieee1394_device_id, version); DEVID(pci_device_id); DEVID_FIELD(pci_device_id, vendor); DEVID_FIELD(pci_device_id, device); DEVID_FIELD(pci_device_id, subvendor); DEVID_FIELD(pci_device_id, subdevice); DEVID_FIELD(pci_device_id, class); DEVID_FIELD(pci_device_id, class_mask); DEVID_FIELD(pci_device_id, override_only); DEVID(ccw_device_id); DEVID_FIELD(ccw_device_id, match_flags); DEVID_FIELD(ccw_device_id, cu_type); DEVID_FIELD(ccw_device_id, cu_model); DEVID_FIELD(ccw_device_id, dev_type); DEVID_FIELD(ccw_device_id, dev_model); DEVID(ap_device_id); DEVID_FIELD(ap_device_id, dev_type); DEVID(css_device_id); DEVID_FIELD(css_device_id, type); DEVID(serio_device_id); DEVID_FIELD(serio_device_id, type); DEVID_FIELD(serio_device_id, proto); DEVID_FIELD(serio_device_id, id); DEVID_FIELD(serio_device_id, extra); DEVID(acpi_device_id); DEVID_FIELD(acpi_device_id, id); DEVID_FIELD(acpi_device_id, cls); DEVID_FIELD(acpi_device_id, cls_msk); DEVID(pnp_device_id); DEVID_FIELD(pnp_device_id, id); DEVID(pnp_card_device_id); DEVID_FIELD(pnp_card_device_id, devs); DEVID(pcmcia_device_id); DEVID_FIELD(pcmcia_device_id, match_flags); DEVID_FIELD(pcmcia_device_id, manf_id); DEVID_FIELD(pcmcia_device_id, card_id); DEVID_FIELD(pcmcia_device_id, func_id); DEVID_FIELD(pcmcia_device_id, function); DEVID_FIELD(pcmcia_device_id, device_no); DEVID_FIELD(pcmcia_device_id, prod_id_hash); DEVID(of_device_id); DEVID_FIELD(of_device_id, name); DEVID_FIELD(of_device_id, type); DEVID_FIELD(of_device_id, compatible); DEVID(vio_device_id); DEVID_FIELD(vio_device_id, type); DEVID_FIELD(vio_device_id, compat); DEVID(input_device_id); DEVID_FIELD(input_device_id, flags); DEVID_FIELD(input_device_id, bustype); DEVID_FIELD(input_device_id, vendor); DEVID_FIELD(input_device_id, product); DEVID_FIELD(input_device_id, version); DEVID_FIELD(input_device_id, evbit); DEVID_FIELD(input_device_id, keybit); DEVID_FIELD(input_device_id, relbit); DEVID_FIELD(input_device_id, absbit); DEVID_FIELD(input_device_id, mscbit); DEVID_FIELD(input_device_id, ledbit); DEVID_FIELD(input_device_id, sndbit); DEVID_FIELD(input_device_id, ffbit); DEVID_FIELD(input_device_id, swbit); DEVID(eisa_device_id); DEVID_FIELD(eisa_device_id, sig); DEVID(parisc_device_id); DEVID_FIELD(parisc_device_id, hw_type); DEVID_FIELD(parisc_device_id, hversion); DEVID_FIELD(parisc_device_id, hversion_rev); DEVID_FIELD(parisc_device_id, sversion); DEVID(sdio_device_id); DEVID_FIELD(sdio_device_id, class); DEVID_FIELD(sdio_device_id, vendor); DEVID_FIELD(sdio_device_id, device); DEVID(ssb_device_id); DEVID_FIELD(ssb_device_id, vendor); DEVID_FIELD(ssb_device_id, coreid); DEVID_FIELD(ssb_device_id, revision); DEVID(bcma_device_id); DEVID_FIELD(bcma_device_id, manuf); DEVID_FIELD(bcma_device_id, id); DEVID_FIELD(bcma_device_id, rev); DEVID_FIELD(bcma_device_id, class); DEVID(virtio_device_id); DEVID_FIELD(virtio_device_id, device); DEVID_FIELD(virtio_device_id, vendor); DEVID(hv_vmbus_device_id); DEVID_FIELD(hv_vmbus_device_id, guid); DEVID(rpmsg_device_id); DEVID_FIELD(rpmsg_device_id, name); DEVID(i2c_device_id); DEVID_FIELD(i2c_device_id, name); DEVID(i3c_device_id); DEVID_FIELD(i3c_device_id, match_flags); DEVID_FIELD(i3c_device_id, dcr); DEVID_FIELD(i3c_device_id, manuf_id); DEVID_FIELD(i3c_device_id, part_id); DEVID_FIELD(i3c_device_id, extra_info); DEVID(spi_device_id); DEVID_FIELD(spi_device_id, name); DEVID(dmi_system_id); DEVID_FIELD(dmi_system_id, matches); DEVID(platform_device_id); DEVID_FIELD(platform_device_id, name); DEVID(mdio_device_id); DEVID_FIELD(mdio_device_id, phy_id); DEVID_FIELD(mdio_device_id, phy_id_mask); DEVID(zorro_device_id); DEVID_FIELD(zorro_device_id, id); DEVID(isapnp_device_id); DEVID_FIELD(isapnp_device_id, vendor); DEVID_FIELD(isapnp_device_id, function); DEVID(ipack_device_id); DEVID_FIELD(ipack_device_id, format); DEVID_FIELD(ipack_device_id, vendor); DEVID_FIELD(ipack_device_id, device); DEVID(amba_id); DEVID_FIELD(amba_id, id); DEVID_FIELD(amba_id, mask); DEVID(mips_cdmm_device_id); DEVID_FIELD(mips_cdmm_device_id, type); DEVID(x86_cpu_id); DEVID_FIELD(x86_cpu_id, feature); DEVID_FIELD(x86_cpu_id, family); DEVID_FIELD(x86_cpu_id, model); DEVID_FIELD(x86_cpu_id, vendor); DEVID(cpu_feature); DEVID_FIELD(cpu_feature, feature); DEVID(mei_cl_device_id); DEVID_FIELD(mei_cl_device_id, name); DEVID_FIELD(mei_cl_device_id, uuid); DEVID_FIELD(mei_cl_device_id, version); DEVID(rio_device_id); DEVID_FIELD(rio_device_id, did); DEVID_FIELD(rio_device_id, vid); DEVID_FIELD(rio_device_id, asm_did); DEVID_FIELD(rio_device_id, asm_vid); DEVID(ulpi_device_id); DEVID_FIELD(ulpi_device_id, vendor); DEVID_FIELD(ulpi_device_id, product); DEVID(hda_device_id); DEVID_FIELD(hda_device_id, vendor_id); DEVID_FIELD(hda_device_id, rev_id); DEVID_FIELD(hda_device_id, api_version); DEVID(sdw_device_id); DEVID_FIELD(sdw_device_id, mfg_id); DEVID_FIELD(sdw_device_id, part_id); DEVID_FIELD(sdw_device_id, sdw_version); DEVID_FIELD(sdw_device_id, class_id); DEVID(fsl_mc_device_id); DEVID_FIELD(fsl_mc_device_id, vendor); DEVID_FIELD(fsl_mc_device_id, obj_type); DEVID(tb_service_id); DEVID_FIELD(tb_service_id, match_flags); DEVID_FIELD(tb_service_id, protocol_key); DEVID_FIELD(tb_service_id, protocol_id); DEVID_FIELD(tb_service_id, protocol_version); DEVID_FIELD(tb_service_id, protocol_revision); DEVID(typec_device_id); DEVID_FIELD(typec_device_id, svid); DEVID_FIELD(typec_device_id, mode); DEVID(tee_client_device_id); DEVID_FIELD(tee_client_device_id, uuid); DEVID(wmi_device_id); DEVID_FIELD(wmi_device_id, guid_string); DEVID(mhi_device_id); DEVID_FIELD(mhi_device_id, chan); DEVID(auxiliary_device_id); DEVID_FIELD(auxiliary_device_id, name); DEVID(ssam_device_id); DEVID_FIELD(ssam_device_id, match_flags); DEVID_FIELD(ssam_device_id, domain); DEVID_FIELD(ssam_device_id, category); DEVID_FIELD(ssam_device_id, target); DEVID_FIELD(ssam_device_id, instance); DEVID_FIELD(ssam_device_id, function); DEVID(dfl_device_id); DEVID_FIELD(dfl_device_id, type); DEVID_FIELD(dfl_device_id, feature_id); DEVID(ishtp_device_id); DEVID_FIELD(ishtp_device_id, guid); DEVID(cdx_device_id); DEVID_FIELD(cdx_device_id, vendor); DEVID_FIELD(cdx_device_id, device); DEVID_FIELD(cdx_device_id, override_only); return 0; }
linux-master
scripts/mod/devicetable-offsets.c
/* Postprocess module symbol versions * * Copyright 2003 Kai Germaschewski * Copyright 2002-2004 Rusty Russell, IBM Corporation * Copyright 2006-2008 Sam Ravnborg * Based in part on module-init-tools/depmod.c,file2alias * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Usage: modpost vmlinux module1.o module2.o ... */ #define _GNU_SOURCE #include <elf.h> #include <fnmatch.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <limits.h> #include <stdbool.h> #include <errno.h> #include "modpost.h" #include "../../include/linux/license.h" #include "../../include/linux/module_symbol.h" static bool module_enabled; /* Are we using CONFIG_MODVERSIONS? */ static bool modversions; /* Is CONFIG_MODULE_SRCVERSION_ALL set? */ static bool all_versions; /* If we are modposting external module set to 1 */ static bool external_module; /* Only warn about unresolved symbols */ static bool warn_unresolved; static int sec_mismatch_count; static bool sec_mismatch_warn_only = true; /* Trim EXPORT_SYMBOLs that are unused by in-tree modules */ static bool trim_unused_exports; /* ignore missing files */ static bool ignore_missing_files; /* If set to 1, only warn (instead of error) about missing ns imports */ static bool allow_missing_ns_imports; static bool error_occurred; static bool extra_warn; /* * Cut off the warnings when there are too many. This typically occurs when * vmlinux is missing. ('make modules' without building vmlinux.) */ #define MAX_UNRESOLVED_REPORTS 10 static unsigned int nr_unresolved; /* In kernel, this size is defined in linux/module.h; * here we use Elf_Addr instead of long for covering cross-compile */ #define MODULE_NAME_LEN (64 - sizeof(Elf_Addr)) void __attribute__((format(printf, 2, 3))) modpost_log(enum loglevel loglevel, const char *fmt, ...) { va_list arglist; switch (loglevel) { case LOG_WARN: fprintf(stderr, "WARNING: "); break; case LOG_ERROR: fprintf(stderr, "ERROR: "); break; case LOG_FATAL: fprintf(stderr, "FATAL: "); break; default: /* invalid loglevel, ignore */ break; } fprintf(stderr, "modpost: "); va_start(arglist, fmt); vfprintf(stderr, fmt, arglist); va_end(arglist); if (loglevel == LOG_FATAL) exit(1); if (loglevel == LOG_ERROR) error_occurred = true; } static inline bool strends(const char *str, const char *postfix) { if (strlen(str) < strlen(postfix)) return false; return strcmp(str + strlen(str) - strlen(postfix), postfix) == 0; } void *do_nofail(void *ptr, const char *expr) { if (!ptr) fatal("Memory allocation failure: %s.\n", expr); return ptr; } char *read_text_file(const char *filename) { struct stat st; size_t nbytes; int fd; char *buf; fd = open(filename, O_RDONLY); if (fd < 0) { perror(filename); exit(1); } if (fstat(fd, &st) < 0) { perror(filename); exit(1); } buf = NOFAIL(malloc(st.st_size + 1)); nbytes = st.st_size; while (nbytes) { ssize_t bytes_read; bytes_read = read(fd, buf, nbytes); if (bytes_read < 0) { perror(filename); exit(1); } nbytes -= bytes_read; } buf[st.st_size] = '\0'; close(fd); return buf; } char *get_line(char **stringp) { char *orig = *stringp, *next; /* do not return the unwanted extra line at EOF */ if (!orig || *orig == '\0') return NULL; /* don't use strsep here, it is not available everywhere */ next = strchr(orig, '\n'); if (next) *next++ = '\0'; *stringp = next; return orig; } /* A list of all modules we processed */ LIST_HEAD(modules); static struct module *find_module(const char *modname) { struct module *mod; list_for_each_entry(mod, &modules, list) { if (strcmp(mod->name, modname) == 0) return mod; } return NULL; } static struct module *new_module(const char *name, size_t namelen) { struct module *mod; mod = NOFAIL(malloc(sizeof(*mod) + namelen + 1)); memset(mod, 0, sizeof(*mod)); INIT_LIST_HEAD(&mod->exported_symbols); INIT_LIST_HEAD(&mod->unresolved_symbols); INIT_LIST_HEAD(&mod->missing_namespaces); INIT_LIST_HEAD(&mod->imported_namespaces); memcpy(mod->name, name, namelen); mod->name[namelen] = '\0'; mod->is_vmlinux = (strcmp(mod->name, "vmlinux") == 0); /* * Set mod->is_gpl_compatible to true by default. If MODULE_LICENSE() * is missing, do not check the use for EXPORT_SYMBOL_GPL() becasue * modpost will exit wiht error anyway. */ mod->is_gpl_compatible = true; list_add_tail(&mod->list, &modules); return mod; } /* A hash of all exported symbols, * struct symbol is also used for lists of unresolved symbols */ #define SYMBOL_HASH_SIZE 1024 struct symbol { struct symbol *next; struct list_head list; /* link to module::exported_symbols or module::unresolved_symbols */ struct module *module; char *namespace; unsigned int crc; bool crc_valid; bool weak; bool is_func; bool is_gpl_only; /* exported by EXPORT_SYMBOL_GPL */ bool used; /* there exists a user of this symbol */ char name[]; }; static struct symbol *symbolhash[SYMBOL_HASH_SIZE]; /* This is based on the hash algorithm from gdbm, via tdb */ static inline unsigned int tdb_hash(const char *name) { unsigned value; /* Used to compute the hash value. */ unsigned i; /* Used to cycle through random values. */ /* Set the initial value from the key size. */ for (value = 0x238F13AF * strlen(name), i = 0; name[i]; i++) value = (value + (((unsigned char *)name)[i] << (i*5 % 24))); return (1103515243 * value + 12345); } /** * Allocate a new symbols for use in the hash of exported symbols or * the list of unresolved symbols per module **/ static struct symbol *alloc_symbol(const char *name) { struct symbol *s = NOFAIL(malloc(sizeof(*s) + strlen(name) + 1)); memset(s, 0, sizeof(*s)); strcpy(s->name, name); return s; } /* For the hash of exported symbols */ static void hash_add_symbol(struct symbol *sym) { unsigned int hash; hash = tdb_hash(sym->name) % SYMBOL_HASH_SIZE; sym->next = symbolhash[hash]; symbolhash[hash] = sym; } static void sym_add_unresolved(const char *name, struct module *mod, bool weak) { struct symbol *sym; sym = alloc_symbol(name); sym->weak = weak; list_add_tail(&sym->list, &mod->unresolved_symbols); } static struct symbol *sym_find_with_module(const char *name, struct module *mod) { struct symbol *s; /* For our purposes, .foo matches foo. PPC64 needs this. */ if (name[0] == '.') name++; for (s = symbolhash[tdb_hash(name) % SYMBOL_HASH_SIZE]; s; s = s->next) { if (strcmp(s->name, name) == 0 && (!mod || s->module == mod)) return s; } return NULL; } static struct symbol *find_symbol(const char *name) { return sym_find_with_module(name, NULL); } struct namespace_list { struct list_head list; char namespace[]; }; static bool contains_namespace(struct list_head *head, const char *namespace) { struct namespace_list *list; /* * The default namespace is null string "", which is always implicitly * contained. */ if (!namespace[0]) return true; list_for_each_entry(list, head, list) { if (!strcmp(list->namespace, namespace)) return true; } return false; } static void add_namespace(struct list_head *head, const char *namespace) { struct namespace_list *ns_entry; if (!contains_namespace(head, namespace)) { ns_entry = NOFAIL(malloc(sizeof(*ns_entry) + strlen(namespace) + 1)); strcpy(ns_entry->namespace, namespace); list_add_tail(&ns_entry->list, head); } } static void *sym_get_data_by_offset(const struct elf_info *info, unsigned int secindex, unsigned long offset) { Elf_Shdr *sechdr = &info->sechdrs[secindex]; return (void *)info->hdr + sechdr->sh_offset + offset; } void *sym_get_data(const struct elf_info *info, const Elf_Sym *sym) { return sym_get_data_by_offset(info, get_secindex(info, sym), sym->st_value); } static const char *sech_name(const struct elf_info *info, Elf_Shdr *sechdr) { return sym_get_data_by_offset(info, info->secindex_strings, sechdr->sh_name); } static const char *sec_name(const struct elf_info *info, unsigned int secindex) { /* * If sym->st_shndx is a special section index, there is no * corresponding section header. * Return "" if the index is out of range of info->sechdrs[] array. */ if (secindex >= info->num_sections) return ""; return sech_name(info, &info->sechdrs[secindex]); } #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0) static struct symbol *sym_add_exported(const char *name, struct module *mod, bool gpl_only, const char *namespace) { struct symbol *s = find_symbol(name); if (s && (!external_module || s->module->is_vmlinux || s->module == mod)) { error("%s: '%s' exported twice. Previous export was in %s%s\n", mod->name, name, s->module->name, s->module->is_vmlinux ? "" : ".ko"); } s = alloc_symbol(name); s->module = mod; s->is_gpl_only = gpl_only; s->namespace = NOFAIL(strdup(namespace)); list_add_tail(&s->list, &mod->exported_symbols); hash_add_symbol(s); return s; } static void sym_set_crc(struct symbol *sym, unsigned int crc) { sym->crc = crc; sym->crc_valid = true; } static void *grab_file(const char *filename, size_t *size) { struct stat st; void *map = MAP_FAILED; int fd; fd = open(filename, O_RDONLY); if (fd < 0) return NULL; if (fstat(fd, &st)) goto failed; *size = st.st_size; map = mmap(NULL, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); failed: close(fd); if (map == MAP_FAILED) return NULL; return map; } static void release_file(void *file, size_t size) { munmap(file, size); } static int parse_elf(struct elf_info *info, const char *filename) { unsigned int i; Elf_Ehdr *hdr; Elf_Shdr *sechdrs; Elf_Sym *sym; const char *secstrings; unsigned int symtab_idx = ~0U, symtab_shndx_idx = ~0U; hdr = grab_file(filename, &info->size); if (!hdr) { if (ignore_missing_files) { fprintf(stderr, "%s: %s (ignored)\n", filename, strerror(errno)); return 0; } perror(filename); exit(1); } info->hdr = hdr; if (info->size < sizeof(*hdr)) { /* file too small, assume this is an empty .o file */ return 0; } /* Is this a valid ELF file? */ if ((hdr->e_ident[EI_MAG0] != ELFMAG0) || (hdr->e_ident[EI_MAG1] != ELFMAG1) || (hdr->e_ident[EI_MAG2] != ELFMAG2) || (hdr->e_ident[EI_MAG3] != ELFMAG3)) { /* Not an ELF file - silently ignore it */ return 0; } /* Fix endianness in ELF header */ hdr->e_type = TO_NATIVE(hdr->e_type); hdr->e_machine = TO_NATIVE(hdr->e_machine); hdr->e_version = TO_NATIVE(hdr->e_version); hdr->e_entry = TO_NATIVE(hdr->e_entry); hdr->e_phoff = TO_NATIVE(hdr->e_phoff); hdr->e_shoff = TO_NATIVE(hdr->e_shoff); hdr->e_flags = TO_NATIVE(hdr->e_flags); hdr->e_ehsize = TO_NATIVE(hdr->e_ehsize); hdr->e_phentsize = TO_NATIVE(hdr->e_phentsize); hdr->e_phnum = TO_NATIVE(hdr->e_phnum); hdr->e_shentsize = TO_NATIVE(hdr->e_shentsize); hdr->e_shnum = TO_NATIVE(hdr->e_shnum); hdr->e_shstrndx = TO_NATIVE(hdr->e_shstrndx); sechdrs = (void *)hdr + hdr->e_shoff; info->sechdrs = sechdrs; /* modpost only works for relocatable objects */ if (hdr->e_type != ET_REL) fatal("%s: not relocatable object.", filename); /* Check if file offset is correct */ if (hdr->e_shoff > info->size) { fatal("section header offset=%lu in file '%s' is bigger than filesize=%zu\n", (unsigned long)hdr->e_shoff, filename, info->size); return 0; } if (hdr->e_shnum == SHN_UNDEF) { /* * There are more than 64k sections, * read count from .sh_size. */ info->num_sections = TO_NATIVE(sechdrs[0].sh_size); } else { info->num_sections = hdr->e_shnum; } if (hdr->e_shstrndx == SHN_XINDEX) { info->secindex_strings = TO_NATIVE(sechdrs[0].sh_link); } else { info->secindex_strings = hdr->e_shstrndx; } /* Fix endianness in section headers */ for (i = 0; i < info->num_sections; i++) { sechdrs[i].sh_name = TO_NATIVE(sechdrs[i].sh_name); sechdrs[i].sh_type = TO_NATIVE(sechdrs[i].sh_type); sechdrs[i].sh_flags = TO_NATIVE(sechdrs[i].sh_flags); sechdrs[i].sh_addr = TO_NATIVE(sechdrs[i].sh_addr); sechdrs[i].sh_offset = TO_NATIVE(sechdrs[i].sh_offset); sechdrs[i].sh_size = TO_NATIVE(sechdrs[i].sh_size); sechdrs[i].sh_link = TO_NATIVE(sechdrs[i].sh_link); sechdrs[i].sh_info = TO_NATIVE(sechdrs[i].sh_info); sechdrs[i].sh_addralign = TO_NATIVE(sechdrs[i].sh_addralign); sechdrs[i].sh_entsize = TO_NATIVE(sechdrs[i].sh_entsize); } /* Find symbol table. */ secstrings = (void *)hdr + sechdrs[info->secindex_strings].sh_offset; for (i = 1; i < info->num_sections; i++) { const char *secname; int nobits = sechdrs[i].sh_type == SHT_NOBITS; if (!nobits && sechdrs[i].sh_offset > info->size) { fatal("%s is truncated. sechdrs[i].sh_offset=%lu > sizeof(*hrd)=%zu\n", filename, (unsigned long)sechdrs[i].sh_offset, sizeof(*hdr)); return 0; } secname = secstrings + sechdrs[i].sh_name; if (strcmp(secname, ".modinfo") == 0) { if (nobits) fatal("%s has NOBITS .modinfo\n", filename); info->modinfo = (void *)hdr + sechdrs[i].sh_offset; info->modinfo_len = sechdrs[i].sh_size; } else if (!strcmp(secname, ".export_symbol")) { info->export_symbol_secndx = i; } if (sechdrs[i].sh_type == SHT_SYMTAB) { unsigned int sh_link_idx; symtab_idx = i; info->symtab_start = (void *)hdr + sechdrs[i].sh_offset; info->symtab_stop = (void *)hdr + sechdrs[i].sh_offset + sechdrs[i].sh_size; sh_link_idx = sechdrs[i].sh_link; info->strtab = (void *)hdr + sechdrs[sh_link_idx].sh_offset; } /* 32bit section no. table? ("more than 64k sections") */ if (sechdrs[i].sh_type == SHT_SYMTAB_SHNDX) { symtab_shndx_idx = i; info->symtab_shndx_start = (void *)hdr + sechdrs[i].sh_offset; info->symtab_shndx_stop = (void *)hdr + sechdrs[i].sh_offset + sechdrs[i].sh_size; } } if (!info->symtab_start) fatal("%s has no symtab?\n", filename); /* Fix endianness in symbols */ for (sym = info->symtab_start; sym < info->symtab_stop; sym++) { sym->st_shndx = TO_NATIVE(sym->st_shndx); sym->st_name = TO_NATIVE(sym->st_name); sym->st_value = TO_NATIVE(sym->st_value); sym->st_size = TO_NATIVE(sym->st_size); } if (symtab_shndx_idx != ~0U) { Elf32_Word *p; if (symtab_idx != sechdrs[symtab_shndx_idx].sh_link) fatal("%s: SYMTAB_SHNDX has bad sh_link: %u!=%u\n", filename, sechdrs[symtab_shndx_idx].sh_link, symtab_idx); /* Fix endianness */ for (p = info->symtab_shndx_start; p < info->symtab_shndx_stop; p++) *p = TO_NATIVE(*p); } return 1; } static void parse_elf_finish(struct elf_info *info) { release_file(info->hdr, info->size); } static int ignore_undef_symbol(struct elf_info *info, const char *symname) { /* ignore __this_module, it will be resolved shortly */ if (strcmp(symname, "__this_module") == 0) return 1; /* ignore global offset table */ if (strcmp(symname, "_GLOBAL_OFFSET_TABLE_") == 0) return 1; if (info->hdr->e_machine == EM_PPC) /* Special register function linked on all modules during final link of .ko */ if (strstarts(symname, "_restgpr_") || strstarts(symname, "_savegpr_") || strstarts(symname, "_rest32gpr_") || strstarts(symname, "_save32gpr_") || strstarts(symname, "_restvr_") || strstarts(symname, "_savevr_")) return 1; if (info->hdr->e_machine == EM_PPC64) /* Special register function linked on all modules during final link of .ko */ if (strstarts(symname, "_restgpr0_") || strstarts(symname, "_savegpr0_") || strstarts(symname, "_restvr_") || strstarts(symname, "_savevr_") || strcmp(symname, ".TOC.") == 0) return 1; if (info->hdr->e_machine == EM_S390) /* Expoline thunks are linked on all kernel modules during final link of .ko */ if (strstarts(symname, "__s390_indirect_jump_r")) return 1; /* Do not ignore this symbol */ return 0; } static void handle_symbol(struct module *mod, struct elf_info *info, const Elf_Sym *sym, const char *symname) { switch (sym->st_shndx) { case SHN_COMMON: if (strstarts(symname, "__gnu_lto_")) { /* Should warn here, but modpost runs before the linker */ } else warn("\"%s\" [%s] is COMMON symbol\n", symname, mod->name); break; case SHN_UNDEF: /* undefined symbol */ if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL && ELF_ST_BIND(sym->st_info) != STB_WEAK) break; if (ignore_undef_symbol(info, symname)) break; if (info->hdr->e_machine == EM_SPARC || info->hdr->e_machine == EM_SPARCV9) { /* Ignore register directives. */ if (ELF_ST_TYPE(sym->st_info) == STT_SPARC_REGISTER) break; if (symname[0] == '.') { char *munged = NOFAIL(strdup(symname)); munged[0] = '_'; munged[1] = toupper(munged[1]); symname = munged; } } sym_add_unresolved(symname, mod, ELF_ST_BIND(sym->st_info) == STB_WEAK); break; default: if (strcmp(symname, "init_module") == 0) mod->has_init = true; if (strcmp(symname, "cleanup_module") == 0) mod->has_cleanup = true; break; } } /** * Parse tag=value strings from .modinfo section **/ static char *next_string(char *string, unsigned long *secsize) { /* Skip non-zero chars */ while (string[0]) { string++; if ((*secsize)-- <= 1) return NULL; } /* Skip any zero padding. */ while (!string[0]) { string++; if ((*secsize)-- <= 1) return NULL; } return string; } static char *get_next_modinfo(struct elf_info *info, const char *tag, char *prev) { char *p; unsigned int taglen = strlen(tag); char *modinfo = info->modinfo; unsigned long size = info->modinfo_len; if (prev) { size -= prev - modinfo; modinfo = next_string(prev, &size); } for (p = modinfo; p; p = next_string(p, &size)) { if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=') return p + taglen + 1; } return NULL; } static char *get_modinfo(struct elf_info *info, const char *tag) { return get_next_modinfo(info, tag, NULL); } static const char *sym_name(struct elf_info *elf, Elf_Sym *sym) { if (sym) return elf->strtab + sym->st_name; else return "(unknown)"; } /* * Check whether the 'string' argument matches one of the 'patterns', * an array of shell wildcard patterns (glob). * * Return true is there is a match. */ static bool match(const char *string, const char *const patterns[]) { const char *pattern; while ((pattern = *patterns++)) { if (!fnmatch(pattern, string, 0)) return true; } return false; } /* useful to pass patterns to match() directly */ #define PATTERNS(...) \ ({ \ static const char *const patterns[] = {__VA_ARGS__, NULL}; \ patterns; \ }) /* sections that we do not want to do full section mismatch check on */ static const char *const section_white_list[] = { ".comment*", ".debug*", ".zdebug*", /* Compressed debug sections. */ ".GCC.command.line", /* record-gcc-switches */ ".mdebug*", /* alpha, score, mips etc. */ ".pdr", /* alpha, score, mips etc. */ ".stab*", ".note*", ".got*", ".toc*", ".xt.prop", /* xtensa */ ".xt.lit", /* xtensa */ ".arcextmap*", /* arc */ ".gnu.linkonce.arcext*", /* arc : modules */ ".cmem*", /* EZchip */ ".fmt_slot*", /* EZchip */ ".gnu.lto*", ".discard.*", ".llvm.call-graph-profile", /* call graph */ NULL }; /* * This is used to find sections missing the SHF_ALLOC flag. * The cause of this is often a section specified in assembler * without "ax" / "aw". */ static void check_section(const char *modname, struct elf_info *elf, Elf_Shdr *sechdr) { const char *sec = sech_name(elf, sechdr); if (sechdr->sh_type == SHT_PROGBITS && !(sechdr->sh_flags & SHF_ALLOC) && !match(sec, section_white_list)) { warn("%s (%s): unexpected non-allocatable section.\n" "Did you forget to use \"ax\"/\"aw\" in a .S file?\n" "Note that for example <linux/init.h> contains\n" "section definitions for use in .S files.\n\n", modname, sec); } } #define ALL_INIT_DATA_SECTIONS \ ".init.setup", ".init.rodata", ".meminit.rodata", \ ".init.data", ".meminit.data" #define ALL_EXIT_DATA_SECTIONS \ ".exit.data", ".memexit.data" #define ALL_INIT_TEXT_SECTIONS \ ".init.text", ".meminit.text" #define ALL_EXIT_TEXT_SECTIONS \ ".exit.text", ".memexit.text" #define ALL_PCI_INIT_SECTIONS \ ".pci_fixup_early", ".pci_fixup_header", ".pci_fixup_final", \ ".pci_fixup_enable", ".pci_fixup_resume", \ ".pci_fixup_resume_early", ".pci_fixup_suspend" #define ALL_XXXINIT_SECTIONS MEM_INIT_SECTIONS #define ALL_XXXEXIT_SECTIONS MEM_EXIT_SECTIONS #define ALL_INIT_SECTIONS INIT_SECTIONS, ALL_XXXINIT_SECTIONS #define ALL_EXIT_SECTIONS EXIT_SECTIONS, ALL_XXXEXIT_SECTIONS #define DATA_SECTIONS ".data", ".data.rel" #define TEXT_SECTIONS ".text", ".text.*", ".sched.text", \ ".kprobes.text", ".cpuidle.text", ".noinstr.text" #define OTHER_TEXT_SECTIONS ".ref.text", ".head.text", ".spinlock.text", \ ".fixup", ".entry.text", ".exception.text", \ ".coldtext", ".softirqentry.text" #define INIT_SECTIONS ".init.*" #define MEM_INIT_SECTIONS ".meminit.*" #define EXIT_SECTIONS ".exit.*" #define MEM_EXIT_SECTIONS ".memexit.*" #define ALL_TEXT_SECTIONS ALL_INIT_TEXT_SECTIONS, ALL_EXIT_TEXT_SECTIONS, \ TEXT_SECTIONS, OTHER_TEXT_SECTIONS enum mismatch { TEXT_TO_ANY_INIT, DATA_TO_ANY_INIT, TEXTDATA_TO_ANY_EXIT, XXXINIT_TO_SOME_INIT, XXXEXIT_TO_SOME_EXIT, ANY_INIT_TO_ANY_EXIT, ANY_EXIT_TO_ANY_INIT, EXTABLE_TO_NON_TEXT, }; /** * Describe how to match sections on different criteria: * * @fromsec: Array of sections to be matched. * * @bad_tosec: Relocations applied to a section in @fromsec to a section in * this array is forbidden (black-list). Can be empty. * * @good_tosec: Relocations applied to a section in @fromsec must be * targeting sections in this array (white-list). Can be empty. * * @mismatch: Type of mismatch. */ struct sectioncheck { const char *fromsec[20]; const char *bad_tosec[20]; const char *good_tosec[20]; enum mismatch mismatch; }; static const struct sectioncheck sectioncheck[] = { /* Do not reference init/exit code/data from * normal code and data */ { .fromsec = { TEXT_SECTIONS, NULL }, .bad_tosec = { ALL_INIT_SECTIONS, NULL }, .mismatch = TEXT_TO_ANY_INIT, }, { .fromsec = { DATA_SECTIONS, NULL }, .bad_tosec = { ALL_XXXINIT_SECTIONS, INIT_SECTIONS, NULL }, .mismatch = DATA_TO_ANY_INIT, }, { .fromsec = { TEXT_SECTIONS, DATA_SECTIONS, NULL }, .bad_tosec = { ALL_EXIT_SECTIONS, NULL }, .mismatch = TEXTDATA_TO_ANY_EXIT, }, /* Do not reference init code/data from meminit code/data */ { .fromsec = { ALL_XXXINIT_SECTIONS, NULL }, .bad_tosec = { INIT_SECTIONS, NULL }, .mismatch = XXXINIT_TO_SOME_INIT, }, /* Do not reference exit code/data from memexit code/data */ { .fromsec = { ALL_XXXEXIT_SECTIONS, NULL }, .bad_tosec = { EXIT_SECTIONS, NULL }, .mismatch = XXXEXIT_TO_SOME_EXIT, }, /* Do not use exit code/data from init code */ { .fromsec = { ALL_INIT_SECTIONS, NULL }, .bad_tosec = { ALL_EXIT_SECTIONS, NULL }, .mismatch = ANY_INIT_TO_ANY_EXIT, }, /* Do not use init code/data from exit code */ { .fromsec = { ALL_EXIT_SECTIONS, NULL }, .bad_tosec = { ALL_INIT_SECTIONS, NULL }, .mismatch = ANY_EXIT_TO_ANY_INIT, }, { .fromsec = { ALL_PCI_INIT_SECTIONS, NULL }, .bad_tosec = { INIT_SECTIONS, NULL }, .mismatch = ANY_INIT_TO_ANY_EXIT, }, { .fromsec = { "__ex_table", NULL }, /* If you're adding any new black-listed sections in here, consider * adding a special 'printer' for them in scripts/check_extable. */ .bad_tosec = { ".altinstr_replacement", NULL }, .good_tosec = {ALL_TEXT_SECTIONS , NULL}, .mismatch = EXTABLE_TO_NON_TEXT, } }; static const struct sectioncheck *section_mismatch( const char *fromsec, const char *tosec) { int i; /* * The target section could be the SHT_NUL section when we're * handling relocations to un-resolved symbols, trying to match it * doesn't make much sense and causes build failures on parisc * architectures. */ if (*tosec == '\0') return NULL; for (i = 0; i < ARRAY_SIZE(sectioncheck); i++) { const struct sectioncheck *check = &sectioncheck[i]; if (match(fromsec, check->fromsec)) { if (check->bad_tosec[0] && match(tosec, check->bad_tosec)) return check; if (check->good_tosec[0] && !match(tosec, check->good_tosec)) return check; } } return NULL; } /** * Whitelist to allow certain references to pass with no warning. * * Pattern 1: * If a module parameter is declared __initdata and permissions=0 * then this is legal despite the warning generated. * We cannot see value of permissions here, so just ignore * this pattern. * The pattern is identified by: * tosec = .init.data * fromsec = .data* * atsym =__param* * * Pattern 1a: * module_param_call() ops can refer to __init set function if permissions=0 * The pattern is identified by: * tosec = .init.text * fromsec = .data* * atsym = __param_ops_* * * Pattern 3: * Whitelist all references from .head.text to any init section * * Pattern 4: * Some symbols belong to init section but still it is ok to reference * these from non-init sections as these symbols don't have any memory * allocated for them and symbol address and value are same. So even * if init section is freed, its ok to reference those symbols. * For ex. symbols marking the init section boundaries. * This pattern is identified by * refsymname = __init_begin, _sinittext, _einittext * * Pattern 5: * GCC may optimize static inlines when fed constant arg(s) resulting * in functions like cpumask_empty() -- generating an associated symbol * cpumask_empty.constprop.3 that appears in the audit. If the const that * is passed in comes from __init, like say nmi_ipi_mask, we get a * meaningless section warning. May need to add isra symbols too... * This pattern is identified by * tosec = init section * fromsec = text section * refsymname = *.constprop.* * **/ static int secref_whitelist(const char *fromsec, const char *fromsym, const char *tosec, const char *tosym) { /* Check for pattern 1 */ if (match(tosec, PATTERNS(ALL_INIT_DATA_SECTIONS)) && match(fromsec, PATTERNS(DATA_SECTIONS)) && strstarts(fromsym, "__param")) return 0; /* Check for pattern 1a */ if (strcmp(tosec, ".init.text") == 0 && match(fromsec, PATTERNS(DATA_SECTIONS)) && strstarts(fromsym, "__param_ops_")) return 0; /* symbols in data sections that may refer to any init/exit sections */ if (match(fromsec, PATTERNS(DATA_SECTIONS)) && match(tosec, PATTERNS(ALL_INIT_SECTIONS, ALL_EXIT_SECTIONS)) && match(fromsym, PATTERNS("*_template", // scsi uses *_template a lot "*_timer", // arm uses ops structures named _timer a lot "*_sht", // scsi also used *_sht to some extent "*_ops", "*_probe", "*_probe_one", "*_console"))) return 0; /* symbols in data sections that may refer to meminit/exit sections */ if (match(fromsec, PATTERNS(DATA_SECTIONS)) && match(tosec, PATTERNS(ALL_XXXINIT_SECTIONS, ALL_EXIT_SECTIONS)) && match(fromsym, PATTERNS("*driver"))) return 0; /* Check for pattern 3 */ if (strstarts(fromsec, ".head.text") && match(tosec, PATTERNS(ALL_INIT_SECTIONS))) return 0; /* Check for pattern 4 */ if (match(tosym, PATTERNS("__init_begin", "_sinittext", "_einittext"))) return 0; /* Check for pattern 5 */ if (match(fromsec, PATTERNS(ALL_TEXT_SECTIONS)) && match(tosec, PATTERNS(ALL_INIT_SECTIONS)) && match(fromsym, PATTERNS("*.constprop.*"))) return 0; return 1; } /* * If there's no name there, ignore it; likewise, ignore it if it's * one of the magic symbols emitted used by current tools. * * Otherwise if find_symbols_between() returns those symbols, they'll * fail the whitelist tests and cause lots of false alarms ... fixable * only by merging __exit and __init sections into __text, bloating * the kernel (which is especially evil on embedded platforms). */ static inline int is_valid_name(struct elf_info *elf, Elf_Sym *sym) { const char *name = elf->strtab + sym->st_name; if (!name || !strlen(name)) return 0; return !is_mapping_symbol(name); } /* Look up the nearest symbol based on the section and the address */ static Elf_Sym *find_nearest_sym(struct elf_info *elf, Elf_Addr addr, unsigned int secndx, bool allow_negative, Elf_Addr min_distance) { Elf_Sym *sym; Elf_Sym *near = NULL; Elf_Addr sym_addr, distance; bool is_arm = (elf->hdr->e_machine == EM_ARM); for (sym = elf->symtab_start; sym < elf->symtab_stop; sym++) { if (get_secindex(elf, sym) != secndx) continue; if (!is_valid_name(elf, sym)) continue; sym_addr = sym->st_value; /* * For ARM Thumb instruction, the bit 0 of st_value is set * if the symbol is STT_FUNC type. Mask it to get the address. */ if (is_arm && ELF_ST_TYPE(sym->st_info) == STT_FUNC) sym_addr &= ~1; if (addr >= sym_addr) distance = addr - sym_addr; else if (allow_negative) distance = sym_addr - addr; else continue; if (distance <= min_distance) { min_distance = distance; near = sym; } if (min_distance == 0) break; } return near; } static Elf_Sym *find_fromsym(struct elf_info *elf, Elf_Addr addr, unsigned int secndx) { return find_nearest_sym(elf, addr, secndx, false, ~0); } static Elf_Sym *find_tosym(struct elf_info *elf, Elf_Addr addr, Elf_Sym *sym) { /* If the supplied symbol has a valid name, return it */ if (is_valid_name(elf, sym)) return sym; /* * Strive to find a better symbol name, but the resulting name may not * match the symbol referenced in the original code. */ return find_nearest_sym(elf, addr, get_secindex(elf, sym), true, 20); } static bool is_executable_section(struct elf_info *elf, unsigned int secndx) { if (secndx >= elf->num_sections) return false; return (elf->sechdrs[secndx].sh_flags & SHF_EXECINSTR) != 0; } static void default_mismatch_handler(const char *modname, struct elf_info *elf, const struct sectioncheck* const mismatch, Elf_Sym *tsym, unsigned int fsecndx, const char *fromsec, Elf_Addr faddr, const char *tosec, Elf_Addr taddr) { Elf_Sym *from; const char *tosym; const char *fromsym; from = find_fromsym(elf, faddr, fsecndx); fromsym = sym_name(elf, from); tsym = find_tosym(elf, taddr, tsym); tosym = sym_name(elf, tsym); /* check whitelist - we may ignore it */ if (!secref_whitelist(fromsec, fromsym, tosec, tosym)) return; sec_mismatch_count++; warn("%s: section mismatch in reference: %s+0x%x (section: %s) -> %s (section: %s)\n", modname, fromsym, (unsigned int)(faddr - from->st_value), fromsec, tosym, tosec); if (mismatch->mismatch == EXTABLE_TO_NON_TEXT) { if (match(tosec, mismatch->bad_tosec)) fatal("The relocation at %s+0x%lx references\n" "section \"%s\" which is black-listed.\n" "Something is seriously wrong and should be fixed.\n" "You might get more information about where this is\n" "coming from by using scripts/check_extable.sh %s\n", fromsec, (long)faddr, tosec, modname); else if (is_executable_section(elf, get_secindex(elf, tsym))) warn("The relocation at %s+0x%lx references\n" "section \"%s\" which is not in the list of\n" "authorized sections. If you're adding a new section\n" "and/or if this reference is valid, add \"%s\" to the\n" "list of authorized sections to jump to on fault.\n" "This can be achieved by adding \"%s\" to\n" "OTHER_TEXT_SECTIONS in scripts/mod/modpost.c.\n", fromsec, (long)faddr, tosec, tosec, tosec); else error("%s+0x%lx references non-executable section '%s'\n", fromsec, (long)faddr, tosec); } } static void check_export_symbol(struct module *mod, struct elf_info *elf, Elf_Addr faddr, const char *secname, Elf_Sym *sym) { static const char *prefix = "__export_symbol_"; const char *label_name, *name, *data; Elf_Sym *label; struct symbol *s; bool is_gpl; label = find_fromsym(elf, faddr, elf->export_symbol_secndx); label_name = sym_name(elf, label); if (!strstarts(label_name, prefix)) { error("%s: .export_symbol section contains strange symbol '%s'\n", mod->name, label_name); return; } if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL && ELF_ST_BIND(sym->st_info) != STB_WEAK) { error("%s: local symbol '%s' was exported\n", mod->name, label_name + strlen(prefix)); return; } name = sym_name(elf, sym); if (strcmp(label_name + strlen(prefix), name)) { error("%s: .export_symbol section references '%s', but it does not seem to be an export symbol\n", mod->name, name); return; } data = sym_get_data(elf, label); /* license */ if (!strcmp(data, "GPL")) { is_gpl = true; } else if (!strcmp(data, "")) { is_gpl = false; } else { error("%s: unknown license '%s' was specified for '%s'\n", mod->name, data, name); return; } data += strlen(data) + 1; /* namespace */ s = sym_add_exported(name, mod, is_gpl, data); /* * We need to be aware whether we are exporting a function or * a data on some architectures. */ s->is_func = (ELF_ST_TYPE(sym->st_info) == STT_FUNC); /* * For parisc64, symbols prefixed $$ from the library have the symbol type * STT_LOPROC. They should be handled as functions too. */ if (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64 && elf->hdr->e_machine == EM_PARISC && ELF_ST_TYPE(sym->st_info) == STT_LOPROC) s->is_func = true; if (match(secname, PATTERNS(INIT_SECTIONS))) warn("%s: %s: EXPORT_SYMBOL used for init symbol. Remove __init or EXPORT_SYMBOL.\n", mod->name, name); else if (match(secname, PATTERNS(EXIT_SECTIONS))) warn("%s: %s: EXPORT_SYMBOL used for exit symbol. Remove __exit or EXPORT_SYMBOL.\n", mod->name, name); } static void check_section_mismatch(struct module *mod, struct elf_info *elf, Elf_Sym *sym, unsigned int fsecndx, const char *fromsec, Elf_Addr faddr, Elf_Addr taddr) { const char *tosec = sec_name(elf, get_secindex(elf, sym)); const struct sectioncheck *mismatch; if (module_enabled && elf->export_symbol_secndx == fsecndx) { check_export_symbol(mod, elf, faddr, tosec, sym); return; } mismatch = section_mismatch(fromsec, tosec); if (!mismatch) return; default_mismatch_handler(mod->name, elf, mismatch, sym, fsecndx, fromsec, faddr, tosec, taddr); } static Elf_Addr addend_386_rel(uint32_t *location, unsigned int r_type) { switch (r_type) { case R_386_32: return TO_NATIVE(*location); case R_386_PC32: return TO_NATIVE(*location) + 4; } return (Elf_Addr)(-1); } #ifndef R_ARM_CALL #define R_ARM_CALL 28 #endif #ifndef R_ARM_JUMP24 #define R_ARM_JUMP24 29 #endif #ifndef R_ARM_THM_CALL #define R_ARM_THM_CALL 10 #endif #ifndef R_ARM_THM_JUMP24 #define R_ARM_THM_JUMP24 30 #endif #ifndef R_ARM_MOVW_ABS_NC #define R_ARM_MOVW_ABS_NC 43 #endif #ifndef R_ARM_MOVT_ABS #define R_ARM_MOVT_ABS 44 #endif #ifndef R_ARM_THM_MOVW_ABS_NC #define R_ARM_THM_MOVW_ABS_NC 47 #endif #ifndef R_ARM_THM_MOVT_ABS #define R_ARM_THM_MOVT_ABS 48 #endif #ifndef R_ARM_THM_JUMP19 #define R_ARM_THM_JUMP19 51 #endif static int32_t sign_extend32(int32_t value, int index) { uint8_t shift = 31 - index; return (int32_t)(value << shift) >> shift; } static Elf_Addr addend_arm_rel(void *loc, Elf_Sym *sym, unsigned int r_type) { uint32_t inst, upper, lower, sign, j1, j2; int32_t offset; switch (r_type) { case R_ARM_ABS32: case R_ARM_REL32: inst = TO_NATIVE(*(uint32_t *)loc); return inst + sym->st_value; case R_ARM_MOVW_ABS_NC: case R_ARM_MOVT_ABS: inst = TO_NATIVE(*(uint32_t *)loc); offset = sign_extend32(((inst & 0xf0000) >> 4) | (inst & 0xfff), 15); return offset + sym->st_value; case R_ARM_PC24: case R_ARM_CALL: case R_ARM_JUMP24: inst = TO_NATIVE(*(uint32_t *)loc); offset = sign_extend32((inst & 0x00ffffff) << 2, 25); return offset + sym->st_value + 8; case R_ARM_THM_MOVW_ABS_NC: case R_ARM_THM_MOVT_ABS: upper = TO_NATIVE(*(uint16_t *)loc); lower = TO_NATIVE(*((uint16_t *)loc + 1)); offset = sign_extend32(((upper & 0x000f) << 12) | ((upper & 0x0400) << 1) | ((lower & 0x7000) >> 4) | (lower & 0x00ff), 15); return offset + sym->st_value; case R_ARM_THM_JUMP19: /* * Encoding T3: * S = upper[10] * imm6 = upper[5:0] * J1 = lower[13] * J2 = lower[11] * imm11 = lower[10:0] * imm32 = SignExtend(S:J2:J1:imm6:imm11:'0') */ upper = TO_NATIVE(*(uint16_t *)loc); lower = TO_NATIVE(*((uint16_t *)loc + 1)); sign = (upper >> 10) & 1; j1 = (lower >> 13) & 1; j2 = (lower >> 11) & 1; offset = sign_extend32((sign << 20) | (j2 << 19) | (j1 << 18) | ((upper & 0x03f) << 12) | ((lower & 0x07ff) << 1), 20); return offset + sym->st_value + 4; case R_ARM_THM_CALL: case R_ARM_THM_JUMP24: /* * Encoding T4: * S = upper[10] * imm10 = upper[9:0] * J1 = lower[13] * J2 = lower[11] * imm11 = lower[10:0] * I1 = NOT(J1 XOR S) * I2 = NOT(J2 XOR S) * imm32 = SignExtend(S:I1:I2:imm10:imm11:'0') */ upper = TO_NATIVE(*(uint16_t *)loc); lower = TO_NATIVE(*((uint16_t *)loc + 1)); sign = (upper >> 10) & 1; j1 = (lower >> 13) & 1; j2 = (lower >> 11) & 1; offset = sign_extend32((sign << 24) | ((~(j1 ^ sign) & 1) << 23) | ((~(j2 ^ sign) & 1) << 22) | ((upper & 0x03ff) << 12) | ((lower & 0x07ff) << 1), 24); return offset + sym->st_value + 4; } return (Elf_Addr)(-1); } static Elf_Addr addend_mips_rel(uint32_t *location, unsigned int r_type) { uint32_t inst; inst = TO_NATIVE(*location); switch (r_type) { case R_MIPS_LO16: return inst & 0xffff; case R_MIPS_26: return (inst & 0x03ffffff) << 2; case R_MIPS_32: return inst; } return (Elf_Addr)(-1); } #ifndef EM_RISCV #define EM_RISCV 243 #endif #ifndef R_RISCV_SUB32 #define R_RISCV_SUB32 39 #endif #ifndef EM_LOONGARCH #define EM_LOONGARCH 258 #endif #ifndef R_LARCH_SUB32 #define R_LARCH_SUB32 55 #endif static void get_rel_type_and_sym(struct elf_info *elf, uint64_t r_info, unsigned int *r_type, unsigned int *r_sym) { typedef struct { Elf64_Word r_sym; /* Symbol index */ unsigned char r_ssym; /* Special symbol for 2nd relocation */ unsigned char r_type3; /* 3rd relocation type */ unsigned char r_type2; /* 2nd relocation type */ unsigned char r_type; /* 1st relocation type */ } Elf64_Mips_R_Info; bool is_64bit = (elf->hdr->e_ident[EI_CLASS] == ELFCLASS64); if (elf->hdr->e_machine == EM_MIPS && is_64bit) { Elf64_Mips_R_Info *mips64_r_info = (void *)&r_info; *r_type = mips64_r_info->r_type; *r_sym = TO_NATIVE(mips64_r_info->r_sym); return; } if (is_64bit) { Elf64_Xword r_info64 = r_info; r_info = TO_NATIVE(r_info64); } else { Elf32_Word r_info32 = r_info; r_info = TO_NATIVE(r_info32); } *r_type = ELF_R_TYPE(r_info); *r_sym = ELF_R_SYM(r_info); } static void section_rela(struct module *mod, struct elf_info *elf, Elf_Shdr *sechdr) { Elf_Rela *rela; unsigned int fsecndx = sechdr->sh_info; const char *fromsec = sec_name(elf, fsecndx); Elf_Rela *start = (void *)elf->hdr + sechdr->sh_offset; Elf_Rela *stop = (void *)start + sechdr->sh_size; /* if from section (name) is know good then skip it */ if (match(fromsec, section_white_list)) return; for (rela = start; rela < stop; rela++) { Elf_Addr taddr, r_offset; unsigned int r_type, r_sym; r_offset = TO_NATIVE(rela->r_offset); get_rel_type_and_sym(elf, rela->r_info, &r_type, &r_sym); taddr = TO_NATIVE(rela->r_addend); switch (elf->hdr->e_machine) { case EM_RISCV: if (!strcmp("__ex_table", fromsec) && r_type == R_RISCV_SUB32) continue; break; case EM_LOONGARCH: if (!strcmp("__ex_table", fromsec) && r_type == R_LARCH_SUB32) continue; break; } check_section_mismatch(mod, elf, elf->symtab_start + r_sym, fsecndx, fromsec, r_offset, taddr); } } static void section_rel(struct module *mod, struct elf_info *elf, Elf_Shdr *sechdr) { Elf_Rel *rel; unsigned int fsecndx = sechdr->sh_info; const char *fromsec = sec_name(elf, fsecndx); Elf_Rel *start = (void *)elf->hdr + sechdr->sh_offset; Elf_Rel *stop = (void *)start + sechdr->sh_size; /* if from section (name) is know good then skip it */ if (match(fromsec, section_white_list)) return; for (rel = start; rel < stop; rel++) { Elf_Sym *tsym; Elf_Addr taddr = 0, r_offset; unsigned int r_type, r_sym; void *loc; r_offset = TO_NATIVE(rel->r_offset); get_rel_type_and_sym(elf, rel->r_info, &r_type, &r_sym); loc = sym_get_data_by_offset(elf, fsecndx, r_offset); tsym = elf->symtab_start + r_sym; switch (elf->hdr->e_machine) { case EM_386: taddr = addend_386_rel(loc, r_type); break; case EM_ARM: taddr = addend_arm_rel(loc, tsym, r_type); break; case EM_MIPS: taddr = addend_mips_rel(loc, r_type); break; default: fatal("Please add code to calculate addend for this architecture\n"); } check_section_mismatch(mod, elf, tsym, fsecndx, fromsec, r_offset, taddr); } } /** * A module includes a number of sections that are discarded * either when loaded or when used as built-in. * For loaded modules all functions marked __init and all data * marked __initdata will be discarded when the module has been initialized. * Likewise for modules used built-in the sections marked __exit * are discarded because __exit marked function are supposed to be called * only when a module is unloaded which never happens for built-in modules. * The check_sec_ref() function traverses all relocation records * to find all references to a section that reference a section that will * be discarded and warns about it. **/ static void check_sec_ref(struct module *mod, struct elf_info *elf) { int i; Elf_Shdr *sechdrs = elf->sechdrs; /* Walk through all sections */ for (i = 0; i < elf->num_sections; i++) { check_section(mod->name, elf, &elf->sechdrs[i]); /* We want to process only relocation sections and not .init */ if (sechdrs[i].sh_type == SHT_RELA) section_rela(mod, elf, &elf->sechdrs[i]); else if (sechdrs[i].sh_type == SHT_REL) section_rel(mod, elf, &elf->sechdrs[i]); } } static char *remove_dot(char *s) { size_t n = strcspn(s, "."); if (n && s[n]) { size_t m = strspn(s + n + 1, "0123456789"); if (m && (s[n + m + 1] == '.' || s[n + m + 1] == 0)) s[n] = 0; } return s; } /* * The CRCs are recorded in .*.cmd files in the form of: * #SYMVER <name> <crc> */ static void extract_crcs_for_object(const char *object, struct module *mod) { char cmd_file[PATH_MAX]; char *buf, *p; const char *base; int dirlen, ret; base = strrchr(object, '/'); if (base) { base++; dirlen = base - object; } else { dirlen = 0; base = object; } ret = snprintf(cmd_file, sizeof(cmd_file), "%.*s.%s.cmd", dirlen, object, base); if (ret >= sizeof(cmd_file)) { error("%s: too long path was truncated\n", cmd_file); return; } buf = read_text_file(cmd_file); p = buf; while ((p = strstr(p, "\n#SYMVER "))) { char *name; size_t namelen; unsigned int crc; struct symbol *sym; name = p + strlen("\n#SYMVER "); p = strchr(name, ' '); if (!p) break; namelen = p - name; p++; if (!isdigit(*p)) continue; /* skip this line */ crc = strtoul(p, &p, 0); if (*p != '\n') continue; /* skip this line */ name[namelen] = '\0'; /* * sym_find_with_module() may return NULL here. * It typically occurs when CONFIG_TRIM_UNUSED_KSYMS=y. * Since commit e1327a127703, genksyms calculates CRCs of all * symbols, including trimmed ones. Ignore orphan CRCs. */ sym = sym_find_with_module(name, mod); if (sym) sym_set_crc(sym, crc); } free(buf); } /* * The symbol versions (CRC) are recorded in the .*.cmd files. * Parse them to retrieve CRCs for the current module. */ static void mod_set_crcs(struct module *mod) { char objlist[PATH_MAX]; char *buf, *p, *obj; int ret; if (mod->is_vmlinux) { strcpy(objlist, ".vmlinux.objs"); } else { /* objects for a module are listed in the *.mod file. */ ret = snprintf(objlist, sizeof(objlist), "%s.mod", mod->name); if (ret >= sizeof(objlist)) { error("%s: too long path was truncated\n", objlist); return; } } buf = read_text_file(objlist); p = buf; while ((obj = strsep(&p, "\n")) && obj[0]) extract_crcs_for_object(obj, mod); free(buf); } static void read_symbols(const char *modname) { const char *symname; char *version; char *license; char *namespace; struct module *mod; struct elf_info info = { }; Elf_Sym *sym; if (!parse_elf(&info, modname)) return; if (!strends(modname, ".o")) { error("%s: filename must be suffixed with .o\n", modname); return; } /* strip trailing .o */ mod = new_module(modname, strlen(modname) - strlen(".o")); if (!mod->is_vmlinux) { license = get_modinfo(&info, "license"); if (!license) error("missing MODULE_LICENSE() in %s\n", modname); while (license) { if (!license_is_gpl_compatible(license)) { mod->is_gpl_compatible = false; break; } license = get_next_modinfo(&info, "license", license); } namespace = get_modinfo(&info, "import_ns"); while (namespace) { add_namespace(&mod->imported_namespaces, namespace); namespace = get_next_modinfo(&info, "import_ns", namespace); } } if (extra_warn && !get_modinfo(&info, "description")) warn("missing MODULE_DESCRIPTION() in %s\n", modname); for (sym = info.symtab_start; sym < info.symtab_stop; sym++) { symname = remove_dot(info.strtab + sym->st_name); handle_symbol(mod, &info, sym, symname); handle_moddevtable(mod, &info, sym, symname); } check_sec_ref(mod, &info); if (!mod->is_vmlinux) { version = get_modinfo(&info, "version"); if (version || all_versions) get_src_version(mod->name, mod->srcversion, sizeof(mod->srcversion) - 1); } parse_elf_finish(&info); if (modversions) { /* * Our trick to get versioning for module struct etc. - it's * never passed as an argument to an exported function, so * the automatic versioning doesn't pick it up, but it's really * important anyhow. */ sym_add_unresolved("module_layout", mod, false); mod_set_crcs(mod); } } static void read_symbols_from_files(const char *filename) { FILE *in = stdin; char fname[PATH_MAX]; in = fopen(filename, "r"); if (!in) fatal("Can't open filenames file %s: %m", filename); while (fgets(fname, PATH_MAX, in) != NULL) { if (strends(fname, "\n")) fname[strlen(fname)-1] = '\0'; read_symbols(fname); } fclose(in); } #define SZ 500 /* We first write the generated file into memory using the * following helper, then compare to the file on disk and * only update the later if anything changed */ void __attribute__((format(printf, 2, 3))) buf_printf(struct buffer *buf, const char *fmt, ...) { char tmp[SZ]; int len; va_list ap; va_start(ap, fmt); len = vsnprintf(tmp, SZ, fmt, ap); buf_write(buf, tmp, len); va_end(ap); } void buf_write(struct buffer *buf, const char *s, int len) { if (buf->size - buf->pos < len) { buf->size += len + SZ; buf->p = NOFAIL(realloc(buf->p, buf->size)); } strncpy(buf->p + buf->pos, s, len); buf->pos += len; } static void check_exports(struct module *mod) { struct symbol *s, *exp; list_for_each_entry(s, &mod->unresolved_symbols, list) { const char *basename; exp = find_symbol(s->name); if (!exp) { if (!s->weak && nr_unresolved++ < MAX_UNRESOLVED_REPORTS) modpost_log(warn_unresolved ? LOG_WARN : LOG_ERROR, "\"%s\" [%s.ko] undefined!\n", s->name, mod->name); continue; } if (exp->module == mod) { error("\"%s\" [%s.ko] was exported without definition\n", s->name, mod->name); continue; } exp->used = true; s->module = exp->module; s->crc_valid = exp->crc_valid; s->crc = exp->crc; basename = strrchr(mod->name, '/'); if (basename) basename++; else basename = mod->name; if (!contains_namespace(&mod->imported_namespaces, exp->namespace)) { modpost_log(allow_missing_ns_imports ? LOG_WARN : LOG_ERROR, "module %s uses symbol %s from namespace %s, but does not import it.\n", basename, exp->name, exp->namespace); add_namespace(&mod->missing_namespaces, exp->namespace); } if (!mod->is_gpl_compatible && exp->is_gpl_only) error("GPL-incompatible module %s.ko uses GPL-only symbol '%s'\n", basename, exp->name); } } static void handle_white_list_exports(const char *white_list) { char *buf, *p, *name; buf = read_text_file(white_list); p = buf; while ((name = strsep(&p, "\n"))) { struct symbol *sym = find_symbol(name); if (sym) sym->used = true; } free(buf); } static void check_modname_len(struct module *mod) { const char *mod_name; mod_name = strrchr(mod->name, '/'); if (mod_name == NULL) mod_name = mod->name; else mod_name++; if (strlen(mod_name) >= MODULE_NAME_LEN) error("module name is too long [%s.ko]\n", mod->name); } /** * Header for the generated file **/ static void add_header(struct buffer *b, struct module *mod) { buf_printf(b, "#include <linux/module.h>\n"); /* * Include build-salt.h after module.h in order to * inherit the definitions. */ buf_printf(b, "#define INCLUDE_VERMAGIC\n"); buf_printf(b, "#include <linux/build-salt.h>\n"); buf_printf(b, "#include <linux/elfnote-lto.h>\n"); buf_printf(b, "#include <linux/export-internal.h>\n"); buf_printf(b, "#include <linux/vermagic.h>\n"); buf_printf(b, "#include <linux/compiler.h>\n"); buf_printf(b, "\n"); buf_printf(b, "#ifdef CONFIG_UNWINDER_ORC\n"); buf_printf(b, "#include <asm/orc_header.h>\n"); buf_printf(b, "ORC_HEADER;\n"); buf_printf(b, "#endif\n"); buf_printf(b, "\n"); buf_printf(b, "BUILD_SALT;\n"); buf_printf(b, "BUILD_LTO_INFO;\n"); buf_printf(b, "\n"); buf_printf(b, "MODULE_INFO(vermagic, VERMAGIC_STRING);\n"); buf_printf(b, "MODULE_INFO(name, KBUILD_MODNAME);\n"); buf_printf(b, "\n"); buf_printf(b, "__visible struct module __this_module\n"); buf_printf(b, "__section(\".gnu.linkonce.this_module\") = {\n"); buf_printf(b, "\t.name = KBUILD_MODNAME,\n"); if (mod->has_init) buf_printf(b, "\t.init = init_module,\n"); if (mod->has_cleanup) buf_printf(b, "#ifdef CONFIG_MODULE_UNLOAD\n" "\t.exit = cleanup_module,\n" "#endif\n"); buf_printf(b, "\t.arch = MODULE_ARCH_INIT,\n"); buf_printf(b, "};\n"); if (!external_module) buf_printf(b, "\nMODULE_INFO(intree, \"Y\");\n"); buf_printf(b, "\n" "#ifdef CONFIG_RETPOLINE\n" "MODULE_INFO(retpoline, \"Y\");\n" "#endif\n"); if (strstarts(mod->name, "drivers/staging")) buf_printf(b, "\nMODULE_INFO(staging, \"Y\");\n"); if (strstarts(mod->name, "tools/testing")) buf_printf(b, "\nMODULE_INFO(test, \"Y\");\n"); } static void add_exported_symbols(struct buffer *buf, struct module *mod) { struct symbol *sym; /* generate struct for exported symbols */ buf_printf(buf, "\n"); list_for_each_entry(sym, &mod->exported_symbols, list) { if (trim_unused_exports && !sym->used) continue; buf_printf(buf, "KSYMTAB_%s(%s, \"%s\", \"%s\");\n", sym->is_func ? "FUNC" : "DATA", sym->name, sym->is_gpl_only ? "_gpl" : "", sym->namespace); } if (!modversions) return; /* record CRCs for exported symbols */ buf_printf(buf, "\n"); list_for_each_entry(sym, &mod->exported_symbols, list) { if (trim_unused_exports && !sym->used) continue; if (!sym->crc_valid) warn("EXPORT symbol \"%s\" [%s%s] version generation failed, symbol will not be versioned.\n" "Is \"%s\" prototyped in <asm/asm-prototypes.h>?\n", sym->name, mod->name, mod->is_vmlinux ? "" : ".ko", sym->name); buf_printf(buf, "SYMBOL_CRC(%s, 0x%08x, \"%s\");\n", sym->name, sym->crc, sym->is_gpl_only ? "_gpl" : ""); } } /** * Record CRCs for unresolved symbols **/ static void add_versions(struct buffer *b, struct module *mod) { struct symbol *s; if (!modversions) return; buf_printf(b, "\n"); buf_printf(b, "static const struct modversion_info ____versions[]\n"); buf_printf(b, "__used __section(\"__versions\") = {\n"); list_for_each_entry(s, &mod->unresolved_symbols, list) { if (!s->module) continue; if (!s->crc_valid) { warn("\"%s\" [%s.ko] has no CRC!\n", s->name, mod->name); continue; } if (strlen(s->name) >= MODULE_NAME_LEN) { error("too long symbol \"%s\" [%s.ko]\n", s->name, mod->name); break; } buf_printf(b, "\t{ %#8x, \"%s\" },\n", s->crc, s->name); } buf_printf(b, "};\n"); } static void add_depends(struct buffer *b, struct module *mod) { struct symbol *s; int first = 1; /* Clear ->seen flag of modules that own symbols needed by this. */ list_for_each_entry(s, &mod->unresolved_symbols, list) { if (s->module) s->module->seen = s->module->is_vmlinux; } buf_printf(b, "\n"); buf_printf(b, "MODULE_INFO(depends, \""); list_for_each_entry(s, &mod->unresolved_symbols, list) { const char *p; if (!s->module) continue; if (s->module->seen) continue; s->module->seen = true; p = strrchr(s->module->name, '/'); if (p) p++; else p = s->module->name; buf_printf(b, "%s%s", first ? "" : ",", p); first = 0; } buf_printf(b, "\");\n"); } static void add_srcversion(struct buffer *b, struct module *mod) { if (mod->srcversion[0]) { buf_printf(b, "\n"); buf_printf(b, "MODULE_INFO(srcversion, \"%s\");\n", mod->srcversion); } } static void write_buf(struct buffer *b, const char *fname) { FILE *file; if (error_occurred) return; file = fopen(fname, "w"); if (!file) { perror(fname); exit(1); } if (fwrite(b->p, 1, b->pos, file) != b->pos) { perror(fname); exit(1); } if (fclose(file) != 0) { perror(fname); exit(1); } } static void write_if_changed(struct buffer *b, const char *fname) { char *tmp; FILE *file; struct stat st; file = fopen(fname, "r"); if (!file) goto write; if (fstat(fileno(file), &st) < 0) goto close_write; if (st.st_size != b->pos) goto close_write; tmp = NOFAIL(malloc(b->pos)); if (fread(tmp, 1, b->pos, file) != b->pos) goto free_write; if (memcmp(tmp, b->p, b->pos) != 0) goto free_write; free(tmp); fclose(file); return; free_write: free(tmp); close_write: fclose(file); write: write_buf(b, fname); } static void write_vmlinux_export_c_file(struct module *mod) { struct buffer buf = { }; buf_printf(&buf, "#include <linux/export-internal.h>\n"); add_exported_symbols(&buf, mod); write_if_changed(&buf, ".vmlinux.export.c"); free(buf.p); } /* do sanity checks, and generate *.mod.c file */ static void write_mod_c_file(struct module *mod) { struct buffer buf = { }; char fname[PATH_MAX]; int ret; add_header(&buf, mod); add_exported_symbols(&buf, mod); add_versions(&buf, mod); add_depends(&buf, mod); add_moddevtable(&buf, mod); add_srcversion(&buf, mod); ret = snprintf(fname, sizeof(fname), "%s.mod.c", mod->name); if (ret >= sizeof(fname)) { error("%s: too long path was truncated\n", fname); goto free; } write_if_changed(&buf, fname); free: free(buf.p); } /* parse Module.symvers file. line format: * 0x12345678<tab>symbol<tab>module<tab>export<tab>namespace **/ static void read_dump(const char *fname) { char *buf, *pos, *line; buf = read_text_file(fname); if (!buf) /* No symbol versions, silently ignore */ return; pos = buf; while ((line = get_line(&pos))) { char *symname, *namespace, *modname, *d, *export; unsigned int crc; struct module *mod; struct symbol *s; bool gpl_only; if (!(symname = strchr(line, '\t'))) goto fail; *symname++ = '\0'; if (!(modname = strchr(symname, '\t'))) goto fail; *modname++ = '\0'; if (!(export = strchr(modname, '\t'))) goto fail; *export++ = '\0'; if (!(namespace = strchr(export, '\t'))) goto fail; *namespace++ = '\0'; crc = strtoul(line, &d, 16); if (*symname == '\0' || *modname == '\0' || *d != '\0') goto fail; if (!strcmp(export, "EXPORT_SYMBOL_GPL")) { gpl_only = true; } else if (!strcmp(export, "EXPORT_SYMBOL")) { gpl_only = false; } else { error("%s: unknown license %s. skip", symname, export); continue; } mod = find_module(modname); if (!mod) { mod = new_module(modname, strlen(modname)); mod->from_dump = true; } s = sym_add_exported(symname, mod, gpl_only, namespace); sym_set_crc(s, crc); } free(buf); return; fail: free(buf); fatal("parse error in symbol dump file\n"); } static void write_dump(const char *fname) { struct buffer buf = { }; struct module *mod; struct symbol *sym; list_for_each_entry(mod, &modules, list) { if (mod->from_dump) continue; list_for_each_entry(sym, &mod->exported_symbols, list) { if (trim_unused_exports && !sym->used) continue; buf_printf(&buf, "0x%08x\t%s\t%s\tEXPORT_SYMBOL%s\t%s\n", sym->crc, sym->name, mod->name, sym->is_gpl_only ? "_GPL" : "", sym->namespace); } } write_buf(&buf, fname); free(buf.p); } static void write_namespace_deps_files(const char *fname) { struct module *mod; struct namespace_list *ns; struct buffer ns_deps_buf = {}; list_for_each_entry(mod, &modules, list) { if (mod->from_dump || list_empty(&mod->missing_namespaces)) continue; buf_printf(&ns_deps_buf, "%s.ko:", mod->name); list_for_each_entry(ns, &mod->missing_namespaces, list) buf_printf(&ns_deps_buf, " %s", ns->namespace); buf_printf(&ns_deps_buf, "\n"); } write_if_changed(&ns_deps_buf, fname); free(ns_deps_buf.p); } struct dump_list { struct list_head list; const char *file; }; int main(int argc, char **argv) { struct module *mod; char *missing_namespace_deps = NULL; char *unused_exports_white_list = NULL; char *dump_write = NULL, *files_source = NULL; int opt; LIST_HEAD(dump_lists); struct dump_list *dl, *dl2; while ((opt = getopt(argc, argv, "ei:MmnT:to:au:WwENd:")) != -1) { switch (opt) { case 'e': external_module = true; break; case 'i': dl = NOFAIL(malloc(sizeof(*dl))); dl->file = optarg; list_add_tail(&dl->list, &dump_lists); break; case 'M': module_enabled = true; break; case 'm': modversions = true; break; case 'n': ignore_missing_files = true; break; case 'o': dump_write = optarg; break; case 'a': all_versions = true; break; case 'T': files_source = optarg; break; case 't': trim_unused_exports = true; break; case 'u': unused_exports_white_list = optarg; break; case 'W': extra_warn = true; break; case 'w': warn_unresolved = true; break; case 'E': sec_mismatch_warn_only = false; break; case 'N': allow_missing_ns_imports = true; break; case 'd': missing_namespace_deps = optarg; break; default: exit(1); } } list_for_each_entry_safe(dl, dl2, &dump_lists, list) { read_dump(dl->file); list_del(&dl->list); free(dl); } while (optind < argc) read_symbols(argv[optind++]); if (files_source) read_symbols_from_files(files_source); list_for_each_entry(mod, &modules, list) { if (mod->from_dump || mod->is_vmlinux) continue; check_modname_len(mod); check_exports(mod); } if (unused_exports_white_list) handle_white_list_exports(unused_exports_white_list); list_for_each_entry(mod, &modules, list) { if (mod->from_dump) continue; if (mod->is_vmlinux) write_vmlinux_export_c_file(mod); else write_mod_c_file(mod); } if (missing_namespace_deps) write_namespace_deps_files(missing_namespace_deps); if (dump_write) write_dump(dump_write); if (sec_mismatch_count && !sec_mismatch_warn_only) error("Section mismatches detected.\n" "Set CONFIG_SECTION_MISMATCH_WARN_ONLY=y to allow them.\n"); if (nr_unresolved > MAX_UNRESOLVED_REPORTS) warn("suppressed %u unresolved symbol warnings because there were too many)\n", nr_unresolved - MAX_UNRESOLVED_REPORTS); return error_occurred ? 1 : 0; }
linux-master
scripts/mod/modpost.c
// SPDX-License-Identifier: GPL-2.0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <elf.h> int main(int argc, char **argv) { unsigned char ei[EI_NIDENT]; union { short s; char c[2]; } endian_test; if (fread(ei, 1, EI_NIDENT, stdin) != EI_NIDENT) { fprintf(stderr, "Error: input truncated\n"); return 1; } if (memcmp(ei, ELFMAG, SELFMAG) != 0) { fprintf(stderr, "Error: not ELF\n"); return 1; } switch (ei[EI_CLASS]) { case ELFCLASS32: printf("#define KERNEL_ELFCLASS ELFCLASS32\n"); break; case ELFCLASS64: printf("#define KERNEL_ELFCLASS ELFCLASS64\n"); break; default: exit(1); } switch (ei[EI_DATA]) { case ELFDATA2LSB: printf("#define KERNEL_ELFDATA ELFDATA2LSB\n"); break; case ELFDATA2MSB: printf("#define KERNEL_ELFDATA ELFDATA2MSB\n"); break; default: exit(1); } if (sizeof(unsigned long) == 4) { printf("#define HOST_ELFCLASS ELFCLASS32\n"); } else if (sizeof(unsigned long) == 8) { printf("#define HOST_ELFCLASS ELFCLASS64\n"); } endian_test.s = 0x0102; if (memcmp(endian_test.c, "\x01\x02", 2) == 0) printf("#define HOST_ELFDATA ELFDATA2MSB\n"); else if (memcmp(endian_test.c, "\x02\x01", 2) == 0) printf("#define HOST_ELFDATA ELFDATA2LSB\n"); else exit(1); return 0; }
linux-master
scripts/mod/mk_elfconfig.c
/* empty file to figure out endianness / word size */
linux-master
scripts/mod/empty.c
// SPDX-License-Identifier: GPL-2.0 /* * lib/bust_spinlocks.c * * Provides a minimal bust_spinlocks for architectures which don't * have one of their own. * * bust_spinlocks() clears any spinlocks which would prevent oops, die(), BUG() * and panic() information from reaching the user. */ #include <linux/kernel.h> #include <linux/printk.h> #include <linux/spinlock.h> #include <linux/tty.h> #include <linux/wait.h> #include <linux/vt_kern.h> #include <linux/console.h> void bust_spinlocks(int yes) { if (yes) { ++oops_in_progress; } else { console_unblank(); if (--oops_in_progress == 0) wake_up_klogd(); } }
linux-master
lib/bust_spinlocks.c
// SPDX-License-Identifier: GPL-2.0-only /* * Lock-less NULL terminated single linked list * * The basic atomic operation of this list is cmpxchg on long. On * architectures that don't have NMI-safe cmpxchg implementation, the * list can NOT be used in NMI handlers. So code that uses the list in * an NMI handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG. * * Copyright 2010,2011 Intel Corp. * Author: Huang Ying <[email protected]> */ #include <linux/kernel.h> #include <linux/export.h> #include <linux/llist.h> /** * llist_add_batch - add several linked entries in batch * @new_first: first entry in batch to be added * @new_last: last entry in batch to be added * @head: the head for your lock-less list * * Return whether list is empty before adding. */ bool llist_add_batch(struct llist_node *new_first, struct llist_node *new_last, struct llist_head *head) { struct llist_node *first = READ_ONCE(head->first); do { new_last->next = first; } while (!try_cmpxchg(&head->first, &first, new_first)); return !first; } EXPORT_SYMBOL_GPL(llist_add_batch); /** * llist_del_first - delete the first entry of lock-less list * @head: the head for your lock-less list * * If list is empty, return NULL, otherwise, return the first entry * deleted, this is the newest added one. * * Only one llist_del_first user can be used simultaneously with * multiple llist_add users without lock. Because otherwise * llist_del_first, llist_add, llist_add (or llist_del_all, llist_add, * llist_add) sequence in another user may change @head->first->next, * but keep @head->first. If multiple consumers are needed, please * use llist_del_all or use lock between consumers. */ struct llist_node *llist_del_first(struct llist_head *head) { struct llist_node *entry, *next; entry = smp_load_acquire(&head->first); do { if (entry == NULL) return NULL; next = READ_ONCE(entry->next); } while (!try_cmpxchg(&head->first, &entry, next)); return entry; } EXPORT_SYMBOL_GPL(llist_del_first); /** * llist_reverse_order - reverse order of a llist chain * @head: first item of the list to be reversed * * Reverse the order of a chain of llist entries and return the * new first entry. */ struct llist_node *llist_reverse_order(struct llist_node *head) { struct llist_node *new_head = NULL; while (head) { struct llist_node *tmp = head; head = head->next; tmp->next = new_head; new_head = tmp; } return new_head; } EXPORT_SYMBOL_GPL(llist_reverse_order);
linux-master
lib/llist.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2015 Robert Jarzmik <[email protected]> * * Scatterlist splitting helpers. */ #include <linux/scatterlist.h> #include <linux/slab.h> struct sg_splitter { struct scatterlist *in_sg0; int nents; off_t skip_sg0; unsigned int length_last_sg; struct scatterlist *out_sg; }; static int sg_calculate_split(struct scatterlist *in, int nents, int nb_splits, off_t skip, const size_t *sizes, struct sg_splitter *splitters, bool mapped) { int i; unsigned int sglen; size_t size = sizes[0], len; struct sg_splitter *curr = splitters; struct scatterlist *sg; for (i = 0; i < nb_splits; i++) { splitters[i].in_sg0 = NULL; splitters[i].nents = 0; } for_each_sg(in, sg, nents, i) { sglen = mapped ? sg_dma_len(sg) : sg->length; if (skip > sglen) { skip -= sglen; continue; } len = min_t(size_t, size, sglen - skip); if (!curr->in_sg0) { curr->in_sg0 = sg; curr->skip_sg0 = skip; } size -= len; curr->nents++; curr->length_last_sg = len; while (!size && (skip + len < sglen) && (--nb_splits > 0)) { curr++; size = *(++sizes); skip += len; len = min_t(size_t, size, sglen - skip); curr->in_sg0 = sg; curr->skip_sg0 = skip; curr->nents = 1; curr->length_last_sg = len; size -= len; } skip = 0; if (!size && --nb_splits > 0) { curr++; size = *(++sizes); } if (!nb_splits) break; } return (size || !splitters[0].in_sg0) ? -EINVAL : 0; } static void sg_split_phys(struct sg_splitter *splitters, const int nb_splits) { int i, j; struct scatterlist *in_sg, *out_sg; struct sg_splitter *split; for (i = 0, split = splitters; i < nb_splits; i++, split++) { in_sg = split->in_sg0; out_sg = split->out_sg; for (j = 0; j < split->nents; j++, out_sg++) { *out_sg = *in_sg; if (!j) { out_sg->offset += split->skip_sg0; out_sg->length -= split->skip_sg0; } else { out_sg->offset = 0; } sg_dma_address(out_sg) = 0; sg_dma_len(out_sg) = 0; in_sg = sg_next(in_sg); } out_sg[-1].length = split->length_last_sg; sg_mark_end(out_sg - 1); } } static void sg_split_mapped(struct sg_splitter *splitters, const int nb_splits) { int i, j; struct scatterlist *in_sg, *out_sg; struct sg_splitter *split; for (i = 0, split = splitters; i < nb_splits; i++, split++) { in_sg = split->in_sg0; out_sg = split->out_sg; for (j = 0; j < split->nents; j++, out_sg++) { sg_dma_address(out_sg) = sg_dma_address(in_sg); sg_dma_len(out_sg) = sg_dma_len(in_sg); if (!j) { sg_dma_address(out_sg) += split->skip_sg0; sg_dma_len(out_sg) -= split->skip_sg0; } in_sg = sg_next(in_sg); } sg_dma_len(--out_sg) = split->length_last_sg; } } /** * sg_split - split a scatterlist into several scatterlists * @in: the input sg list * @in_mapped_nents: the result of a dma_map_sg(in, ...), or 0 if not mapped. * @skip: the number of bytes to skip in the input sg list * @nb_splits: the number of desired sg outputs * @split_sizes: the respective size of each output sg list in bytes * @out: an array where to store the allocated output sg lists * @out_mapped_nents: the resulting sg lists mapped number of sg entries. Might * be NULL if sglist not already mapped (in_mapped_nents = 0) * @gfp_mask: the allocation flag * * This function splits the input sg list into nb_splits sg lists, which are * allocated and stored into out. * The @in is split into : * - @out[0], which covers bytes [@skip .. @skip + @split_sizes[0] - 1] of @in * - @out[1], which covers bytes [@skip + split_sizes[0] .. * @skip + @split_sizes[0] + @split_sizes[1] -1] * etc ... * It will be the caller's duty to kfree() out array members. * * Returns 0 upon success, or error code */ int sg_split(struct scatterlist *in, const int in_mapped_nents, const off_t skip, const int nb_splits, const size_t *split_sizes, struct scatterlist **out, int *out_mapped_nents, gfp_t gfp_mask) { int i, ret; struct sg_splitter *splitters; splitters = kcalloc(nb_splits, sizeof(*splitters), gfp_mask); if (!splitters) return -ENOMEM; ret = sg_calculate_split(in, sg_nents(in), nb_splits, skip, split_sizes, splitters, false); if (ret < 0) goto err; ret = -ENOMEM; for (i = 0; i < nb_splits; i++) { splitters[i].out_sg = kmalloc_array(splitters[i].nents, sizeof(struct scatterlist), gfp_mask); if (!splitters[i].out_sg) goto err; } /* * The order of these 3 calls is important and should be kept. */ sg_split_phys(splitters, nb_splits); if (in_mapped_nents) { ret = sg_calculate_split(in, in_mapped_nents, nb_splits, skip, split_sizes, splitters, true); if (ret < 0) goto err; sg_split_mapped(splitters, nb_splits); } for (i = 0; i < nb_splits; i++) { out[i] = splitters[i].out_sg; if (out_mapped_nents) out_mapped_nents[i] = splitters[i].nents; } kfree(splitters); return 0; err: for (i = 0; i < nb_splits; i++) kfree(splitters[i].out_sg); kfree(splitters); return ret; } EXPORT_SYMBOL(sg_split);
linux-master
lib/sg_split.c
// SPDX-License-Identifier: GPL-2.0-only /* * crc4.c - simple crc-4 calculations. */ #include <linux/crc4.h> #include <linux/module.h> static const uint8_t crc4_tab[] = { 0x0, 0x7, 0xe, 0x9, 0xb, 0xc, 0x5, 0x2, 0x1, 0x6, 0xf, 0x8, 0xa, 0xd, 0x4, 0x3, }; /** * crc4 - calculate the 4-bit crc of a value. * @c: starting crc4 * @x: value to checksum * @bits: number of bits in @x to checksum * * Returns the crc4 value of @x, using polynomial 0b10111. * * The @x value is treated as left-aligned, and bits above @bits are ignored * in the crc calculations. */ uint8_t crc4(uint8_t c, uint64_t x, int bits) { int i; /* mask off anything above the top bit */ x &= (1ull << bits) - 1; /* Align to 4-bits */ bits = (bits + 3) & ~0x3; /* Calculate crc4 over four-bit nibbles, starting at the MSbit */ for (i = bits - 4; i >= 0; i -= 4) c = crc4_tab[c ^ ((x >> i) & 0xf)]; return c; } EXPORT_SYMBOL_GPL(crc4); MODULE_DESCRIPTION("CRC4 calculations"); MODULE_LICENSE("GPL");
linux-master
lib/crc4.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * lib/lshrdi3.c */ #include <linux/module.h> #include <linux/libgcc.h> long long notrace __lshrdi3(long long u, word_type b) { DWunion uu, w; word_type bm; if (b == 0) return u; uu.ll = u; bm = 32 - b; if (bm <= 0) { w.s.high = 0; w.s.low = (unsigned int) uu.s.high >> -bm; } else { const unsigned int carries = (unsigned int) uu.s.high << bm; w.s.high = (unsigned int) uu.s.high >> b; w.s.low = ((unsigned int) uu.s.low >> b) | carries; } return w.ll; } EXPORT_SYMBOL(__lshrdi3);
linux-master
lib/lshrdi3.c
#include <linux/libfdt_env.h> #include "../scripts/dtc/libfdt/fdt_empty_tree.c"
linux-master
lib/fdt_empty_tree.c
// SPDX-License-Identifier: GPL-2.0 /* * lib/locking-selftest.c * * Testsuite for various locking APIs: spinlocks, rwlocks, * mutexes and rw-semaphores. * * It is checking both false positives and false negatives. * * Started by Ingo Molnar: * * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <[email protected]> */ #include <linux/rwsem.h> #include <linux/mutex.h> #include <linux/ww_mutex.h> #include <linux/sched.h> #include <linux/sched/mm.h> #include <linux/delay.h> #include <linux/lockdep.h> #include <linux/spinlock.h> #include <linux/kallsyms.h> #include <linux/interrupt.h> #include <linux/debug_locks.h> #include <linux/irqflags.h> #include <linux/rtmutex.h> #include <linux/local_lock.h> #ifdef CONFIG_PREEMPT_RT # define NON_RT(...) #else # define NON_RT(...) __VA_ARGS__ #endif /* * Change this to 1 if you want to see the failure printouts: */ static unsigned int debug_locks_verbose; unsigned int force_read_lock_recursive; static DEFINE_WD_CLASS(ww_lockdep); static int __init setup_debug_locks_verbose(char *str) { get_option(&str, &debug_locks_verbose); return 1; } __setup("debug_locks_verbose=", setup_debug_locks_verbose); #define FAILURE 0 #define SUCCESS 1 #define LOCKTYPE_SPIN 0x1 #define LOCKTYPE_RWLOCK 0x2 #define LOCKTYPE_MUTEX 0x4 #define LOCKTYPE_RWSEM 0x8 #define LOCKTYPE_WW 0x10 #define LOCKTYPE_RTMUTEX 0x20 #define LOCKTYPE_LL 0x40 #define LOCKTYPE_SPECIAL 0x80 static struct ww_acquire_ctx t, t2; static struct ww_mutex o, o2, o3; /* * Normal standalone locks, for the circular and irq-context * dependency tests: */ static DEFINE_SPINLOCK(lock_A); static DEFINE_SPINLOCK(lock_B); static DEFINE_SPINLOCK(lock_C); static DEFINE_SPINLOCK(lock_D); static DEFINE_RAW_SPINLOCK(raw_lock_A); static DEFINE_RAW_SPINLOCK(raw_lock_B); static DEFINE_RWLOCK(rwlock_A); static DEFINE_RWLOCK(rwlock_B); static DEFINE_RWLOCK(rwlock_C); static DEFINE_RWLOCK(rwlock_D); static DEFINE_MUTEX(mutex_A); static DEFINE_MUTEX(mutex_B); static DEFINE_MUTEX(mutex_C); static DEFINE_MUTEX(mutex_D); static DECLARE_RWSEM(rwsem_A); static DECLARE_RWSEM(rwsem_B); static DECLARE_RWSEM(rwsem_C); static DECLARE_RWSEM(rwsem_D); #ifdef CONFIG_RT_MUTEXES static DEFINE_RT_MUTEX(rtmutex_A); static DEFINE_RT_MUTEX(rtmutex_B); static DEFINE_RT_MUTEX(rtmutex_C); static DEFINE_RT_MUTEX(rtmutex_D); #endif /* * Locks that we initialize dynamically as well so that * e.g. X1 and X2 becomes two instances of the same class, * but X* and Y* are different classes. We do this so that * we do not trigger a real lockup: */ static DEFINE_SPINLOCK(lock_X1); static DEFINE_SPINLOCK(lock_X2); static DEFINE_SPINLOCK(lock_Y1); static DEFINE_SPINLOCK(lock_Y2); static DEFINE_SPINLOCK(lock_Z1); static DEFINE_SPINLOCK(lock_Z2); static DEFINE_RWLOCK(rwlock_X1); static DEFINE_RWLOCK(rwlock_X2); static DEFINE_RWLOCK(rwlock_Y1); static DEFINE_RWLOCK(rwlock_Y2); static DEFINE_RWLOCK(rwlock_Z1); static DEFINE_RWLOCK(rwlock_Z2); static DEFINE_MUTEX(mutex_X1); static DEFINE_MUTEX(mutex_X2); static DEFINE_MUTEX(mutex_Y1); static DEFINE_MUTEX(mutex_Y2); static DEFINE_MUTEX(mutex_Z1); static DEFINE_MUTEX(mutex_Z2); static DECLARE_RWSEM(rwsem_X1); static DECLARE_RWSEM(rwsem_X2); static DECLARE_RWSEM(rwsem_Y1); static DECLARE_RWSEM(rwsem_Y2); static DECLARE_RWSEM(rwsem_Z1); static DECLARE_RWSEM(rwsem_Z2); #ifdef CONFIG_RT_MUTEXES static DEFINE_RT_MUTEX(rtmutex_X1); static DEFINE_RT_MUTEX(rtmutex_X2); static DEFINE_RT_MUTEX(rtmutex_Y1); static DEFINE_RT_MUTEX(rtmutex_Y2); static DEFINE_RT_MUTEX(rtmutex_Z1); static DEFINE_RT_MUTEX(rtmutex_Z2); #endif static DEFINE_PER_CPU(local_lock_t, local_A); /* * non-inlined runtime initializers, to let separate locks share * the same lock-class: */ #define INIT_CLASS_FUNC(class) \ static noinline void \ init_class_##class(spinlock_t *lock, rwlock_t *rwlock, \ struct mutex *mutex, struct rw_semaphore *rwsem)\ { \ spin_lock_init(lock); \ rwlock_init(rwlock); \ mutex_init(mutex); \ init_rwsem(rwsem); \ } INIT_CLASS_FUNC(X) INIT_CLASS_FUNC(Y) INIT_CLASS_FUNC(Z) static void init_shared_classes(void) { #ifdef CONFIG_RT_MUTEXES static struct lock_class_key rt_X, rt_Y, rt_Z; __rt_mutex_init(&rtmutex_X1, __func__, &rt_X); __rt_mutex_init(&rtmutex_X2, __func__, &rt_X); __rt_mutex_init(&rtmutex_Y1, __func__, &rt_Y); __rt_mutex_init(&rtmutex_Y2, __func__, &rt_Y); __rt_mutex_init(&rtmutex_Z1, __func__, &rt_Z); __rt_mutex_init(&rtmutex_Z2, __func__, &rt_Z); #endif init_class_X(&lock_X1, &rwlock_X1, &mutex_X1, &rwsem_X1); init_class_X(&lock_X2, &rwlock_X2, &mutex_X2, &rwsem_X2); init_class_Y(&lock_Y1, &rwlock_Y1, &mutex_Y1, &rwsem_Y1); init_class_Y(&lock_Y2, &rwlock_Y2, &mutex_Y2, &rwsem_Y2); init_class_Z(&lock_Z1, &rwlock_Z1, &mutex_Z1, &rwsem_Z1); init_class_Z(&lock_Z2, &rwlock_Z2, &mutex_Z2, &rwsem_Z2); } /* * For spinlocks and rwlocks we also do hardirq-safe / softirq-safe tests. * The following functions use a lock from a simulated hardirq/softirq * context, causing the locks to be marked as hardirq-safe/softirq-safe: */ #define HARDIRQ_DISABLE local_irq_disable #define HARDIRQ_ENABLE local_irq_enable #define HARDIRQ_ENTER() \ local_irq_disable(); \ __irq_enter(); \ lockdep_hardirq_threaded(); \ WARN_ON(!in_irq()); #define HARDIRQ_EXIT() \ __irq_exit(); \ local_irq_enable(); #define SOFTIRQ_DISABLE local_bh_disable #define SOFTIRQ_ENABLE local_bh_enable #define SOFTIRQ_ENTER() \ local_bh_disable(); \ local_irq_disable(); \ lockdep_softirq_enter(); \ WARN_ON(!in_softirq()); #define SOFTIRQ_EXIT() \ lockdep_softirq_exit(); \ local_irq_enable(); \ local_bh_enable(); /* * Shortcuts for lock/unlock API variants, to keep * the testcases compact: */ #define L(x) spin_lock(&lock_##x) #define U(x) spin_unlock(&lock_##x) #define LU(x) L(x); U(x) #define SI(x) spin_lock_init(&lock_##x) #define WL(x) write_lock(&rwlock_##x) #define WU(x) write_unlock(&rwlock_##x) #define WLU(x) WL(x); WU(x) #define RL(x) read_lock(&rwlock_##x) #define RU(x) read_unlock(&rwlock_##x) #define RLU(x) RL(x); RU(x) #define RWI(x) rwlock_init(&rwlock_##x) #define ML(x) mutex_lock(&mutex_##x) #define MU(x) mutex_unlock(&mutex_##x) #define MI(x) mutex_init(&mutex_##x) #define RTL(x) rt_mutex_lock(&rtmutex_##x) #define RTU(x) rt_mutex_unlock(&rtmutex_##x) #define RTI(x) rt_mutex_init(&rtmutex_##x) #define WSL(x) down_write(&rwsem_##x) #define WSU(x) up_write(&rwsem_##x) #define RSL(x) down_read(&rwsem_##x) #define RSU(x) up_read(&rwsem_##x) #define RWSI(x) init_rwsem(&rwsem_##x) #ifndef CONFIG_DEBUG_WW_MUTEX_SLOWPATH #define WWAI(x) ww_acquire_init(x, &ww_lockdep) #else #define WWAI(x) do { ww_acquire_init(x, &ww_lockdep); (x)->deadlock_inject_countdown = ~0U; } while (0) #endif #define WWAD(x) ww_acquire_done(x) #define WWAF(x) ww_acquire_fini(x) #define WWL(x, c) ww_mutex_lock(x, c) #define WWT(x) ww_mutex_trylock(x, NULL) #define WWL1(x) ww_mutex_lock(x, NULL) #define WWU(x) ww_mutex_unlock(x) #define LOCK_UNLOCK_2(x,y) LOCK(x); LOCK(y); UNLOCK(y); UNLOCK(x) /* * Generate different permutations of the same testcase, using * the same basic lock-dependency/state events: */ #define GENERATE_TESTCASE(name) \ \ static void name(void) { E(); } #define GENERATE_PERMUTATIONS_2_EVENTS(name) \ \ static void name##_12(void) { E1(); E2(); } \ static void name##_21(void) { E2(); E1(); } #define GENERATE_PERMUTATIONS_3_EVENTS(name) \ \ static void name##_123(void) { E1(); E2(); E3(); } \ static void name##_132(void) { E1(); E3(); E2(); } \ static void name##_213(void) { E2(); E1(); E3(); } \ static void name##_231(void) { E2(); E3(); E1(); } \ static void name##_312(void) { E3(); E1(); E2(); } \ static void name##_321(void) { E3(); E2(); E1(); } /* * AA deadlock: */ #define E() \ \ LOCK(X1); \ LOCK(X2); /* this one should fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(AA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(AA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(AA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(AA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(AA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(AA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(AA_rtmutex); #endif #undef E /* * Special-case for read-locking, they are * allowed to recurse on the same lock class: */ static void rlock_AA1(void) { RL(X1); RL(X1); // this one should NOT fail } static void rlock_AA1B(void) { RL(X1); RL(X2); // this one should NOT fail } static void rsem_AA1(void) { RSL(X1); RSL(X1); // this one should fail } static void rsem_AA1B(void) { RSL(X1); RSL(X2); // this one should fail } /* * The mixing of read and write locks is not allowed: */ static void rlock_AA2(void) { RL(X1); WL(X2); // this one should fail } static void rsem_AA2(void) { RSL(X1); WSL(X2); // this one should fail } static void rlock_AA3(void) { WL(X1); RL(X2); // this one should fail } static void rsem_AA3(void) { WSL(X1); RSL(X2); // this one should fail } /* * read_lock(A) * spin_lock(B) * spin_lock(B) * write_lock(A) */ static void rlock_ABBA1(void) { RL(X1); L(Y1); U(Y1); RU(X1); L(Y1); WL(X1); WU(X1); U(Y1); // should fail } static void rwsem_ABBA1(void) { RSL(X1); ML(Y1); MU(Y1); RSU(X1); ML(Y1); WSL(X1); WSU(X1); MU(Y1); // should fail } /* * read_lock(A) * spin_lock(B) * spin_lock(B) * write_lock(A) * * This test case is aimed at poking whether the chain cache prevents us from * detecting a read-lock/lock-write deadlock: if the chain cache doesn't differ * read/write locks, the following case may happen * * { read_lock(A)->lock(B) dependency exists } * * P0: * lock(B); * read_lock(A); * * { Not a deadlock, B -> A is added in the chain cache } * * P1: * lock(B); * write_lock(A); * * { B->A found in chain cache, not reported as a deadlock } * */ static void rlock_chaincache_ABBA1(void) { RL(X1); L(Y1); U(Y1); RU(X1); L(Y1); RL(X1); RU(X1); U(Y1); L(Y1); WL(X1); WU(X1); U(Y1); // should fail } /* * read_lock(A) * spin_lock(B) * spin_lock(B) * read_lock(A) */ static void rlock_ABBA2(void) { RL(X1); L(Y1); U(Y1); RU(X1); L(Y1); RL(X1); RU(X1); U(Y1); // should NOT fail } static void rwsem_ABBA2(void) { RSL(X1); ML(Y1); MU(Y1); RSU(X1); ML(Y1); RSL(X1); RSU(X1); MU(Y1); // should fail } /* * write_lock(A) * spin_lock(B) * spin_lock(B) * write_lock(A) */ static void rlock_ABBA3(void) { WL(X1); L(Y1); U(Y1); WU(X1); L(Y1); WL(X1); WU(X1); U(Y1); // should fail } static void rwsem_ABBA3(void) { WSL(X1); ML(Y1); MU(Y1); WSU(X1); ML(Y1); WSL(X1); WSU(X1); MU(Y1); // should fail } /* * ABBA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBA_rtmutex); #endif #undef E /* * AB BC CA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(C, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBCCA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBCCA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBCCA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBCCA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBCCA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBCCA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBCCA_rtmutex); #endif #undef E /* * AB CA BC deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, A); \ LOCK_UNLOCK_2(B, C); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCABC_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCABC_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCABC_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCABC_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCABC_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCABC_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCABC_rtmutex); #endif #undef E /* * AB BC CD DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABBCCDDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABBCCDDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABBCCDDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABBCCDDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABBCCDDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABBCCDDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABBCCDDA_rtmutex); #endif #undef E /* * AB CD BD DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(B, D); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCDBDDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCDBDDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCDBDDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCDBDDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCDBDDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCDBDDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCDBDDA_rtmutex); #endif #undef E /* * AB CD BC DA deadlock: */ #define E() \ \ LOCK_UNLOCK_2(A, B); \ LOCK_UNLOCK_2(C, D); \ LOCK_UNLOCK_2(B, C); \ LOCK_UNLOCK_2(D, A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(ABCDBCDA_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(ABCDBCDA_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(ABCDBCDA_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(ABCDBCDA_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(ABCDBCDA_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(ABCDBCDA_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(ABCDBCDA_rtmutex); #endif #undef E #ifdef CONFIG_PREEMPT_RT # define RT_PREPARE_DBL_UNLOCK() { migrate_disable(); rcu_read_lock(); } #else # define RT_PREPARE_DBL_UNLOCK() #endif /* * Double unlock: */ #define E() \ \ LOCK(A); \ RT_PREPARE_DBL_UNLOCK(); \ UNLOCK(A); \ UNLOCK(A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(double_unlock_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(double_unlock_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(double_unlock_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(double_unlock_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(double_unlock_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(double_unlock_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(double_unlock_rtmutex); #endif #undef E /* * initializing a held lock: */ #define E() \ \ LOCK(A); \ INIT(A); /* fail */ /* * 6 testcases: */ #include "locking-selftest-spin.h" GENERATE_TESTCASE(init_held_spin) #include "locking-selftest-wlock.h" GENERATE_TESTCASE(init_held_wlock) #include "locking-selftest-rlock.h" GENERATE_TESTCASE(init_held_rlock) #include "locking-selftest-mutex.h" GENERATE_TESTCASE(init_held_mutex) #include "locking-selftest-wsem.h" GENERATE_TESTCASE(init_held_wsem) #include "locking-selftest-rsem.h" GENERATE_TESTCASE(init_held_rsem) #ifdef CONFIG_RT_MUTEXES #include "locking-selftest-rtmutex.h" GENERATE_TESTCASE(init_held_rtmutex); #endif #undef E /* * locking an irq-safe lock with irqs enabled: */ #define E1() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); #define E2() \ \ LOCK(A); \ UNLOCK(A); /* * Generate 24 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_wlock) #endif #undef E1 #undef E2 #ifndef CONFIG_PREEMPT_RT /* * Enabling hardirqs with a softirq-safe lock held: */ #define E1() \ \ SOFTIRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ SOFTIRQ_EXIT(); #define E2() \ \ HARDIRQ_DISABLE(); \ LOCK(A); \ HARDIRQ_ENABLE(); \ UNLOCK(A); /* * Generate 12 testcases: */ #include "locking-selftest-spin.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_spin) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_wlock) #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_rlock) #undef E1 #undef E2 #endif /* * Enabling irqs with an irq-safe lock held: */ #define E1() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); #define E2() \ \ IRQ_DISABLE(); \ LOCK(A); \ IRQ_ENABLE(); \ UNLOCK(A); /* * Generate 24 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_wlock) #endif #undef E1 #undef E2 /* * Acquiring a irq-unsafe lock while holding an irq-safe-lock: */ #define E1() \ \ LOCK(A); \ LOCK(B); \ UNLOCK(B); \ UNLOCK(A); \ #define E2() \ \ LOCK(B); \ UNLOCK(B); #define E3() \ \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_wlock) #endif #undef E1 #undef E2 #undef E3 /* * If a lock turns into softirq-safe, but earlier it took * a softirq-unsafe lock: */ #define E1() \ IRQ_DISABLE(); \ LOCK(A); \ LOCK(B); \ UNLOCK(B); \ UNLOCK(A); \ IRQ_ENABLE(); #define E2() \ LOCK(B); \ UNLOCK(B); #define E3() \ IRQ_ENTER(); \ LOCK(A); \ UNLOCK(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_wlock) #endif #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock irq inversion. * * Deadlock scenario: * * CPU#1 is at #1, i.e. it has write-locked A, but has not * taken B yet. * * CPU#2 is at #2, i.e. it has locked B. * * Hardirq hits CPU#2 at point #2 and is trying to read-lock A. * * The deadlock occurs because CPU#1 will spin on B, and CPU#2 * will spin on A. */ #define E1() \ \ IRQ_DISABLE(); \ WL(A); \ LOCK(B); \ UNLOCK(B); \ WU(A); \ IRQ_ENABLE(); #define E2() \ \ LOCK(B); \ UNLOCK(B); #define E3() \ \ IRQ_ENTER(); \ RL(A); \ RU(A); \ IRQ_EXIT(); /* * Generate 36 testcases: */ #include "locking-selftest-spin-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_spin) #include "locking-selftest-rlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_rlock) #include "locking-selftest-wlock-hardirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-spin-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_spin) #include "locking-selftest-rlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_rlock) #include "locking-selftest-wlock-softirq.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_wlock) #endif #undef E1 #undef E2 #undef E3 /* * write-read / write-read / write-read deadlock even if read is recursive */ #define E1() \ \ WL(X1); \ RL(Y1); \ RU(Y1); \ WU(X1); #define E2() \ \ WL(Y1); \ RL(Z1); \ RU(Z1); \ WU(Y1); #define E3() \ \ WL(Z1); \ RL(X1); \ RU(X1); \ WU(Z1); #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(W1R2_W2R3_W3R1) #undef E1 #undef E2 #undef E3 /* * write-write / read-read / write-read deadlock even if read is recursive */ #define E1() \ \ WL(X1); \ WL(Y1); \ WU(Y1); \ WU(X1); #define E2() \ \ RL(Y1); \ RL(Z1); \ RU(Z1); \ RU(Y1); #define E3() \ \ WL(Z1); \ RL(X1); \ RU(X1); \ WU(Z1); #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(W1W2_R2R3_W3R1) #undef E1 #undef E2 #undef E3 /* * write-write / read-read / read-write is not deadlock when read is recursive */ #define E1() \ \ WL(X1); \ WL(Y1); \ WU(Y1); \ WU(X1); #define E2() \ \ RL(Y1); \ RL(Z1); \ RU(Z1); \ RU(Y1); #define E3() \ \ RL(Z1); \ WL(X1); \ WU(X1); \ RU(Z1); #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(W1R2_R2R3_W3W1) #undef E1 #undef E2 #undef E3 /* * write-read / read-read / write-write is not deadlock when read is recursive */ #define E1() \ \ WL(X1); \ RL(Y1); \ RU(Y1); \ WU(X1); #define E2() \ \ RL(Y1); \ RL(Z1); \ RU(Z1); \ RU(Y1); #define E3() \ \ WL(Z1); \ WL(X1); \ WU(X1); \ WU(Z1); #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(W1W2_R2R3_R3W1) #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock recursion that is actually safe. */ #define E1() \ \ IRQ_DISABLE(); \ WL(A); \ WU(A); \ IRQ_ENABLE(); #define E2() \ \ RL(A); \ RU(A); \ #define E3() \ \ IRQ_ENTER(); \ LOCK(A); \ L(B); \ U(B); \ UNLOCK(A); \ IRQ_EXIT(); /* * Generate 24 testcases: */ #include "locking-selftest-hardirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_hard_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-softirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_soft_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_soft_wlock) #endif #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock recursion that is unsafe. */ #define E1() \ \ IRQ_DISABLE(); \ L(B); \ LOCK(A); \ UNLOCK(A); \ U(B); \ IRQ_ENABLE(); #define E2() \ \ RL(A); \ RU(A); \ #define E3() \ \ IRQ_ENTER(); \ L(B); \ U(B); \ IRQ_EXIT(); /* * Generate 24 testcases: */ #include "locking-selftest-hardirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_hard_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-softirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_soft_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_soft_wlock) #endif #undef E1 #undef E2 #undef E3 /* * read-lock / write-lock recursion that is unsafe. * * A is a ENABLED_*_READ lock * B is a USED_IN_*_READ lock * * read_lock(A); * write_lock(B); * <interrupt> * read_lock(B); * write_lock(A); // if this one is read_lock(), no deadlock */ #define E1() \ \ IRQ_DISABLE(); \ WL(B); \ LOCK(A); \ UNLOCK(A); \ WU(B); \ IRQ_ENABLE(); #define E2() \ \ RL(A); \ RU(A); \ #define E3() \ \ IRQ_ENTER(); \ RL(B); \ RU(B); \ IRQ_EXIT(); /* * Generate 24 testcases: */ #include "locking-selftest-hardirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion3_hard_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion3_hard_wlock) #ifndef CONFIG_PREEMPT_RT #include "locking-selftest-softirq.h" #include "locking-selftest-rlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion3_soft_rlock) #include "locking-selftest-wlock.h" GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion3_soft_wlock) #endif #ifdef CONFIG_DEBUG_LOCK_ALLOC # define I_SPINLOCK(x) lockdep_reset_lock(&lock_##x.dep_map) # define I_RAW_SPINLOCK(x) lockdep_reset_lock(&raw_lock_##x.dep_map) # define I_RWLOCK(x) lockdep_reset_lock(&rwlock_##x.dep_map) # define I_MUTEX(x) lockdep_reset_lock(&mutex_##x.dep_map) # define I_RWSEM(x) lockdep_reset_lock(&rwsem_##x.dep_map) # define I_WW(x) lockdep_reset_lock(&x.dep_map) # define I_LOCAL_LOCK(x) lockdep_reset_lock(this_cpu_ptr(&local_##x.dep_map)) #ifdef CONFIG_RT_MUTEXES # define I_RTMUTEX(x) lockdep_reset_lock(&rtmutex_##x.dep_map) #endif #else # define I_SPINLOCK(x) # define I_RAW_SPINLOCK(x) # define I_RWLOCK(x) # define I_MUTEX(x) # define I_RWSEM(x) # define I_WW(x) # define I_LOCAL_LOCK(x) #endif #ifndef I_RTMUTEX # define I_RTMUTEX(x) #endif #ifdef CONFIG_RT_MUTEXES #define I2_RTMUTEX(x) rt_mutex_init(&rtmutex_##x) #else #define I2_RTMUTEX(x) #endif #define I1(x) \ do { \ I_SPINLOCK(x); \ I_RWLOCK(x); \ I_MUTEX(x); \ I_RWSEM(x); \ I_RTMUTEX(x); \ } while (0) #define I2(x) \ do { \ spin_lock_init(&lock_##x); \ rwlock_init(&rwlock_##x); \ mutex_init(&mutex_##x); \ init_rwsem(&rwsem_##x); \ I2_RTMUTEX(x); \ } while (0) static void reset_locks(void) { local_irq_disable(); lockdep_free_key_range(&ww_lockdep.acquire_key, 1); lockdep_free_key_range(&ww_lockdep.mutex_key, 1); I1(A); I1(B); I1(C); I1(D); I1(X1); I1(X2); I1(Y1); I1(Y2); I1(Z1); I1(Z2); I_WW(t); I_WW(t2); I_WW(o.base); I_WW(o2.base); I_WW(o3.base); I_RAW_SPINLOCK(A); I_RAW_SPINLOCK(B); I_LOCAL_LOCK(A); lockdep_reset(); I2(A); I2(B); I2(C); I2(D); init_shared_classes(); raw_spin_lock_init(&raw_lock_A); raw_spin_lock_init(&raw_lock_B); local_lock_init(this_cpu_ptr(&local_A)); ww_mutex_init(&o, &ww_lockdep); ww_mutex_init(&o2, &ww_lockdep); ww_mutex_init(&o3, &ww_lockdep); memset(&t, 0, sizeof(t)); memset(&t2, 0, sizeof(t2)); memset(&ww_lockdep.acquire_key, 0, sizeof(ww_lockdep.acquire_key)); memset(&ww_lockdep.mutex_key, 0, sizeof(ww_lockdep.mutex_key)); local_irq_enable(); } #undef I static int testcase_total; static int testcase_successes; static int expected_testcase_failures; static int unexpected_testcase_failures; static void dotest(void (*testcase_fn)(void), int expected, int lockclass_mask) { int saved_preempt_count = preempt_count(); #ifdef CONFIG_PREEMPT_RT #ifdef CONFIG_SMP int saved_mgd_count = current->migration_disabled; #endif int saved_rcu_count = current->rcu_read_lock_nesting; #endif WARN_ON(irqs_disabled()); debug_locks_silent = !(debug_locks_verbose & lockclass_mask); testcase_fn(); /* * Filter out expected failures: */ #ifndef CONFIG_PROVE_LOCKING if (expected == FAILURE && debug_locks) { expected_testcase_failures++; pr_cont("failed|"); } else #endif if (debug_locks != expected) { unexpected_testcase_failures++; pr_cont("FAILED|"); } else { testcase_successes++; pr_cont(" ok |"); } testcase_total++; if (debug_locks_verbose & lockclass_mask) pr_cont(" lockclass mask: %x, debug_locks: %d, expected: %d\n", lockclass_mask, debug_locks, expected); /* * Some tests (e.g. double-unlock) might corrupt the preemption * count, so restore it: */ preempt_count_set(saved_preempt_count); #ifdef CONFIG_PREEMPT_RT #ifdef CONFIG_SMP while (current->migration_disabled > saved_mgd_count) migrate_enable(); #endif while (current->rcu_read_lock_nesting > saved_rcu_count) rcu_read_unlock(); WARN_ON_ONCE(current->rcu_read_lock_nesting < saved_rcu_count); #endif #ifdef CONFIG_TRACE_IRQFLAGS if (softirq_count()) current->softirqs_enabled = 0; else current->softirqs_enabled = 1; #endif reset_locks(); } #ifdef CONFIG_RT_MUTEXES #define dotest_rt(fn, e, m) dotest((fn), (e), (m)) #else #define dotest_rt(fn, e, m) #endif static inline void print_testname(const char *testname) { printk("%33s:", testname); } #define DO_TESTCASE_1(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_1B(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_##nr, FAILURE, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_1RR(desc, name, nr) \ print_testname(desc"/"#nr); \ pr_cont(" |"); \ dotest(name##_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_1RRB(desc, name, nr) \ print_testname(desc"/"#nr); \ pr_cont(" |"); \ dotest(name##_##nr, FAILURE, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_3(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_3RW(desc, name, nr) \ print_testname(desc"/"#nr); \ dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN|LOCKTYPE_RWLOCK);\ dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_2RW(desc, name, nr) \ print_testname(desc"/"#nr); \ pr_cont(" |"); \ dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \ pr_cont("\n"); #define DO_TESTCASE_2x2RW(desc, name, nr) \ DO_TESTCASE_2RW("hard-"desc, name##_hard, nr) \ NON_RT(DO_TESTCASE_2RW("soft-"desc, name##_soft, nr)) \ #define DO_TESTCASE_6x2x2RW(desc, name) \ DO_TESTCASE_2x2RW(desc, name, 123); \ DO_TESTCASE_2x2RW(desc, name, 132); \ DO_TESTCASE_2x2RW(desc, name, 213); \ DO_TESTCASE_2x2RW(desc, name, 231); \ DO_TESTCASE_2x2RW(desc, name, 312); \ DO_TESTCASE_2x2RW(desc, name, 321); #define DO_TESTCASE_6(desc, name) \ print_testname(desc); \ dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \ dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \ dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, FAILURE, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); #define DO_TESTCASE_6_SUCCESS(desc, name) \ print_testname(desc); \ dotest(name##_spin, SUCCESS, LOCKTYPE_SPIN); \ dotest(name##_wlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, SUCCESS, LOCKTYPE_MUTEX); \ dotest(name##_wsem, SUCCESS, LOCKTYPE_RWSEM); \ dotest(name##_rsem, SUCCESS, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, SUCCESS, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); /* * 'read' variant: rlocks must not trigger. */ #define DO_TESTCASE_6R(desc, name) \ print_testname(desc); \ dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \ dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \ dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \ dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \ dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \ dotest_rt(name##_rtmutex, FAILURE, LOCKTYPE_RTMUTEX); \ pr_cont("\n"); #define DO_TESTCASE_2I(desc, name, nr) \ DO_TESTCASE_1("hard-"desc, name##_hard, nr); \ NON_RT(DO_TESTCASE_1("soft-"desc, name##_soft, nr)); #define DO_TESTCASE_2IB(desc, name, nr) \ DO_TESTCASE_1B("hard-"desc, name##_hard, nr); \ NON_RT(DO_TESTCASE_1B("soft-"desc, name##_soft, nr)); #define DO_TESTCASE_6I(desc, name, nr) \ DO_TESTCASE_3("hard-"desc, name##_hard, nr); \ NON_RT(DO_TESTCASE_3("soft-"desc, name##_soft, nr)); #define DO_TESTCASE_6IRW(desc, name, nr) \ DO_TESTCASE_3RW("hard-"desc, name##_hard, nr); \ NON_RT(DO_TESTCASE_3RW("soft-"desc, name##_soft, nr)); #define DO_TESTCASE_2x3(desc, name) \ DO_TESTCASE_3(desc, name, 12); \ DO_TESTCASE_3(desc, name, 21); #define DO_TESTCASE_2x6(desc, name) \ DO_TESTCASE_6I(desc, name, 12); \ DO_TESTCASE_6I(desc, name, 21); #define DO_TESTCASE_6x2(desc, name) \ DO_TESTCASE_2I(desc, name, 123); \ DO_TESTCASE_2I(desc, name, 132); \ DO_TESTCASE_2I(desc, name, 213); \ DO_TESTCASE_2I(desc, name, 231); \ DO_TESTCASE_2I(desc, name, 312); \ DO_TESTCASE_2I(desc, name, 321); #define DO_TESTCASE_6x2B(desc, name) \ DO_TESTCASE_2IB(desc, name, 123); \ DO_TESTCASE_2IB(desc, name, 132); \ DO_TESTCASE_2IB(desc, name, 213); \ DO_TESTCASE_2IB(desc, name, 231); \ DO_TESTCASE_2IB(desc, name, 312); \ DO_TESTCASE_2IB(desc, name, 321); #define DO_TESTCASE_6x1RR(desc, name) \ DO_TESTCASE_1RR(desc, name, 123); \ DO_TESTCASE_1RR(desc, name, 132); \ DO_TESTCASE_1RR(desc, name, 213); \ DO_TESTCASE_1RR(desc, name, 231); \ DO_TESTCASE_1RR(desc, name, 312); \ DO_TESTCASE_1RR(desc, name, 321); #define DO_TESTCASE_6x1RRB(desc, name) \ DO_TESTCASE_1RRB(desc, name, 123); \ DO_TESTCASE_1RRB(desc, name, 132); \ DO_TESTCASE_1RRB(desc, name, 213); \ DO_TESTCASE_1RRB(desc, name, 231); \ DO_TESTCASE_1RRB(desc, name, 312); \ DO_TESTCASE_1RRB(desc, name, 321); #define DO_TESTCASE_6x6(desc, name) \ DO_TESTCASE_6I(desc, name, 123); \ DO_TESTCASE_6I(desc, name, 132); \ DO_TESTCASE_6I(desc, name, 213); \ DO_TESTCASE_6I(desc, name, 231); \ DO_TESTCASE_6I(desc, name, 312); \ DO_TESTCASE_6I(desc, name, 321); #define DO_TESTCASE_6x6RW(desc, name) \ DO_TESTCASE_6IRW(desc, name, 123); \ DO_TESTCASE_6IRW(desc, name, 132); \ DO_TESTCASE_6IRW(desc, name, 213); \ DO_TESTCASE_6IRW(desc, name, 231); \ DO_TESTCASE_6IRW(desc, name, 312); \ DO_TESTCASE_6IRW(desc, name, 321); static void ww_test_fail_acquire(void) { int ret; WWAI(&t); t.stamp++; ret = WWL(&o, &t); if (WARN_ON(!o.ctx) || WARN_ON(ret)) return; /* No lockdep test, pure API */ ret = WWL(&o, &t); WARN_ON(ret != -EALREADY); ret = WWT(&o); WARN_ON(ret); t2 = t; t2.stamp++; ret = WWL(&o, &t2); WARN_ON(ret != -EDEADLK); WWU(&o); if (WWT(&o)) WWU(&o); #ifdef CONFIG_DEBUG_LOCK_ALLOC else DEBUG_LOCKS_WARN_ON(1); #endif } #ifdef CONFIG_PREEMPT_RT #define ww_mutex_base_lock(b) rt_mutex_lock(b) #define ww_mutex_base_trylock(b) rt_mutex_trylock(b) #define ww_mutex_base_lock_nest_lock(b, b2) rt_mutex_lock_nest_lock(b, b2) #define ww_mutex_base_lock_interruptible(b) rt_mutex_lock_interruptible(b) #define ww_mutex_base_lock_killable(b) rt_mutex_lock_killable(b) #define ww_mutex_base_unlock(b) rt_mutex_unlock(b) #else #define ww_mutex_base_lock(b) mutex_lock(b) #define ww_mutex_base_trylock(b) mutex_trylock(b) #define ww_mutex_base_lock_nest_lock(b, b2) mutex_lock_nest_lock(b, b2) #define ww_mutex_base_lock_interruptible(b) mutex_lock_interruptible(b) #define ww_mutex_base_lock_killable(b) mutex_lock_killable(b) #define ww_mutex_base_unlock(b) mutex_unlock(b) #endif static void ww_test_normal(void) { int ret; WWAI(&t); /* * None of the ww_mutex codepaths should be taken in the 'normal' * mutex calls. The easiest way to verify this is by using the * normal mutex calls, and making sure o.ctx is unmodified. */ /* mutex_lock (and indirectly, mutex_lock_nested) */ o.ctx = (void *)~0UL; ww_mutex_base_lock(&o.base); ww_mutex_base_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); /* mutex_lock_interruptible (and *_nested) */ o.ctx = (void *)~0UL; ret = ww_mutex_base_lock_interruptible(&o.base); if (!ret) ww_mutex_base_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* mutex_lock_killable (and *_nested) */ o.ctx = (void *)~0UL; ret = ww_mutex_base_lock_killable(&o.base); if (!ret) ww_mutex_base_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* trylock, succeeding */ o.ctx = (void *)~0UL; ret = ww_mutex_base_trylock(&o.base); WARN_ON(!ret); if (ret) ww_mutex_base_unlock(&o.base); else WARN_ON(1); WARN_ON(o.ctx != (void *)~0UL); /* trylock, failing */ o.ctx = (void *)~0UL; ww_mutex_base_lock(&o.base); ret = ww_mutex_base_trylock(&o.base); WARN_ON(ret); ww_mutex_base_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); /* nest_lock */ o.ctx = (void *)~0UL; ww_mutex_base_lock_nest_lock(&o.base, &t); ww_mutex_base_unlock(&o.base); WARN_ON(o.ctx != (void *)~0UL); } static void ww_test_two_contexts(void) { WWAI(&t); WWAI(&t2); } static void ww_test_diff_class(void) { WWAI(&t); #ifdef DEBUG_WW_MUTEXES t.ww_class = NULL; #endif WWL(&o, &t); } static void ww_test_context_done_twice(void) { WWAI(&t); WWAD(&t); WWAD(&t); WWAF(&t); } static void ww_test_context_unlock_twice(void) { WWAI(&t); WWAD(&t); WWAF(&t); WWAF(&t); } static void ww_test_context_fini_early(void) { WWAI(&t); WWL(&o, &t); WWAD(&t); WWAF(&t); } static void ww_test_context_lock_after_done(void) { WWAI(&t); WWAD(&t); WWL(&o, &t); } static void ww_test_object_unlock_twice(void) { WWL1(&o); WWU(&o); WWU(&o); } static void ww_test_object_lock_unbalanced(void) { WWAI(&t); WWL(&o, &t); t.acquired = 0; WWU(&o); WWAF(&t); } static void ww_test_object_lock_stale_context(void) { WWAI(&t); o.ctx = &t2; WWL(&o, &t); } static void ww_test_edeadlk_normal(void) { int ret; ww_mutex_base_lock(&o2.base); o2.ctx = &t2; mutex_release(&o2.base.dep_map, _THIS_IP_); WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); ww_mutex_base_unlock(&o2.base); WWU(&o); WWL(&o2, &t); } static void ww_test_edeadlk_normal_slow(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); ww_mutex_base_unlock(&o2.base); WWU(&o); ww_mutex_lock_slow(&o2, &t); } static void ww_test_edeadlk_no_unlock(void) { int ret; ww_mutex_base_lock(&o2.base); o2.ctx = &t2; mutex_release(&o2.base.dep_map, _THIS_IP_); WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); ww_mutex_base_unlock(&o2.base); WWL(&o2, &t); } static void ww_test_edeadlk_no_unlock_slow(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); o2.ctx = NULL; mutex_acquire(&o2.base.dep_map, 0, 1, _THIS_IP_); ww_mutex_base_unlock(&o2.base); ww_mutex_lock_slow(&o2, &t); } static void ww_test_edeadlk_acquire_more(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ret = WWL(&o3, &t); } static void ww_test_edeadlk_acquire_more_slow(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ww_mutex_lock_slow(&o3, &t); } static void ww_test_edeadlk_acquire_more_edeadlk(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; ww_mutex_base_lock(&o3.base); mutex_release(&o3.base.dep_map, _THIS_IP_); o3.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ret = WWL(&o3, &t); WARN_ON(ret != -EDEADLK); } static void ww_test_edeadlk_acquire_more_edeadlk_slow(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; ww_mutex_base_lock(&o3.base); mutex_release(&o3.base.dep_map, _THIS_IP_); o3.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); ww_mutex_lock_slow(&o3, &t); } static void ww_test_edeadlk_acquire_wrong(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); if (!ret) WWU(&o2); WWU(&o); ret = WWL(&o3, &t); } static void ww_test_edeadlk_acquire_wrong_slow(void) { int ret; ww_mutex_base_lock(&o2.base); mutex_release(&o2.base.dep_map, _THIS_IP_); o2.ctx = &t2; WWAI(&t); t2 = t; t2.stamp--; ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret != -EDEADLK); if (!ret) WWU(&o2); WWU(&o); ww_mutex_lock_slow(&o3, &t); } static void ww_test_spin_nest_unlocked(void) { spin_lock_nest_lock(&lock_A, &o.base); U(A); } /* This is not a deadlock, because we have X1 to serialize Y1 and Y2 */ static void ww_test_spin_nest_lock(void) { spin_lock(&lock_X1); spin_lock_nest_lock(&lock_Y1, &lock_X1); spin_lock(&lock_A); spin_lock_nest_lock(&lock_Y2, &lock_X1); spin_unlock(&lock_A); spin_unlock(&lock_Y2); spin_unlock(&lock_Y1); spin_unlock(&lock_X1); } static void ww_test_unneeded_slow(void) { WWAI(&t); ww_mutex_lock_slow(&o, &t); } static void ww_test_context_block(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); WWL1(&o2); } static void ww_test_context_try(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); ret = WWT(&o2); WARN_ON(!ret); WWU(&o2); WWU(&o); } static void ww_test_context_context(void) { int ret; WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); ret = WWL(&o2, &t); WARN_ON(ret); WWU(&o2); WWU(&o); } static void ww_test_try_block(void) { bool ret; ret = WWT(&o); WARN_ON(!ret); WWL1(&o2); WWU(&o2); WWU(&o); } static void ww_test_try_try(void) { bool ret; ret = WWT(&o); WARN_ON(!ret); ret = WWT(&o2); WARN_ON(!ret); WWU(&o2); WWU(&o); } static void ww_test_try_context(void) { int ret; ret = WWT(&o); WARN_ON(!ret); WWAI(&t); ret = WWL(&o2, &t); WARN_ON(ret); } static void ww_test_block_block(void) { WWL1(&o); WWL1(&o2); } static void ww_test_block_try(void) { bool ret; WWL1(&o); ret = WWT(&o2); WARN_ON(!ret); } static void ww_test_block_context(void) { int ret; WWL1(&o); WWAI(&t); ret = WWL(&o2, &t); WARN_ON(ret); } static void ww_test_spin_block(void) { L(A); U(A); WWL1(&o); L(A); U(A); WWU(&o); L(A); WWL1(&o); WWU(&o); U(A); } static void ww_test_spin_try(void) { bool ret; L(A); U(A); ret = WWT(&o); WARN_ON(!ret); L(A); U(A); WWU(&o); L(A); ret = WWT(&o); WARN_ON(!ret); WWU(&o); U(A); } static void ww_test_spin_context(void) { int ret; L(A); U(A); WWAI(&t); ret = WWL(&o, &t); WARN_ON(ret); L(A); U(A); WWU(&o); L(A); ret = WWL(&o, &t); WARN_ON(ret); WWU(&o); U(A); } static void ww_tests(void) { printk(" --------------------------------------------------------------------------\n"); printk(" | Wound/wait tests |\n"); printk(" ---------------------\n"); print_testname("ww api failures"); dotest(ww_test_fail_acquire, SUCCESS, LOCKTYPE_WW); dotest(ww_test_normal, SUCCESS, LOCKTYPE_WW); dotest(ww_test_unneeded_slow, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("ww contexts mixing"); dotest(ww_test_two_contexts, FAILURE, LOCKTYPE_WW); dotest(ww_test_diff_class, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("finishing ww context"); dotest(ww_test_context_done_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_unlock_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_fini_early, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_lock_after_done, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("locking mismatches"); dotest(ww_test_object_unlock_twice, FAILURE, LOCKTYPE_WW); dotest(ww_test_object_lock_unbalanced, FAILURE, LOCKTYPE_WW); dotest(ww_test_object_lock_stale_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("EDEADLK handling"); dotest(ww_test_edeadlk_normal, SUCCESS, LOCKTYPE_WW); dotest(ww_test_edeadlk_normal_slow, SUCCESS, LOCKTYPE_WW); dotest(ww_test_edeadlk_no_unlock, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_no_unlock_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_edeadlk, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_more_edeadlk_slow, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_wrong, FAILURE, LOCKTYPE_WW); dotest(ww_test_edeadlk_acquire_wrong_slow, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("spinlock nest unlocked"); dotest(ww_test_spin_nest_unlocked, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("spinlock nest test"); dotest(ww_test_spin_nest_lock, SUCCESS, LOCKTYPE_WW); pr_cont("\n"); printk(" -----------------------------------------------------\n"); printk(" |block | try |context|\n"); printk(" -----------------------------------------------------\n"); print_testname("context"); dotest(ww_test_context_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_context_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_context_context, SUCCESS, LOCKTYPE_WW); pr_cont("\n"); print_testname("try"); dotest(ww_test_try_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_try_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_try_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("block"); dotest(ww_test_block_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_block_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_block_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); print_testname("spinlock"); dotest(ww_test_spin_block, FAILURE, LOCKTYPE_WW); dotest(ww_test_spin_try, SUCCESS, LOCKTYPE_WW); dotest(ww_test_spin_context, FAILURE, LOCKTYPE_WW); pr_cont("\n"); } /* * <in hardirq handler> * read_lock(&A); * <hardirq disable> * spin_lock(&B); * spin_lock(&B); * read_lock(&A); * * is a deadlock. */ static void queued_read_lock_hardirq_RE_Er(void) { HARDIRQ_ENTER(); read_lock(&rwlock_A); LOCK(B); UNLOCK(B); read_unlock(&rwlock_A); HARDIRQ_EXIT(); HARDIRQ_DISABLE(); LOCK(B); read_lock(&rwlock_A); read_unlock(&rwlock_A); UNLOCK(B); HARDIRQ_ENABLE(); } /* * <in hardirq handler> * spin_lock(&B); * <hardirq disable> * read_lock(&A); * read_lock(&A); * spin_lock(&B); * * is not a deadlock. */ static void queued_read_lock_hardirq_ER_rE(void) { HARDIRQ_ENTER(); LOCK(B); read_lock(&rwlock_A); read_unlock(&rwlock_A); UNLOCK(B); HARDIRQ_EXIT(); HARDIRQ_DISABLE(); read_lock(&rwlock_A); LOCK(B); UNLOCK(B); read_unlock(&rwlock_A); HARDIRQ_ENABLE(); } /* * <hardirq disable> * spin_lock(&B); * read_lock(&A); * <in hardirq handler> * spin_lock(&B); * read_lock(&A); * * is a deadlock. Because the two read_lock()s are both non-recursive readers. */ static void queued_read_lock_hardirq_inversion(void) { HARDIRQ_ENTER(); LOCK(B); UNLOCK(B); HARDIRQ_EXIT(); HARDIRQ_DISABLE(); LOCK(B); read_lock(&rwlock_A); read_unlock(&rwlock_A); UNLOCK(B); HARDIRQ_ENABLE(); read_lock(&rwlock_A); read_unlock(&rwlock_A); } static void queued_read_lock_tests(void) { printk(" --------------------------------------------------------------------------\n"); printk(" | queued read lock tests |\n"); printk(" ---------------------------\n"); print_testname("hardirq read-lock/lock-read"); dotest(queued_read_lock_hardirq_RE_Er, FAILURE, LOCKTYPE_RWLOCK); pr_cont("\n"); print_testname("hardirq lock-read/read-lock"); dotest(queued_read_lock_hardirq_ER_rE, SUCCESS, LOCKTYPE_RWLOCK); pr_cont("\n"); print_testname("hardirq inversion"); dotest(queued_read_lock_hardirq_inversion, FAILURE, LOCKTYPE_RWLOCK); pr_cont("\n"); } static void fs_reclaim_correct_nesting(void) { fs_reclaim_acquire(GFP_KERNEL); might_alloc(GFP_NOFS); fs_reclaim_release(GFP_KERNEL); } static void fs_reclaim_wrong_nesting(void) { fs_reclaim_acquire(GFP_KERNEL); might_alloc(GFP_KERNEL); fs_reclaim_release(GFP_KERNEL); } static void fs_reclaim_protected_nesting(void) { unsigned int flags; fs_reclaim_acquire(GFP_KERNEL); flags = memalloc_nofs_save(); might_alloc(GFP_KERNEL); memalloc_nofs_restore(flags); fs_reclaim_release(GFP_KERNEL); } static void fs_reclaim_tests(void) { printk(" --------------------\n"); printk(" | fs_reclaim tests |\n"); printk(" --------------------\n"); print_testname("correct nesting"); dotest(fs_reclaim_correct_nesting, SUCCESS, 0); pr_cont("\n"); print_testname("wrong nesting"); dotest(fs_reclaim_wrong_nesting, FAILURE, 0); pr_cont("\n"); print_testname("protected nesting"); dotest(fs_reclaim_protected_nesting, SUCCESS, 0); pr_cont("\n"); } /* Defines guard classes to create contexts */ DEFINE_LOCK_GUARD_0(HARDIRQ, HARDIRQ_ENTER(), HARDIRQ_EXIT()) DEFINE_LOCK_GUARD_0(NOTTHREADED_HARDIRQ, do { local_irq_disable(); __irq_enter(); WARN_ON(!in_irq()); } while(0), HARDIRQ_EXIT()) DEFINE_LOCK_GUARD_0(SOFTIRQ, SOFTIRQ_ENTER(), SOFTIRQ_EXIT()) /* Define RCU guards, should go away when RCU has its own guard definitions */ DEFINE_LOCK_GUARD_0(RCU, rcu_read_lock(), rcu_read_unlock()) DEFINE_LOCK_GUARD_0(RCU_BH, rcu_read_lock_bh(), rcu_read_unlock_bh()) DEFINE_LOCK_GUARD_0(RCU_SCHED, rcu_read_lock_sched(), rcu_read_unlock_sched()) #define GENERATE_2_CONTEXT_TESTCASE(outer, outer_lock, inner, inner_lock) \ \ static void __maybe_unused inner##_in_##outer(void) \ { \ /* Relies the reversed clean-up ordering: inner first */ \ guard(outer)(outer_lock); \ guard(inner)(inner_lock); \ } /* * wait contexts (considering PREEMPT_RT) * * o: inner is allowed in outer * x: inner is disallowed in outer * * \ inner | RCU | RAW_SPIN | SPIN | MUTEX * outer \ | | | | * ---------------+-------+----------+------+------- * HARDIRQ | o | o | o | x * ---------------+-------+----------+------+------- * NOTTHREADED_IRQ| o | o | x | x * ---------------+-------+----------+------+------- * SOFTIRQ | o | o | o | x * ---------------+-------+----------+------+------- * RCU | o | o | o | x * ---------------+-------+----------+------+------- * RCU_BH | o | o | o | x * ---------------+-------+----------+------+------- * RCU_SCHED | o | o | x | x * ---------------+-------+----------+------+------- * RAW_SPIN | o | o | x | x * ---------------+-------+----------+------+------- * SPIN | o | o | o | x * ---------------+-------+----------+------+------- * MUTEX | o | o | o | o * ---------------+-------+----------+------+------- */ #define GENERATE_2_CONTEXT_TESTCASE_FOR_ALL_OUTER(inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(HARDIRQ, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(NOTTHREADED_HARDIRQ, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(SOFTIRQ, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(RCU, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(RCU_BH, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(RCU_SCHED, , inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(raw_spinlock, &raw_lock_A, inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(spinlock, &lock_A, inner, inner_lock) \ GENERATE_2_CONTEXT_TESTCASE(mutex, &mutex_A, inner, inner_lock) GENERATE_2_CONTEXT_TESTCASE_FOR_ALL_OUTER(RCU, ) GENERATE_2_CONTEXT_TESTCASE_FOR_ALL_OUTER(raw_spinlock, &raw_lock_B) GENERATE_2_CONTEXT_TESTCASE_FOR_ALL_OUTER(spinlock, &lock_B) GENERATE_2_CONTEXT_TESTCASE_FOR_ALL_OUTER(mutex, &mutex_B) /* the outer context allows all kinds of preemption */ #define DO_CONTEXT_TESTCASE_OUTER_PREEMPTIBLE(outer) \ dotest(RCU_in_##outer, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(raw_spinlock_in_##outer, SUCCESS, LOCKTYPE_SPIN); \ dotest(spinlock_in_##outer, SUCCESS, LOCKTYPE_SPIN); \ dotest(mutex_in_##outer, SUCCESS, LOCKTYPE_MUTEX); \ /* * the outer context only allows the preemption introduced by spinlock_t (which * is a sleepable lock for PREEMPT_RT) */ #define DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(outer) \ dotest(RCU_in_##outer, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(raw_spinlock_in_##outer, SUCCESS, LOCKTYPE_SPIN); \ dotest(spinlock_in_##outer, SUCCESS, LOCKTYPE_SPIN); \ dotest(mutex_in_##outer, FAILURE, LOCKTYPE_MUTEX); \ /* the outer doesn't allows any kind of preemption */ #define DO_CONTEXT_TESTCASE_OUTER_NOT_PREEMPTIBLE(outer) \ dotest(RCU_in_##outer, SUCCESS, LOCKTYPE_RWLOCK); \ dotest(raw_spinlock_in_##outer, SUCCESS, LOCKTYPE_SPIN); \ dotest(spinlock_in_##outer, FAILURE, LOCKTYPE_SPIN); \ dotest(mutex_in_##outer, FAILURE, LOCKTYPE_MUTEX); \ static void wait_context_tests(void) { printk(" --------------------------------------------------------------------------\n"); printk(" | wait context tests |\n"); printk(" --------------------------------------------------------------------------\n"); printk(" | rcu | raw | spin |mutex |\n"); printk(" --------------------------------------------------------------------------\n"); print_testname("in hardirq context"); DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(HARDIRQ); pr_cont("\n"); print_testname("in hardirq context (not threaded)"); DO_CONTEXT_TESTCASE_OUTER_NOT_PREEMPTIBLE(NOTTHREADED_HARDIRQ); pr_cont("\n"); print_testname("in softirq context"); DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(SOFTIRQ); pr_cont("\n"); print_testname("in RCU context"); DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(RCU); pr_cont("\n"); print_testname("in RCU-bh context"); DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(RCU_BH); pr_cont("\n"); print_testname("in RCU-sched context"); DO_CONTEXT_TESTCASE_OUTER_NOT_PREEMPTIBLE(RCU_SCHED); pr_cont("\n"); print_testname("in RAW_SPINLOCK context"); DO_CONTEXT_TESTCASE_OUTER_NOT_PREEMPTIBLE(raw_spinlock); pr_cont("\n"); print_testname("in SPINLOCK context"); DO_CONTEXT_TESTCASE_OUTER_LIMITED_PREEMPTIBLE(spinlock); pr_cont("\n"); print_testname("in MUTEX context"); DO_CONTEXT_TESTCASE_OUTER_PREEMPTIBLE(mutex); pr_cont("\n"); } static void local_lock_2(void) { local_lock(&local_A); /* IRQ-ON */ local_unlock(&local_A); HARDIRQ_ENTER(); spin_lock(&lock_A); /* IN-IRQ */ spin_unlock(&lock_A); HARDIRQ_EXIT() HARDIRQ_DISABLE(); spin_lock(&lock_A); local_lock(&local_A); /* IN-IRQ <-> IRQ-ON cycle, false */ local_unlock(&local_A); spin_unlock(&lock_A); HARDIRQ_ENABLE(); } static void local_lock_3A(void) { local_lock(&local_A); /* IRQ-ON */ spin_lock(&lock_B); /* IRQ-ON */ spin_unlock(&lock_B); local_unlock(&local_A); HARDIRQ_ENTER(); spin_lock(&lock_A); /* IN-IRQ */ spin_unlock(&lock_A); HARDIRQ_EXIT() HARDIRQ_DISABLE(); spin_lock(&lock_A); local_lock(&local_A); /* IN-IRQ <-> IRQ-ON cycle only if we count local_lock(), false */ local_unlock(&local_A); spin_unlock(&lock_A); HARDIRQ_ENABLE(); } static void local_lock_3B(void) { local_lock(&local_A); /* IRQ-ON */ spin_lock(&lock_B); /* IRQ-ON */ spin_unlock(&lock_B); local_unlock(&local_A); HARDIRQ_ENTER(); spin_lock(&lock_A); /* IN-IRQ */ spin_unlock(&lock_A); HARDIRQ_EXIT() HARDIRQ_DISABLE(); spin_lock(&lock_A); local_lock(&local_A); /* IN-IRQ <-> IRQ-ON cycle only if we count local_lock(), false */ local_unlock(&local_A); spin_unlock(&lock_A); HARDIRQ_ENABLE(); HARDIRQ_DISABLE(); spin_lock(&lock_A); spin_lock(&lock_B); /* IN-IRQ <-> IRQ-ON cycle, true */ spin_unlock(&lock_B); spin_unlock(&lock_A); HARDIRQ_DISABLE(); } static void local_lock_tests(void) { printk(" --------------------------------------------------------------------------\n"); printk(" | local_lock tests |\n"); printk(" ---------------------\n"); print_testname("local_lock inversion 2"); dotest(local_lock_2, SUCCESS, LOCKTYPE_LL); pr_cont("\n"); print_testname("local_lock inversion 3A"); dotest(local_lock_3A, SUCCESS, LOCKTYPE_LL); pr_cont("\n"); print_testname("local_lock inversion 3B"); dotest(local_lock_3B, FAILURE, LOCKTYPE_LL); pr_cont("\n"); } static void hardirq_deadlock_softirq_not_deadlock(void) { /* mutex_A is hardirq-unsafe and softirq-unsafe */ /* mutex_A -> lock_C */ mutex_lock(&mutex_A); HARDIRQ_DISABLE(); spin_lock(&lock_C); spin_unlock(&lock_C); HARDIRQ_ENABLE(); mutex_unlock(&mutex_A); /* lock_A is hardirq-safe */ HARDIRQ_ENTER(); spin_lock(&lock_A); spin_unlock(&lock_A); HARDIRQ_EXIT(); /* lock_A -> lock_B */ HARDIRQ_DISABLE(); spin_lock(&lock_A); spin_lock(&lock_B); spin_unlock(&lock_B); spin_unlock(&lock_A); HARDIRQ_ENABLE(); /* lock_B -> lock_C */ HARDIRQ_DISABLE(); spin_lock(&lock_B); spin_lock(&lock_C); spin_unlock(&lock_C); spin_unlock(&lock_B); HARDIRQ_ENABLE(); /* lock_D is softirq-safe */ SOFTIRQ_ENTER(); spin_lock(&lock_D); spin_unlock(&lock_D); SOFTIRQ_EXIT(); /* And lock_D is hardirq-unsafe */ SOFTIRQ_DISABLE(); spin_lock(&lock_D); spin_unlock(&lock_D); SOFTIRQ_ENABLE(); /* * mutex_A -> lock_C -> lock_D is softirq-unsafe -> softirq-safe, not * deadlock. * * lock_A -> lock_B -> lock_C -> lock_D is hardirq-safe -> * hardirq-unsafe, deadlock. */ HARDIRQ_DISABLE(); spin_lock(&lock_C); spin_lock(&lock_D); spin_unlock(&lock_D); spin_unlock(&lock_C); HARDIRQ_ENABLE(); } void locking_selftest(void) { /* * Got a locking failure before the selftest ran? */ if (!debug_locks) { printk("----------------------------------\n"); printk("| Locking API testsuite disabled |\n"); printk("----------------------------------\n"); return; } /* * treats read_lock() as recursive read locks for testing purpose */ force_read_lock_recursive = 1; /* * Run the testsuite: */ printk("------------------------\n"); printk("| Locking API testsuite:\n"); printk("----------------------------------------------------------------------------\n"); printk(" | spin |wlock |rlock |mutex | wsem | rsem |rtmutex\n"); printk(" --------------------------------------------------------------------------\n"); init_shared_classes(); lockdep_set_selftest_task(current); DO_TESTCASE_6R("A-A deadlock", AA); DO_TESTCASE_6R("A-B-B-A deadlock", ABBA); DO_TESTCASE_6R("A-B-B-C-C-A deadlock", ABBCCA); DO_TESTCASE_6R("A-B-C-A-B-C deadlock", ABCABC); DO_TESTCASE_6R("A-B-B-C-C-D-D-A deadlock", ABBCCDDA); DO_TESTCASE_6R("A-B-C-D-B-D-D-A deadlock", ABCDBDDA); DO_TESTCASE_6R("A-B-C-D-B-C-D-A deadlock", ABCDBCDA); DO_TESTCASE_6("double unlock", double_unlock); DO_TESTCASE_6("initialize held", init_held); printk(" --------------------------------------------------------------------------\n"); print_testname("recursive read-lock"); pr_cont(" |"); dotest(rlock_AA1, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA1, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("recursive read-lock #2"); pr_cont(" |"); dotest(rlock_AA1B, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA1B, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed read-write-lock"); pr_cont(" |"); dotest(rlock_AA2, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA2, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed write-read-lock"); pr_cont(" |"); dotest(rlock_AA3, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rsem_AA3, FAILURE, LOCKTYPE_RWSEM); pr_cont("\n"); print_testname("mixed read-lock/lock-write ABBA"); pr_cont(" |"); dotest(rlock_ABBA1, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rwsem_ABBA1, FAILURE, LOCKTYPE_RWSEM); print_testname("mixed read-lock/lock-read ABBA"); pr_cont(" |"); dotest(rlock_ABBA2, SUCCESS, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rwsem_ABBA2, FAILURE, LOCKTYPE_RWSEM); print_testname("mixed write-lock/lock-write ABBA"); pr_cont(" |"); dotest(rlock_ABBA3, FAILURE, LOCKTYPE_RWLOCK); pr_cont(" |"); dotest(rwsem_ABBA3, FAILURE, LOCKTYPE_RWSEM); print_testname("chain cached mixed R-L/L-W ABBA"); pr_cont(" |"); dotest(rlock_chaincache_ABBA1, FAILURE, LOCKTYPE_RWLOCK); DO_TESTCASE_6x1RRB("rlock W1R2/W2R3/W3R1", W1R2_W2R3_W3R1); DO_TESTCASE_6x1RRB("rlock W1W2/R2R3/W3R1", W1W2_R2R3_W3R1); DO_TESTCASE_6x1RR("rlock W1W2/R2R3/R3W1", W1W2_R2R3_R3W1); DO_TESTCASE_6x1RR("rlock W1R2/R2R3/W3W1", W1R2_R2R3_W3W1); printk(" --------------------------------------------------------------------------\n"); /* * irq-context testcases: */ DO_TESTCASE_2x6("irqs-on + irq-safe-A", irqsafe1); NON_RT(DO_TESTCASE_2x3("sirq-safe-A => hirqs-on", irqsafe2A)); DO_TESTCASE_2x6("safe-A + irqs-on", irqsafe2B); DO_TESTCASE_6x6("safe-A + unsafe-B #1", irqsafe3); DO_TESTCASE_6x6("safe-A + unsafe-B #2", irqsafe4); DO_TESTCASE_6x6RW("irq lock-inversion", irq_inversion); DO_TESTCASE_6x2x2RW("irq read-recursion", irq_read_recursion); DO_TESTCASE_6x2x2RW("irq read-recursion #2", irq_read_recursion2); DO_TESTCASE_6x2x2RW("irq read-recursion #3", irq_read_recursion3); ww_tests(); force_read_lock_recursive = 0; /* * queued_read_lock() specific test cases can be put here */ if (IS_ENABLED(CONFIG_QUEUED_RWLOCKS)) queued_read_lock_tests(); fs_reclaim_tests(); /* Wait context test cases that are specific for RAW_LOCK_NESTING */ if (IS_ENABLED(CONFIG_PROVE_RAW_LOCK_NESTING)) wait_context_tests(); local_lock_tests(); print_testname("hardirq_unsafe_softirq_safe"); dotest(hardirq_deadlock_softirq_not_deadlock, FAILURE, LOCKTYPE_SPECIAL); pr_cont("\n"); if (unexpected_testcase_failures) { printk("-----------------------------------------------------------------\n"); debug_locks = 0; printk("BUG: %3d unexpected failures (out of %3d) - debugging disabled! |\n", unexpected_testcase_failures, testcase_total); printk("-----------------------------------------------------------------\n"); } else if (expected_testcase_failures && testcase_successes) { printk("--------------------------------------------------------\n"); printk("%3d out of %3d testcases failed, as expected. |\n", expected_testcase_failures, testcase_total); printk("----------------------------------------------------\n"); debug_locks = 1; } else if (expected_testcase_failures && !testcase_successes) { printk("--------------------------------------------------------\n"); printk("All %3d testcases failed, as expected. |\n", expected_testcase_failures); printk("----------------------------------------\n"); debug_locks = 1; } else { printk("-------------------------------------------------------\n"); printk("Good, all %3d testcases passed! |\n", testcase_successes); printk("---------------------------------\n"); debug_locks = 1; } lockdep_set_selftest_task(NULL); debug_locks_silent = 0; }
linux-master
lib/locking-selftest.c
// SPDX-License-Identifier: GPL-2.0-or-later /* ASN.1 Object identifier (OID) registry * * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. * Written by David Howells ([email protected]) */ #include <linux/module.h> #include <linux/export.h> #include <linux/oid_registry.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/bug.h> #include <linux/asn1.h> #include "oid_registry_data.c" MODULE_DESCRIPTION("OID Registry"); MODULE_AUTHOR("Red Hat, Inc."); MODULE_LICENSE("GPL"); /** * look_up_OID - Find an OID registration for the specified data * @data: Binary representation of the OID * @datasize: Size of the binary representation */ enum OID look_up_OID(const void *data, size_t datasize) { const unsigned char *octets = data; enum OID oid; unsigned char xhash; unsigned i, j, k, hash; size_t len; /* Hash the OID data */ hash = datasize - 1; for (i = 0; i < datasize; i++) hash += octets[i] * 33; hash = (hash >> 24) ^ (hash >> 16) ^ (hash >> 8) ^ hash; hash &= 0xff; /* Binary search the OID registry. OIDs are stored in ascending order * of hash value then ascending order of size and then in ascending * order of reverse value. */ i = 0; k = OID__NR; while (i < k) { j = (i + k) / 2; xhash = oid_search_table[j].hash; if (xhash > hash) { k = j; continue; } if (xhash < hash) { i = j + 1; continue; } oid = oid_search_table[j].oid; len = oid_index[oid + 1] - oid_index[oid]; if (len > datasize) { k = j; continue; } if (len < datasize) { i = j + 1; continue; } /* Variation is most likely to be at the tail end of the * OID, so do the comparison in reverse. */ while (len > 0) { unsigned char a = oid_data[oid_index[oid] + --len]; unsigned char b = octets[len]; if (a > b) { k = j; goto next; } if (a < b) { i = j + 1; goto next; } } return oid; next: ; } return OID__NR; } EXPORT_SYMBOL_GPL(look_up_OID); /** * parse_OID - Parse an OID from a bytestream * @data: Binary representation of the header + OID * @datasize: Size of the binary representation * @oid: Pointer to oid to return result * * Parse an OID from a bytestream that holds the OID in the format * ASN1_OID | length | oid. The length indicator must equal to datasize - 2. * -EBADMSG is returned if the bytestream is too short. */ int parse_OID(const void *data, size_t datasize, enum OID *oid) { const unsigned char *v = data; /* we need 2 bytes of header and at least 1 byte for oid */ if (datasize < 3 || v[0] != ASN1_OID || v[1] != datasize - 2) return -EBADMSG; *oid = look_up_OID(data + 2, datasize - 2); return 0; } EXPORT_SYMBOL_GPL(parse_OID); /* * sprint_OID - Print an Object Identifier into a buffer * @data: The encoded OID to print * @datasize: The size of the encoded OID * @buffer: The buffer to render into * @bufsize: The size of the buffer * * The OID is rendered into the buffer in "a.b.c.d" format and the number of * bytes is returned. -EBADMSG is returned if the data could not be interpreted * and -ENOBUFS if the buffer was too small. */ int sprint_oid(const void *data, size_t datasize, char *buffer, size_t bufsize) { const unsigned char *v = data, *end = v + datasize; unsigned long num; unsigned char n; size_t ret; int count; if (v >= end) goto bad; n = *v++; ret = count = snprintf(buffer, bufsize, "%u.%u", n / 40, n % 40); if (count >= bufsize) return -ENOBUFS; buffer += count; bufsize -= count; while (v < end) { n = *v++; if (!(n & 0x80)) { num = n; } else { num = n & 0x7f; do { if (v >= end) goto bad; n = *v++; num <<= 7; num |= n & 0x7f; } while (n & 0x80); } ret += count = snprintf(buffer, bufsize, ".%lu", num); if (count >= bufsize) return -ENOBUFS; buffer += count; bufsize -= count; } return ret; bad: snprintf(buffer, bufsize, "(bad)"); return -EBADMSG; } EXPORT_SYMBOL_GPL(sprint_oid); /** * sprint_OID - Print an Object Identifier into a buffer * @oid: The OID to print * @buffer: The buffer to render into * @bufsize: The size of the buffer * * The OID is rendered into the buffer in "a.b.c.d" format and the number of * bytes is returned. */ int sprint_OID(enum OID oid, char *buffer, size_t bufsize) { int ret; BUG_ON(oid >= OID__NR); ret = sprint_oid(oid_data + oid_index[oid], oid_index[oid + 1] - oid_index[oid], buffer, bufsize); BUG_ON(ret == -EBADMSG); return ret; } EXPORT_SYMBOL_GPL(sprint_OID);
linux-master
lib/oid_registry.c
// SPDX-License-Identifier: GPL-2.0-only /* * lib/btree.c - Simple In-memory B+Tree * * Copyright (c) 2007-2008 Joern Engel <[email protected]> * Bits and pieces stolen from Peter Zijlstra's code, which is * Copyright 2007, Red Hat Inc. Peter Zijlstra * * see http://programming.kicks-ass.net/kernel-patches/vma_lookup/btree.patch * * A relatively simple B+Tree implementation. I have written it as a learning * exercise to understand how B+Trees work. Turned out to be useful as well. * * B+Trees can be used similar to Linux radix trees (which don't have anything * in common with textbook radix trees, beware). Prerequisite for them working * well is that access to a random tree node is much faster than a large number * of operations within each node. * * Disks have fulfilled the prerequisite for a long time. More recently DRAM * has gained similar properties, as memory access times, when measured in cpu * cycles, have increased. Cacheline sizes have increased as well, which also * helps B+Trees. * * Compared to radix trees, B+Trees are more efficient when dealing with a * sparsely populated address space. Between 25% and 50% of the memory is * occupied with valid pointers. When densely populated, radix trees contain * ~98% pointers - hard to beat. Very sparse radix trees contain only ~2% * pointers. * * This particular implementation stores pointers identified by a long value. * Storing NULL pointers is illegal, lookup will return NULL when no entry * was found. * * A tricks was used that is not commonly found in textbooks. The lowest * values are to the right, not to the left. All used slots within a node * are on the left, all unused slots contain NUL values. Most operations * simply loop once over all slots and terminate on the first NUL. */ #include <linux/btree.h> #include <linux/cache.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define NODESIZE MAX(L1_CACHE_BYTES, 128) struct btree_geo { int keylen; int no_pairs; int no_longs; }; struct btree_geo btree_geo32 = { .keylen = 1, .no_pairs = NODESIZE / sizeof(long) / 2, .no_longs = NODESIZE / sizeof(long) / 2, }; EXPORT_SYMBOL_GPL(btree_geo32); #define LONG_PER_U64 (64 / BITS_PER_LONG) struct btree_geo btree_geo64 = { .keylen = LONG_PER_U64, .no_pairs = NODESIZE / sizeof(long) / (1 + LONG_PER_U64), .no_longs = LONG_PER_U64 * (NODESIZE / sizeof(long) / (1 + LONG_PER_U64)), }; EXPORT_SYMBOL_GPL(btree_geo64); struct btree_geo btree_geo128 = { .keylen = 2 * LONG_PER_U64, .no_pairs = NODESIZE / sizeof(long) / (1 + 2 * LONG_PER_U64), .no_longs = 2 * LONG_PER_U64 * (NODESIZE / sizeof(long) / (1 + 2 * LONG_PER_U64)), }; EXPORT_SYMBOL_GPL(btree_geo128); #define MAX_KEYLEN (2 * LONG_PER_U64) static struct kmem_cache *btree_cachep; void *btree_alloc(gfp_t gfp_mask, void *pool_data) { return kmem_cache_alloc(btree_cachep, gfp_mask); } EXPORT_SYMBOL_GPL(btree_alloc); void btree_free(void *element, void *pool_data) { kmem_cache_free(btree_cachep, element); } EXPORT_SYMBOL_GPL(btree_free); static unsigned long *btree_node_alloc(struct btree_head *head, gfp_t gfp) { unsigned long *node; node = mempool_alloc(head->mempool, gfp); if (likely(node)) memset(node, 0, NODESIZE); return node; } static int longcmp(const unsigned long *l1, const unsigned long *l2, size_t n) { size_t i; for (i = 0; i < n; i++) { if (l1[i] < l2[i]) return -1; if (l1[i] > l2[i]) return 1; } return 0; } static unsigned long *longcpy(unsigned long *dest, const unsigned long *src, size_t n) { size_t i; for (i = 0; i < n; i++) dest[i] = src[i]; return dest; } static unsigned long *longset(unsigned long *s, unsigned long c, size_t n) { size_t i; for (i = 0; i < n; i++) s[i] = c; return s; } static void dec_key(struct btree_geo *geo, unsigned long *key) { unsigned long val; int i; for (i = geo->keylen - 1; i >= 0; i--) { val = key[i]; key[i] = val - 1; if (val) break; } } static unsigned long *bkey(struct btree_geo *geo, unsigned long *node, int n) { return &node[n * geo->keylen]; } static void *bval(struct btree_geo *geo, unsigned long *node, int n) { return (void *)node[geo->no_longs + n]; } static void setkey(struct btree_geo *geo, unsigned long *node, int n, unsigned long *key) { longcpy(bkey(geo, node, n), key, geo->keylen); } static void setval(struct btree_geo *geo, unsigned long *node, int n, void *val) { node[geo->no_longs + n] = (unsigned long) val; } static void clearpair(struct btree_geo *geo, unsigned long *node, int n) { longset(bkey(geo, node, n), 0, geo->keylen); node[geo->no_longs + n] = 0; } static inline void __btree_init(struct btree_head *head) { head->node = NULL; head->height = 0; } void btree_init_mempool(struct btree_head *head, mempool_t *mempool) { __btree_init(head); head->mempool = mempool; } EXPORT_SYMBOL_GPL(btree_init_mempool); int btree_init(struct btree_head *head) { __btree_init(head); head->mempool = mempool_create(0, btree_alloc, btree_free, NULL); if (!head->mempool) return -ENOMEM; return 0; } EXPORT_SYMBOL_GPL(btree_init); void btree_destroy(struct btree_head *head) { mempool_free(head->node, head->mempool); mempool_destroy(head->mempool); head->mempool = NULL; } EXPORT_SYMBOL_GPL(btree_destroy); void *btree_last(struct btree_head *head, struct btree_geo *geo, unsigned long *key) { int height = head->height; unsigned long *node = head->node; if (height == 0) return NULL; for ( ; height > 1; height--) node = bval(geo, node, 0); longcpy(key, bkey(geo, node, 0), geo->keylen); return bval(geo, node, 0); } EXPORT_SYMBOL_GPL(btree_last); static int keycmp(struct btree_geo *geo, unsigned long *node, int pos, unsigned long *key) { return longcmp(bkey(geo, node, pos), key, geo->keylen); } static int keyzero(struct btree_geo *geo, unsigned long *key) { int i; for (i = 0; i < geo->keylen; i++) if (key[i]) return 0; return 1; } static void *btree_lookup_node(struct btree_head *head, struct btree_geo *geo, unsigned long *key) { int i, height = head->height; unsigned long *node = head->node; if (height == 0) return NULL; for ( ; height > 1; height--) { for (i = 0; i < geo->no_pairs; i++) if (keycmp(geo, node, i, key) <= 0) break; if (i == geo->no_pairs) return NULL; node = bval(geo, node, i); if (!node) return NULL; } return node; } void *btree_lookup(struct btree_head *head, struct btree_geo *geo, unsigned long *key) { int i; unsigned long *node; node = btree_lookup_node(head, geo, key); if (!node) return NULL; for (i = 0; i < geo->no_pairs; i++) if (keycmp(geo, node, i, key) == 0) return bval(geo, node, i); return NULL; } EXPORT_SYMBOL_GPL(btree_lookup); int btree_update(struct btree_head *head, struct btree_geo *geo, unsigned long *key, void *val) { int i; unsigned long *node; node = btree_lookup_node(head, geo, key); if (!node) return -ENOENT; for (i = 0; i < geo->no_pairs; i++) if (keycmp(geo, node, i, key) == 0) { setval(geo, node, i, val); return 0; } return -ENOENT; } EXPORT_SYMBOL_GPL(btree_update); /* * Usually this function is quite similar to normal lookup. But the key of * a parent node may be smaller than the smallest key of all its siblings. * In such a case we cannot just return NULL, as we have only proven that no * key smaller than __key, but larger than this parent key exists. * So we set __key to the parent key and retry. We have to use the smallest * such parent key, which is the last parent key we encountered. */ void *btree_get_prev(struct btree_head *head, struct btree_geo *geo, unsigned long *__key) { int i, height; unsigned long *node, *oldnode; unsigned long *retry_key = NULL, key[MAX_KEYLEN]; if (keyzero(geo, __key)) return NULL; if (head->height == 0) return NULL; longcpy(key, __key, geo->keylen); retry: dec_key(geo, key); node = head->node; for (height = head->height ; height > 1; height--) { for (i = 0; i < geo->no_pairs; i++) if (keycmp(geo, node, i, key) <= 0) break; if (i == geo->no_pairs) goto miss; oldnode = node; node = bval(geo, node, i); if (!node) goto miss; retry_key = bkey(geo, oldnode, i); } if (!node) goto miss; for (i = 0; i < geo->no_pairs; i++) { if (keycmp(geo, node, i, key) <= 0) { if (bval(geo, node, i)) { longcpy(__key, bkey(geo, node, i), geo->keylen); return bval(geo, node, i); } else goto miss; } } miss: if (retry_key) { longcpy(key, retry_key, geo->keylen); retry_key = NULL; goto retry; } return NULL; } EXPORT_SYMBOL_GPL(btree_get_prev); static int getpos(struct btree_geo *geo, unsigned long *node, unsigned long *key) { int i; for (i = 0; i < geo->no_pairs; i++) { if (keycmp(geo, node, i, key) <= 0) break; } return i; } static int getfill(struct btree_geo *geo, unsigned long *node, int start) { int i; for (i = start; i < geo->no_pairs; i++) if (!bval(geo, node, i)) break; return i; } /* * locate the correct leaf node in the btree */ static unsigned long *find_level(struct btree_head *head, struct btree_geo *geo, unsigned long *key, int level) { unsigned long *node = head->node; int i, height; for (height = head->height; height > level; height--) { for (i = 0; i < geo->no_pairs; i++) if (keycmp(geo, node, i, key) <= 0) break; if ((i == geo->no_pairs) || !bval(geo, node, i)) { /* right-most key is too large, update it */ /* FIXME: If the right-most key on higher levels is * always zero, this wouldn't be necessary. */ i--; setkey(geo, node, i, key); } BUG_ON(i < 0); node = bval(geo, node, i); } BUG_ON(!node); return node; } static int btree_grow(struct btree_head *head, struct btree_geo *geo, gfp_t gfp) { unsigned long *node; int fill; node = btree_node_alloc(head, gfp); if (!node) return -ENOMEM; if (head->node) { fill = getfill(geo, head->node, 0); setkey(geo, node, 0, bkey(geo, head->node, fill - 1)); setval(geo, node, 0, head->node); } head->node = node; head->height++; return 0; } static void btree_shrink(struct btree_head *head, struct btree_geo *geo) { unsigned long *node; int fill; if (head->height <= 1) return; node = head->node; fill = getfill(geo, node, 0); BUG_ON(fill > 1); head->node = bval(geo, node, 0); head->height--; mempool_free(node, head->mempool); } static int btree_insert_level(struct btree_head *head, struct btree_geo *geo, unsigned long *key, void *val, int level, gfp_t gfp) { unsigned long *node; int i, pos, fill, err; BUG_ON(!val); if (head->height < level) { err = btree_grow(head, geo, gfp); if (err) return err; } retry: node = find_level(head, geo, key, level); pos = getpos(geo, node, key); fill = getfill(geo, node, pos); /* two identical keys are not allowed */ BUG_ON(pos < fill && keycmp(geo, node, pos, key) == 0); if (fill == geo->no_pairs) { /* need to split node */ unsigned long *new; new = btree_node_alloc(head, gfp); if (!new) return -ENOMEM; err = btree_insert_level(head, geo, bkey(geo, node, fill / 2 - 1), new, level + 1, gfp); if (err) { mempool_free(new, head->mempool); return err; } for (i = 0; i < fill / 2; i++) { setkey(geo, new, i, bkey(geo, node, i)); setval(geo, new, i, bval(geo, node, i)); setkey(geo, node, i, bkey(geo, node, i + fill / 2)); setval(geo, node, i, bval(geo, node, i + fill / 2)); clearpair(geo, node, i + fill / 2); } if (fill & 1) { setkey(geo, node, i, bkey(geo, node, fill - 1)); setval(geo, node, i, bval(geo, node, fill - 1)); clearpair(geo, node, fill - 1); } goto retry; } BUG_ON(fill >= geo->no_pairs); /* shift and insert */ for (i = fill; i > pos; i--) { setkey(geo, node, i, bkey(geo, node, i - 1)); setval(geo, node, i, bval(geo, node, i - 1)); } setkey(geo, node, pos, key); setval(geo, node, pos, val); return 0; } int btree_insert(struct btree_head *head, struct btree_geo *geo, unsigned long *key, void *val, gfp_t gfp) { BUG_ON(!val); return btree_insert_level(head, geo, key, val, 1, gfp); } EXPORT_SYMBOL_GPL(btree_insert); static void *btree_remove_level(struct btree_head *head, struct btree_geo *geo, unsigned long *key, int level); static void merge(struct btree_head *head, struct btree_geo *geo, int level, unsigned long *left, int lfill, unsigned long *right, int rfill, unsigned long *parent, int lpos) { int i; for (i = 0; i < rfill; i++) { /* Move all keys to the left */ setkey(geo, left, lfill + i, bkey(geo, right, i)); setval(geo, left, lfill + i, bval(geo, right, i)); } /* Exchange left and right child in parent */ setval(geo, parent, lpos, right); setval(geo, parent, lpos + 1, left); /* Remove left (formerly right) child from parent */ btree_remove_level(head, geo, bkey(geo, parent, lpos), level + 1); mempool_free(right, head->mempool); } static void rebalance(struct btree_head *head, struct btree_geo *geo, unsigned long *key, int level, unsigned long *child, int fill) { unsigned long *parent, *left = NULL, *right = NULL; int i, no_left, no_right; if (fill == 0) { /* Because we don't steal entries from a neighbour, this case * can happen. Parent node contains a single child, this * node, so merging with a sibling never happens. */ btree_remove_level(head, geo, key, level + 1); mempool_free(child, head->mempool); return; } parent = find_level(head, geo, key, level + 1); i = getpos(geo, parent, key); BUG_ON(bval(geo, parent, i) != child); if (i > 0) { left = bval(geo, parent, i - 1); no_left = getfill(geo, left, 0); if (fill + no_left <= geo->no_pairs) { merge(head, geo, level, left, no_left, child, fill, parent, i - 1); return; } } if (i + 1 < getfill(geo, parent, i)) { right = bval(geo, parent, i + 1); no_right = getfill(geo, right, 0); if (fill + no_right <= geo->no_pairs) { merge(head, geo, level, child, fill, right, no_right, parent, i); return; } } /* * We could also try to steal one entry from the left or right * neighbor. By not doing so we changed the invariant from * "all nodes are at least half full" to "no two neighboring * nodes can be merged". Which means that the average fill of * all nodes is still half or better. */ } static void *btree_remove_level(struct btree_head *head, struct btree_geo *geo, unsigned long *key, int level) { unsigned long *node; int i, pos, fill; void *ret; if (level > head->height) { /* we recursed all the way up */ head->height = 0; head->node = NULL; return NULL; } node = find_level(head, geo, key, level); pos = getpos(geo, node, key); fill = getfill(geo, node, pos); if ((level == 1) && (keycmp(geo, node, pos, key) != 0)) return NULL; ret = bval(geo, node, pos); /* remove and shift */ for (i = pos; i < fill - 1; i++) { setkey(geo, node, i, bkey(geo, node, i + 1)); setval(geo, node, i, bval(geo, node, i + 1)); } clearpair(geo, node, fill - 1); if (fill - 1 < geo->no_pairs / 2) { if (level < head->height) rebalance(head, geo, key, level, node, fill - 1); else if (fill - 1 == 1) btree_shrink(head, geo); } return ret; } void *btree_remove(struct btree_head *head, struct btree_geo *geo, unsigned long *key) { if (head->height == 0) return NULL; return btree_remove_level(head, geo, key, 1); } EXPORT_SYMBOL_GPL(btree_remove); int btree_merge(struct btree_head *target, struct btree_head *victim, struct btree_geo *geo, gfp_t gfp) { unsigned long key[MAX_KEYLEN]; unsigned long dup[MAX_KEYLEN]; void *val; int err; BUG_ON(target == victim); if (!(target->node)) { /* target is empty, just copy fields over */ target->node = victim->node; target->height = victim->height; __btree_init(victim); return 0; } /* TODO: This needs some optimizations. Currently we do three tree * walks to remove a single object from the victim. */ for (;;) { if (!btree_last(victim, geo, key)) break; val = btree_lookup(victim, geo, key); err = btree_insert(target, geo, key, val, gfp); if (err) return err; /* We must make a copy of the key, as the original will get * mangled inside btree_remove. */ longcpy(dup, key, geo->keylen); btree_remove(victim, geo, dup); } return 0; } EXPORT_SYMBOL_GPL(btree_merge); static size_t __btree_for_each(struct btree_head *head, struct btree_geo *geo, unsigned long *node, unsigned long opaque, void (*func)(void *elem, unsigned long opaque, unsigned long *key, size_t index, void *func2), void *func2, int reap, int height, size_t count) { int i; unsigned long *child; for (i = 0; i < geo->no_pairs; i++) { child = bval(geo, node, i); if (!child) break; if (height > 1) count = __btree_for_each(head, geo, child, opaque, func, func2, reap, height - 1, count); else func(child, opaque, bkey(geo, node, i), count++, func2); } if (reap) mempool_free(node, head->mempool); return count; } static void empty(void *elem, unsigned long opaque, unsigned long *key, size_t index, void *func2) { } void visitorl(void *elem, unsigned long opaque, unsigned long *key, size_t index, void *__func) { visitorl_t func = __func; func(elem, opaque, *key, index); } EXPORT_SYMBOL_GPL(visitorl); void visitor32(void *elem, unsigned long opaque, unsigned long *__key, size_t index, void *__func) { visitor32_t func = __func; u32 *key = (void *)__key; func(elem, opaque, *key, index); } EXPORT_SYMBOL_GPL(visitor32); void visitor64(void *elem, unsigned long opaque, unsigned long *__key, size_t index, void *__func) { visitor64_t func = __func; u64 *key = (void *)__key; func(elem, opaque, *key, index); } EXPORT_SYMBOL_GPL(visitor64); void visitor128(void *elem, unsigned long opaque, unsigned long *__key, size_t index, void *__func) { visitor128_t func = __func; u64 *key = (void *)__key; func(elem, opaque, key[0], key[1], index); } EXPORT_SYMBOL_GPL(visitor128); size_t btree_visitor(struct btree_head *head, struct btree_geo *geo, unsigned long opaque, void (*func)(void *elem, unsigned long opaque, unsigned long *key, size_t index, void *func2), void *func2) { size_t count = 0; if (!func2) func = empty; if (head->node) count = __btree_for_each(head, geo, head->node, opaque, func, func2, 0, head->height, 0); return count; } EXPORT_SYMBOL_GPL(btree_visitor); size_t btree_grim_visitor(struct btree_head *head, struct btree_geo *geo, unsigned long opaque, void (*func)(void *elem, unsigned long opaque, unsigned long *key, size_t index, void *func2), void *func2) { size_t count = 0; if (!func2) func = empty; if (head->node) count = __btree_for_each(head, geo, head->node, opaque, func, func2, 1, head->height, 0); __btree_init(head); return count; } EXPORT_SYMBOL_GPL(btree_grim_visitor); static int __init btree_module_init(void) { btree_cachep = kmem_cache_create("btree_node", NODESIZE, 0, SLAB_HWCACHE_ALIGN, NULL); return 0; } static void __exit btree_module_exit(void) { kmem_cache_destroy(btree_cachep); } /* If core code starts using btree, initialization should happen even earlier */ module_init(btree_module_init); module_exit(btree_module_exit); MODULE_AUTHOR("Joern Engel <[email protected]>"); MODULE_AUTHOR("Johannes Berg <[email protected]>");
linux-master
lib/btree.c
// SPDX-License-Identifier: GPL-2.0-only #ifndef CONFIG_HAVE_ARCH_BITREVERSE #include <linux/types.h> #include <linux/module.h> #include <linux/bitrev.h> MODULE_AUTHOR("Akinobu Mita <[email protected]>"); MODULE_DESCRIPTION("Bit ordering reversal functions"); MODULE_LICENSE("GPL"); const u8 byte_rev_table[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, }; EXPORT_SYMBOL_GPL(byte_rev_table); #endif /* CONFIG_HAVE_ARCH_BITREVERSE */
linux-master
lib/bitrev.c
// SPDX-License-Identifier: GPL-2.0+ /* * Test cases for API provided by cmdline.c */ #include <kunit/test.h> #include <linux/kernel.h> #include <linux/random.h> #include <linux/string.h> static const char *cmdline_test_strings[] = { "\"\"", "" , "=" , "\"-", "," , "-," , ",-" , "-" , "+," , "--", ",,", "''" , "\"\",", "\",\"", "-\"\"", "\"", }; static const int cmdline_test_values[] = { 1, 1, 1, 1, 2, 3, 2, 3, 1, 3, 2, 1, 1, 1, 3, 1, }; static_assert(ARRAY_SIZE(cmdline_test_strings) == ARRAY_SIZE(cmdline_test_values)); static const char *cmdline_test_range_strings[] = { "-7" , "--7" , "-1-2" , "7--9", "7-" , "-7--9", "7-9," , "9-7" , "5-a", "a-5" , "5-8" , ",8-5", "+,1", "-,4" , "-3,0-1,6", "4,-" , " +2", " -9" , "0-1,-3,6", "- 9" , }; static const int cmdline_test_range_values[][16] = { { 1, -7, }, { 0, -0, }, { 4, -1, 0, +1, 2, }, { 0, 7, }, { 0, +7, }, { 0, -7, }, { 3, +7, 8, +9, 0, }, { 0, 9, }, { 0, +5, }, { 0, -0, }, { 4, +5, 6, +7, 8, }, { 0, 0, }, { 0, +0, }, { 0, -0, }, { 4, -3, 0, +1, 6, }, { 1, 4, }, { 0, +0, }, { 0, -0, }, { 4, +0, 1, -3, 6, }, { 0, 0, }, }; static_assert(ARRAY_SIZE(cmdline_test_range_strings) == ARRAY_SIZE(cmdline_test_range_values)); static void cmdline_do_one_test(struct kunit *test, const char *in, int rc, int offset) { const char *fmt = "Pattern: %s"; const char *out = in; int dummy; int ret; ret = get_option((char **)&out, &dummy); KUNIT_EXPECT_EQ_MSG(test, ret, rc, fmt, in); KUNIT_EXPECT_PTR_EQ_MSG(test, out, in + offset, fmt, in); } static void cmdline_test_noint(struct kunit *test) { unsigned int i = 0; do { const char *str = cmdline_test_strings[i]; int rc = 0; int offset; /* Only first and leading '-' will advance the pointer */ offset = !!(*str == '-'); cmdline_do_one_test(test, str, rc, offset); } while (++i < ARRAY_SIZE(cmdline_test_strings)); } static void cmdline_test_lead_int(struct kunit *test) { unsigned int i = 0; char in[32]; do { const char *str = cmdline_test_strings[i]; int rc = cmdline_test_values[i]; int offset; sprintf(in, "%u%s", get_random_u8(), str); /* Only first '-' after the number will advance the pointer */ offset = strlen(in) - strlen(str) + !!(rc == 2); cmdline_do_one_test(test, in, rc, offset); } while (++i < ARRAY_SIZE(cmdline_test_strings)); } static void cmdline_test_tail_int(struct kunit *test) { unsigned int i = 0; char in[32]; do { const char *str = cmdline_test_strings[i]; /* When "" or "-" the result will be valid integer */ int rc = strcmp(str, "") ? (strcmp(str, "-") ? 0 : 1) : 1; int offset; sprintf(in, "%s%u", str, get_random_u8()); /* * Only first and leading '-' not followed by integer * will advance the pointer. */ offset = rc ? strlen(in) : !!(*str == '-'); cmdline_do_one_test(test, in, rc, offset); } while (++i < ARRAY_SIZE(cmdline_test_strings)); } static void cmdline_do_one_range_test(struct kunit *test, const char *in, unsigned int n, const int *e) { unsigned int i; int r[16]; int *p; memset(r, 0, sizeof(r)); get_options(in, ARRAY_SIZE(r), r); KUNIT_EXPECT_EQ_MSG(test, r[0], e[0], "in test %u (parsed) expected %d numbers, got %d", n, e[0], r[0]); for (i = 1; i < ARRAY_SIZE(r); i++) KUNIT_EXPECT_EQ_MSG(test, r[i], e[i], "in test %u at %u", n, i); memset(r, 0, sizeof(r)); get_options(in, 0, r); KUNIT_EXPECT_EQ_MSG(test, r[0], e[0], "in test %u (validated) expected %d numbers, got %d", n, e[0], r[0]); p = memchr_inv(&r[1], 0, sizeof(r) - sizeof(r[0])); KUNIT_EXPECT_PTR_EQ_MSG(test, p, NULL, "in test %u at %u out of bound", n, p - r); } static void cmdline_test_range(struct kunit *test) { unsigned int i = 0; do { const char *str = cmdline_test_range_strings[i]; const int *e = cmdline_test_range_values[i]; cmdline_do_one_range_test(test, str, i, e); } while (++i < ARRAY_SIZE(cmdline_test_range_strings)); } static struct kunit_case cmdline_test_cases[] = { KUNIT_CASE(cmdline_test_noint), KUNIT_CASE(cmdline_test_lead_int), KUNIT_CASE(cmdline_test_tail_int), KUNIT_CASE(cmdline_test_range), {} }; static struct kunit_suite cmdline_test_suite = { .name = "cmdline", .test_cases = cmdline_test_cases, }; kunit_test_suite(cmdline_test_suite); MODULE_LICENSE("GPL");
linux-master
lib/cmdline_kunit.c
// SPDX-License-Identifier: GPL-2.0-only #include <kunit/test.h> #include <linux/sort.h> #include <linux/slab.h> #include <linux/module.h> /* a simple boot-time regression test */ #define TEST_LEN 1000 static int cmpint(const void *a, const void *b) { return *(int *)a - *(int *)b; } static void test_sort(struct kunit *test) { int *a, i, r = 1; a = kunit_kmalloc_array(test, TEST_LEN, sizeof(*a), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, a); for (i = 0; i < TEST_LEN; i++) { r = (r * 725861) % 6599; a[i] = r; } sort(a, TEST_LEN, sizeof(*a), cmpint, NULL); for (i = 0; i < TEST_LEN-1; i++) KUNIT_ASSERT_LE(test, a[i], a[i + 1]); } static struct kunit_case sort_test_cases[] = { KUNIT_CASE(test_sort), {} }; static struct kunit_suite sort_test_suite = { .name = "lib_sort", .test_cases = sort_test_cases, }; kunit_test_suites(&sort_test_suite); MODULE_LICENSE("GPL");
linux-master
lib/test_sort.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Red Black Trees (C) 1999 Andrea Arcangeli <[email protected]> (C) 2002 David Woodhouse <[email protected]> (C) 2012 Michel Lespinasse <[email protected]> linux/lib/rbtree.c */ #include <linux/rbtree_augmented.h> #include <linux/export.h> /* * red-black trees properties: https://en.wikipedia.org/wiki/Rbtree * * 1) A node is either red or black * 2) The root is black * 3) All leaves (NULL) are black * 4) Both children of every red node are black * 5) Every simple path from root to leaves contains the same number * of black nodes. * * 4 and 5 give the O(log n) guarantee, since 4 implies you cannot have two * consecutive red nodes in a path and every red node is therefore followed by * a black. So if B is the number of black nodes on every simple path (as per * 5), then the longest possible path due to 4 is 2B. * * We shall indicate color with case, where black nodes are uppercase and red * nodes will be lowercase. Unknown color nodes shall be drawn as red within * parentheses and have some accompanying text comment. */ /* * Notes on lockless lookups: * * All stores to the tree structure (rb_left and rb_right) must be done using * WRITE_ONCE(). And we must not inadvertently cause (temporary) loops in the * tree structure as seen in program order. * * These two requirements will allow lockless iteration of the tree -- not * correct iteration mind you, tree rotations are not atomic so a lookup might * miss entire subtrees. * * But they do guarantee that any such traversal will only see valid elements * and that it will indeed complete -- does not get stuck in a loop. * * It also guarantees that if the lookup returns an element it is the 'correct' * one. But not returning an element does _NOT_ mean it's not present. * * NOTE: * * Stores to __rb_parent_color are not important for simple lookups so those * are left undone as of now. Nor did I check for loops involving parent * pointers. */ static inline void rb_set_black(struct rb_node *rb) { rb->__rb_parent_color += RB_BLACK; } static inline struct rb_node *rb_red_parent(struct rb_node *red) { return (struct rb_node *)red->__rb_parent_color; } /* * Helper function for rotations: * - old's parent and color get assigned to new * - old gets assigned new as a parent and 'color' as a color. */ static inline void __rb_rotate_set_parents(struct rb_node *old, struct rb_node *new, struct rb_root *root, int color) { struct rb_node *parent = rb_parent(old); new->__rb_parent_color = old->__rb_parent_color; rb_set_parent_color(old, new, color); __rb_change_child(old, new, parent, root); } static __always_inline void __rb_insert(struct rb_node *node, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) { struct rb_node *parent = rb_red_parent(node), *gparent, *tmp; while (true) { /* * Loop invariant: node is red. */ if (unlikely(!parent)) { /* * The inserted node is root. Either this is the * first node, or we recursed at Case 1 below and * are no longer violating 4). */ rb_set_parent_color(node, NULL, RB_BLACK); break; } /* * If there is a black parent, we are done. * Otherwise, take some corrective action as, * per 4), we don't want a red root or two * consecutive red nodes. */ if(rb_is_black(parent)) break; gparent = rb_red_parent(parent); tmp = gparent->rb_right; if (parent != tmp) { /* parent == gparent->rb_left */ if (tmp && rb_is_red(tmp)) { /* * Case 1 - node's uncle is red (color flips). * * G g * / \ / \ * p u --> P U * / / * n n * * However, since g's parent might be red, and * 4) does not allow this, we need to recurse * at g. */ rb_set_parent_color(tmp, gparent, RB_BLACK); rb_set_parent_color(parent, gparent, RB_BLACK); node = gparent; parent = rb_parent(node); rb_set_parent_color(node, parent, RB_RED); continue; } tmp = parent->rb_right; if (node == tmp) { /* * Case 2 - node's uncle is black and node is * the parent's right child (left rotate at parent). * * G G * / \ / \ * p U --> n U * \ / * n p * * This still leaves us in violation of 4), the * continuation into Case 3 will fix that. */ tmp = node->rb_left; WRITE_ONCE(parent->rb_right, tmp); WRITE_ONCE(node->rb_left, parent); if (tmp) rb_set_parent_color(tmp, parent, RB_BLACK); rb_set_parent_color(parent, node, RB_RED); augment_rotate(parent, node); parent = node; tmp = node->rb_right; } /* * Case 3 - node's uncle is black and node is * the parent's left child (right rotate at gparent). * * G P * / \ / \ * p U --> n g * / \ * n U */ WRITE_ONCE(gparent->rb_left, tmp); /* == parent->rb_right */ WRITE_ONCE(parent->rb_right, gparent); if (tmp) rb_set_parent_color(tmp, gparent, RB_BLACK); __rb_rotate_set_parents(gparent, parent, root, RB_RED); augment_rotate(gparent, parent); break; } else { tmp = gparent->rb_left; if (tmp && rb_is_red(tmp)) { /* Case 1 - color flips */ rb_set_parent_color(tmp, gparent, RB_BLACK); rb_set_parent_color(parent, gparent, RB_BLACK); node = gparent; parent = rb_parent(node); rb_set_parent_color(node, parent, RB_RED); continue; } tmp = parent->rb_left; if (node == tmp) { /* Case 2 - right rotate at parent */ tmp = node->rb_right; WRITE_ONCE(parent->rb_left, tmp); WRITE_ONCE(node->rb_right, parent); if (tmp) rb_set_parent_color(tmp, parent, RB_BLACK); rb_set_parent_color(parent, node, RB_RED); augment_rotate(parent, node); parent = node; tmp = node->rb_left; } /* Case 3 - left rotate at gparent */ WRITE_ONCE(gparent->rb_right, tmp); /* == parent->rb_left */ WRITE_ONCE(parent->rb_left, gparent); if (tmp) rb_set_parent_color(tmp, gparent, RB_BLACK); __rb_rotate_set_parents(gparent, parent, root, RB_RED); augment_rotate(gparent, parent); break; } } } /* * Inline version for rb_erase() use - we want to be able to inline * and eliminate the dummy_rotate callback there */ static __always_inline void ____rb_erase_color(struct rb_node *parent, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) { struct rb_node *node = NULL, *sibling, *tmp1, *tmp2; while (true) { /* * Loop invariants: * - node is black (or NULL on first iteration) * - node is not the root (parent is not NULL) * - All leaf paths going through parent and node have a * black node count that is 1 lower than other leaf paths. */ sibling = parent->rb_right; if (node != sibling) { /* node == parent->rb_left */ if (rb_is_red(sibling)) { /* * Case 1 - left rotate at parent * * P S * / \ / \ * N s --> p Sr * / \ / \ * Sl Sr N Sl */ tmp1 = sibling->rb_left; WRITE_ONCE(parent->rb_right, tmp1); WRITE_ONCE(sibling->rb_left, parent); rb_set_parent_color(tmp1, parent, RB_BLACK); __rb_rotate_set_parents(parent, sibling, root, RB_RED); augment_rotate(parent, sibling); sibling = tmp1; } tmp1 = sibling->rb_right; if (!tmp1 || rb_is_black(tmp1)) { tmp2 = sibling->rb_left; if (!tmp2 || rb_is_black(tmp2)) { /* * Case 2 - sibling color flip * (p could be either color here) * * (p) (p) * / \ / \ * N S --> N s * / \ / \ * Sl Sr Sl Sr * * This leaves us violating 5) which * can be fixed by flipping p to black * if it was red, or by recursing at p. * p is red when coming from Case 1. */ rb_set_parent_color(sibling, parent, RB_RED); if (rb_is_red(parent)) rb_set_black(parent); else { node = parent; parent = rb_parent(node); if (parent) continue; } break; } /* * Case 3 - right rotate at sibling * (p could be either color here) * * (p) (p) * / \ / \ * N S --> N sl * / \ \ * sl Sr S * \ * Sr * * Note: p might be red, and then both * p and sl are red after rotation(which * breaks property 4). This is fixed in * Case 4 (in __rb_rotate_set_parents() * which set sl the color of p * and set p RB_BLACK) * * (p) (sl) * / \ / \ * N sl --> P S * \ / \ * S N Sr * \ * Sr */ tmp1 = tmp2->rb_right; WRITE_ONCE(sibling->rb_left, tmp1); WRITE_ONCE(tmp2->rb_right, sibling); WRITE_ONCE(parent->rb_right, tmp2); if (tmp1) rb_set_parent_color(tmp1, sibling, RB_BLACK); augment_rotate(sibling, tmp2); tmp1 = sibling; sibling = tmp2; } /* * Case 4 - left rotate at parent + color flips * (p and sl could be either color here. * After rotation, p becomes black, s acquires * p's color, and sl keeps its color) * * (p) (s) * / \ / \ * N S --> P Sr * / \ / \ * (sl) sr N (sl) */ tmp2 = sibling->rb_left; WRITE_ONCE(parent->rb_right, tmp2); WRITE_ONCE(sibling->rb_left, parent); rb_set_parent_color(tmp1, sibling, RB_BLACK); if (tmp2) rb_set_parent(tmp2, parent); __rb_rotate_set_parents(parent, sibling, root, RB_BLACK); augment_rotate(parent, sibling); break; } else { sibling = parent->rb_left; if (rb_is_red(sibling)) { /* Case 1 - right rotate at parent */ tmp1 = sibling->rb_right; WRITE_ONCE(parent->rb_left, tmp1); WRITE_ONCE(sibling->rb_right, parent); rb_set_parent_color(tmp1, parent, RB_BLACK); __rb_rotate_set_parents(parent, sibling, root, RB_RED); augment_rotate(parent, sibling); sibling = tmp1; } tmp1 = sibling->rb_left; if (!tmp1 || rb_is_black(tmp1)) { tmp2 = sibling->rb_right; if (!tmp2 || rb_is_black(tmp2)) { /* Case 2 - sibling color flip */ rb_set_parent_color(sibling, parent, RB_RED); if (rb_is_red(parent)) rb_set_black(parent); else { node = parent; parent = rb_parent(node); if (parent) continue; } break; } /* Case 3 - left rotate at sibling */ tmp1 = tmp2->rb_left; WRITE_ONCE(sibling->rb_right, tmp1); WRITE_ONCE(tmp2->rb_left, sibling); WRITE_ONCE(parent->rb_left, tmp2); if (tmp1) rb_set_parent_color(tmp1, sibling, RB_BLACK); augment_rotate(sibling, tmp2); tmp1 = sibling; sibling = tmp2; } /* Case 4 - right rotate at parent + color flips */ tmp2 = sibling->rb_right; WRITE_ONCE(parent->rb_left, tmp2); WRITE_ONCE(sibling->rb_right, parent); rb_set_parent_color(tmp1, sibling, RB_BLACK); if (tmp2) rb_set_parent(tmp2, parent); __rb_rotate_set_parents(parent, sibling, root, RB_BLACK); augment_rotate(parent, sibling); break; } } } /* Non-inline version for rb_erase_augmented() use */ void __rb_erase_color(struct rb_node *parent, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) { ____rb_erase_color(parent, root, augment_rotate); } EXPORT_SYMBOL(__rb_erase_color); /* * Non-augmented rbtree manipulation functions. * * We use dummy augmented callbacks here, and have the compiler optimize them * out of the rb_insert_color() and rb_erase() function definitions. */ static inline void dummy_propagate(struct rb_node *node, struct rb_node *stop) {} static inline void dummy_copy(struct rb_node *old, struct rb_node *new) {} static inline void dummy_rotate(struct rb_node *old, struct rb_node *new) {} static const struct rb_augment_callbacks dummy_callbacks = { .propagate = dummy_propagate, .copy = dummy_copy, .rotate = dummy_rotate }; void rb_insert_color(struct rb_node *node, struct rb_root *root) { __rb_insert(node, root, dummy_rotate); } EXPORT_SYMBOL(rb_insert_color); void rb_erase(struct rb_node *node, struct rb_root *root) { struct rb_node *rebalance; rebalance = __rb_erase_augmented(node, root, &dummy_callbacks); if (rebalance) ____rb_erase_color(rebalance, root, dummy_rotate); } EXPORT_SYMBOL(rb_erase); /* * Augmented rbtree manipulation functions. * * This instantiates the same __always_inline functions as in the non-augmented * case, but this time with user-defined callbacks. */ void __rb_insert_augmented(struct rb_node *node, struct rb_root *root, void (*augment_rotate)(struct rb_node *old, struct rb_node *new)) { __rb_insert(node, root, augment_rotate); } EXPORT_SYMBOL(__rb_insert_augmented); /* * This function returns the first node (in sort order) of the tree. */ struct rb_node *rb_first(const struct rb_root *root) { struct rb_node *n; n = root->rb_node; if (!n) return NULL; while (n->rb_left) n = n->rb_left; return n; } EXPORT_SYMBOL(rb_first); struct rb_node *rb_last(const struct rb_root *root) { struct rb_node *n; n = root->rb_node; if (!n) return NULL; while (n->rb_right) n = n->rb_right; return n; } EXPORT_SYMBOL(rb_last); struct rb_node *rb_next(const struct rb_node *node) { struct rb_node *parent; if (RB_EMPTY_NODE(node)) return NULL; /* * If we have a right-hand child, go down and then left as far * as we can. */ if (node->rb_right) { node = node->rb_right; while (node->rb_left) node = node->rb_left; return (struct rb_node *)node; } /* * No right-hand children. Everything down and left is smaller than us, * so any 'next' node must be in the general direction of our parent. * Go up the tree; any time the ancestor is a right-hand child of its * parent, keep going up. First time it's a left-hand child of its * parent, said parent is our 'next' node. */ while ((parent = rb_parent(node)) && node == parent->rb_right) node = parent; return parent; } EXPORT_SYMBOL(rb_next); struct rb_node *rb_prev(const struct rb_node *node) { struct rb_node *parent; if (RB_EMPTY_NODE(node)) return NULL; /* * If we have a left-hand child, go down and then right as far * as we can. */ if (node->rb_left) { node = node->rb_left; while (node->rb_right) node = node->rb_right; return (struct rb_node *)node; } /* * No left-hand children. Go up till we find an ancestor which * is a right-hand child of its parent. */ while ((parent = rb_parent(node)) && node == parent->rb_left) node = parent; return parent; } EXPORT_SYMBOL(rb_prev); void rb_replace_node(struct rb_node *victim, struct rb_node *new, struct rb_root *root) { struct rb_node *parent = rb_parent(victim); /* Copy the pointers/colour from the victim to the replacement */ *new = *victim; /* Set the surrounding nodes to point to the replacement */ if (victim->rb_left) rb_set_parent(victim->rb_left, new); if (victim->rb_right) rb_set_parent(victim->rb_right, new); __rb_change_child(victim, new, parent, root); } EXPORT_SYMBOL(rb_replace_node); void rb_replace_node_rcu(struct rb_node *victim, struct rb_node *new, struct rb_root *root) { struct rb_node *parent = rb_parent(victim); /* Copy the pointers/colour from the victim to the replacement */ *new = *victim; /* Set the surrounding nodes to point to the replacement */ if (victim->rb_left) rb_set_parent(victim->rb_left, new); if (victim->rb_right) rb_set_parent(victim->rb_right, new); /* Set the parent's pointer to the new node last after an RCU barrier * so that the pointers onwards are seen to be set correctly when doing * an RCU walk over the tree. */ __rb_change_child_rcu(victim, new, parent, root); } EXPORT_SYMBOL(rb_replace_node_rcu); static struct rb_node *rb_left_deepest_node(const struct rb_node *node) { for (;;) { if (node->rb_left) node = node->rb_left; else if (node->rb_right) node = node->rb_right; else return (struct rb_node *)node; } } struct rb_node *rb_next_postorder(const struct rb_node *node) { const struct rb_node *parent; if (!node) return NULL; parent = rb_parent(node); /* If we're sitting on node, we've already seen our children */ if (parent && node == parent->rb_left && parent->rb_right) { /* If we are the parent's left node, go to the parent's right * node then all the way down to the left */ return rb_left_deepest_node(parent->rb_right); } else /* Otherwise we are the parent's right node, and the parent * should be next */ return (struct rb_node *)parent; } EXPORT_SYMBOL(rb_next_postorder); struct rb_node *rb_first_postorder(const struct rb_root *root) { if (!root->rb_node) return NULL; return rb_left_deepest_node(root->rb_node); } EXPORT_SYMBOL(rb_first_postorder);
linux-master
lib/rbtree.c
// SPDX-License-Identifier: GPL-2.0 /* * KUnit test for the Kernel Hashtable structures. * * Copyright (C) 2022, Google LLC. * Author: Rae Moar <[email protected]> */ #include <kunit/test.h> #include <linux/hashtable.h> struct hashtable_test_entry { int key; int data; struct hlist_node node; int visited; }; static void hashtable_test_hash_init(struct kunit *test) { /* Test the different ways of initialising a hashtable. */ DEFINE_HASHTABLE(hash1, 2); DECLARE_HASHTABLE(hash2, 3); /* When using DECLARE_HASHTABLE, must use hash_init to * initialize the hashtable. */ hash_init(hash2); KUNIT_EXPECT_TRUE(test, hash_empty(hash1)); KUNIT_EXPECT_TRUE(test, hash_empty(hash2)); } static void hashtable_test_hash_empty(struct kunit *test) { struct hashtable_test_entry a; DEFINE_HASHTABLE(hash, 1); KUNIT_EXPECT_TRUE(test, hash_empty(hash)); a.key = 1; a.data = 13; hash_add(hash, &a.node, a.key); /* Hashtable should no longer be empty. */ KUNIT_EXPECT_FALSE(test, hash_empty(hash)); } static void hashtable_test_hash_hashed(struct kunit *test) { struct hashtable_test_entry a, b; DEFINE_HASHTABLE(hash, 4); a.key = 1; a.data = 13; hash_add(hash, &a.node, a.key); b.key = 1; b.data = 2; hash_add(hash, &b.node, b.key); KUNIT_EXPECT_TRUE(test, hash_hashed(&a.node)); KUNIT_EXPECT_TRUE(test, hash_hashed(&b.node)); } static void hashtable_test_hash_add(struct kunit *test) { struct hashtable_test_entry a, b, *x; int bkt; DEFINE_HASHTABLE(hash, 3); a.key = 1; a.data = 13; a.visited = 0; hash_add(hash, &a.node, a.key); b.key = 2; b.data = 10; b.visited = 0; hash_add(hash, &b.node, b.key); hash_for_each(hash, bkt, x, node) { x->visited++; if (x->key == a.key) KUNIT_EXPECT_EQ(test, x->data, 13); else if (x->key == b.key) KUNIT_EXPECT_EQ(test, x->data, 10); else KUNIT_FAIL(test, "Unexpected key in hashtable."); } /* Both entries should have been visited exactly once. */ KUNIT_EXPECT_EQ(test, a.visited, 1); KUNIT_EXPECT_EQ(test, b.visited, 1); } static void hashtable_test_hash_del(struct kunit *test) { struct hashtable_test_entry a, b, *x; DEFINE_HASHTABLE(hash, 6); a.key = 1; a.data = 13; hash_add(hash, &a.node, a.key); b.key = 2; b.data = 10; b.visited = 0; hash_add(hash, &b.node, b.key); hash_del(&b.node); hash_for_each_possible(hash, x, node, b.key) { x->visited++; KUNIT_EXPECT_NE(test, x->key, b.key); } /* The deleted entry should not have been visited. */ KUNIT_EXPECT_EQ(test, b.visited, 0); hash_del(&a.node); /* The hashtable should be empty. */ KUNIT_EXPECT_TRUE(test, hash_empty(hash)); } static void hashtable_test_hash_for_each(struct kunit *test) { struct hashtable_test_entry entries[3]; struct hashtable_test_entry *x; int bkt, i, j, count; DEFINE_HASHTABLE(hash, 3); /* Add three entries to the hashtable. */ for (i = 0; i < 3; i++) { entries[i].key = i; entries[i].data = i + 10; entries[i].visited = 0; hash_add(hash, &entries[i].node, entries[i].key); } count = 0; hash_for_each(hash, bkt, x, node) { x->visited += 1; KUNIT_ASSERT_GE_MSG(test, x->key, 0, "Unexpected key in hashtable."); KUNIT_ASSERT_LT_MSG(test, x->key, 3, "Unexpected key in hashtable."); count++; } /* Should have visited each entry exactly once. */ KUNIT_EXPECT_EQ(test, count, 3); for (j = 0; j < 3; j++) KUNIT_EXPECT_EQ(test, entries[j].visited, 1); } static void hashtable_test_hash_for_each_safe(struct kunit *test) { struct hashtable_test_entry entries[3]; struct hashtable_test_entry *x; struct hlist_node *tmp; int bkt, i, j, count; DEFINE_HASHTABLE(hash, 3); /* Add three entries to the hashtable. */ for (i = 0; i < 3; i++) { entries[i].key = i; entries[i].data = i + 10; entries[i].visited = 0; hash_add(hash, &entries[i].node, entries[i].key); } count = 0; hash_for_each_safe(hash, bkt, tmp, x, node) { x->visited += 1; KUNIT_ASSERT_GE_MSG(test, x->key, 0, "Unexpected key in hashtable."); KUNIT_ASSERT_LT_MSG(test, x->key, 3, "Unexpected key in hashtable."); count++; /* Delete entry during loop. */ hash_del(&x->node); } /* Should have visited each entry exactly once. */ KUNIT_EXPECT_EQ(test, count, 3); for (j = 0; j < 3; j++) KUNIT_EXPECT_EQ(test, entries[j].visited, 1); } static void hashtable_test_hash_for_each_possible(struct kunit *test) { struct hashtable_test_entry entries[4]; struct hashtable_test_entry *x, *y; int buckets[2]; int bkt, i, j, count; DEFINE_HASHTABLE(hash, 5); /* Add three entries with key = 0 to the hashtable. */ for (i = 0; i < 3; i++) { entries[i].key = 0; entries[i].data = i; entries[i].visited = 0; hash_add(hash, &entries[i].node, entries[i].key); } /* Add an entry with key = 1. */ entries[3].key = 1; entries[3].data = 3; entries[3].visited = 0; hash_add(hash, &entries[3].node, entries[3].key); count = 0; hash_for_each_possible(hash, x, node, 0) { x->visited += 1; KUNIT_ASSERT_GE_MSG(test, x->data, 0, "Unexpected data in hashtable."); KUNIT_ASSERT_LT_MSG(test, x->data, 4, "Unexpected data in hashtable."); count++; } /* Should have visited each entry with key = 0 exactly once. */ for (j = 0; j < 3; j++) KUNIT_EXPECT_EQ(test, entries[j].visited, 1); /* Save the buckets for the different keys. */ hash_for_each(hash, bkt, y, node) { KUNIT_ASSERT_GE_MSG(test, y->key, 0, "Unexpected key in hashtable."); KUNIT_ASSERT_LE_MSG(test, y->key, 1, "Unexpected key in hashtable."); buckets[y->key] = bkt; } /* If entry with key = 1 is in the same bucket as the entries with * key = 0, check it was visited. Otherwise ensure that only three * entries were visited. */ if (buckets[0] == buckets[1]) { KUNIT_EXPECT_EQ(test, count, 4); KUNIT_EXPECT_EQ(test, entries[3].visited, 1); } else { KUNIT_EXPECT_EQ(test, count, 3); KUNIT_EXPECT_EQ(test, entries[3].visited, 0); } } static void hashtable_test_hash_for_each_possible_safe(struct kunit *test) { struct hashtable_test_entry entries[4]; struct hashtable_test_entry *x, *y; struct hlist_node *tmp; int buckets[2]; int bkt, i, j, count; DEFINE_HASHTABLE(hash, 5); /* Add three entries with key = 0 to the hashtable. */ for (i = 0; i < 3; i++) { entries[i].key = 0; entries[i].data = i; entries[i].visited = 0; hash_add(hash, &entries[i].node, entries[i].key); } /* Add an entry with key = 1. */ entries[3].key = 1; entries[3].data = 3; entries[3].visited = 0; hash_add(hash, &entries[3].node, entries[3].key); count = 0; hash_for_each_possible_safe(hash, x, tmp, node, 0) { x->visited += 1; KUNIT_ASSERT_GE_MSG(test, x->data, 0, "Unexpected data in hashtable."); KUNIT_ASSERT_LT_MSG(test, x->data, 4, "Unexpected data in hashtable."); count++; /* Delete entry during loop. */ hash_del(&x->node); } /* Should have visited each entry with key = 0 exactly once. */ for (j = 0; j < 3; j++) KUNIT_EXPECT_EQ(test, entries[j].visited, 1); /* Save the buckets for the different keys. */ hash_for_each(hash, bkt, y, node) { KUNIT_ASSERT_GE_MSG(test, y->key, 0, "Unexpected key in hashtable."); KUNIT_ASSERT_LE_MSG(test, y->key, 1, "Unexpected key in hashtable."); buckets[y->key] = bkt; } /* If entry with key = 1 is in the same bucket as the entries with * key = 0, check it was visited. Otherwise ensure that only three * entries were visited. */ if (buckets[0] == buckets[1]) { KUNIT_EXPECT_EQ(test, count, 4); KUNIT_EXPECT_EQ(test, entries[3].visited, 1); } else { KUNIT_EXPECT_EQ(test, count, 3); KUNIT_EXPECT_EQ(test, entries[3].visited, 0); } } static struct kunit_case hashtable_test_cases[] = { KUNIT_CASE(hashtable_test_hash_init), KUNIT_CASE(hashtable_test_hash_empty), KUNIT_CASE(hashtable_test_hash_hashed), KUNIT_CASE(hashtable_test_hash_add), KUNIT_CASE(hashtable_test_hash_del), KUNIT_CASE(hashtable_test_hash_for_each), KUNIT_CASE(hashtable_test_hash_for_each_safe), KUNIT_CASE(hashtable_test_hash_for_each_possible), KUNIT_CASE(hashtable_test_hash_for_each_possible_safe), {}, }; static struct kunit_suite hashtable_test_module = { .name = "hashtable", .test_cases = hashtable_test_cases, }; kunit_test_suites(&hashtable_test_module); MODULE_LICENSE("GPL");
linux-master
lib/hashtable_test.c