Home | History | Annotate | Download | only in src
      1 /* Authors: Karl MacMillan <kmacmillan (at) mentalrootkit.com>
      2  *	    Joshua Brindle <jbrindle (at) tresys.com>
      3  *          Jason Tang <jtang (at) tresys.com>
      4  *
      5  * Copyright (C) 2004-2005 Tresys Technology, LLC
      6  * Copyright (C) 2007 Red Hat, Inc.
      7  *
      8  *  This library is free software; you can redistribute it and/or
      9  *  modify it under the terms of the GNU Lesser General Public
     10  *  License as published by the Free Software Foundation; either
     11  *  version 2.1 of the License, or (at your option) any later version.
     12  *
     13  *  This library is distributed in the hope that it will be useful,
     14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     16  *  Lesser General Public License for more details.
     17  *
     18  *  You should have received a copy of the GNU Lesser General Public
     19  *  License along with this library; if not, write to the Free Software
     20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     21  */
     22 
     23 #include <sepol/policydb/policydb.h>
     24 #include <sepol/policydb/conditional.h>
     25 #include <sepol/policydb/hashtab.h>
     26 #include <sepol/policydb/avrule_block.h>
     27 #include <sepol/policydb/link.h>
     28 #include <sepol/policydb/util.h>
     29 
     30 #include <stdlib.h>
     31 #include <stdarg.h>
     32 #include <stdio.h>
     33 #include <string.h>
     34 #include <assert.h>
     35 
     36 #include "debug.h"
     37 
     38 #undef min
     39 #define min(a,b) (((a) < (b)) ? (a) : (b))
     40 
     41 typedef struct policy_module {
     42 	policydb_t *policy;
     43 	uint32_t num_decls;
     44 	uint32_t *map[SYM_NUM];
     45 	uint32_t *avdecl_map;
     46 	uint32_t **perm_map;
     47 	uint32_t *perm_map_len;
     48 
     49 	/* a pointer to within the base module's avrule_block chain to
     50 	 * where this module's global now resides */
     51 	avrule_block_t *base_global;
     52 } policy_module_t;
     53 
     54 typedef struct link_state {
     55 	int verbose;
     56 	policydb_t *base;
     57 	avrule_block_t *last_avrule_block, *last_base_avrule_block;
     58 	uint32_t next_decl_id, current_decl_id;
     59 
     60 	/* temporary variables, used during hashtab_map() calls */
     61 	policy_module_t *cur;
     62 	char *cur_mod_name;
     63 	avrule_decl_t *dest_decl;
     64 	class_datum_t *src_class, *dest_class;
     65 	char *dest_class_name;
     66 	char dest_class_req;	/* flag indicating the class was not declared */
     67 	uint32_t symbol_num;
     68 	/* used to report the name of the module if dependancy error occurs */
     69 	policydb_t **decl_to_mod;
     70 
     71 	/* error reporting fields */
     72 	sepol_handle_t *handle;
     73 } link_state_t;
     74 
     75 typedef struct missing_requirement {
     76 	uint32_t symbol_type;
     77 	uint32_t symbol_value;
     78 	uint32_t perm_value;
     79 } missing_requirement_t;
     80 
     81 static const char *symtab_names[SYM_NUM] = {
     82 	"common", "class", "role", "type/attribute", "user",
     83 	"bool", "level", "category"
     84 };
     85 
     86 /* Deallocates all elements within a module, but NOT the policydb_t
     87  * structure within, as well as the pointer itself. */
     88 static void policy_module_destroy(policy_module_t * mod)
     89 {
     90 	unsigned int i;
     91 	if (mod == NULL) {
     92 		return;
     93 	}
     94 	for (i = 0; i < SYM_NUM; i++) {
     95 		free(mod->map[i]);
     96 	}
     97 	for (i = 0; mod->perm_map != NULL && i < mod->policy->p_classes.nprim;
     98 	     i++) {
     99 		free(mod->perm_map[i]);
    100 	}
    101 	free(mod->perm_map);
    102 	free(mod->perm_map_len);
    103 	free(mod->avdecl_map);
    104 	free(mod);
    105 }
    106 
    107 /***** functions that copy identifiers from a module to base *****/
    108 
    109 /* Note: there is currently no scoping for permissions, which causes some
    110  * strange side-effects. The current approach is this:
    111  *
    112  * a) perm is required and the class _and_ perm are declared in base: only add a mapping.
    113  * b) perm is required and the class and perm are _not_ declared in base: simply add the permissions
    114  *    to the object class. This means that the requirements for the decl are the union of the permissions
    115  *    required for all decls, but who cares.
    116  * c) perm is required, the class is declared in base, but the perm is not present. Nothing we can do
    117  *    here because we can't mark a single permission as required, so we bail with a requirement error
    118  *    _even_ if we are in an optional.
    119  *
    120  * A is correct behavior, b is wrong but not too bad, c is totall wrong for optionals. Fixing this requires
    121  * a format change.
    122  */
    123 static int permission_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    124 				    void *data)
    125 {
    126 	char *perm_id = key, *new_id = NULL;
    127 	perm_datum_t *perm, *new_perm = NULL, *dest_perm;
    128 	link_state_t *state = (link_state_t *) data;
    129 
    130 	class_datum_t *src_class = state->src_class;
    131 	class_datum_t *dest_class = state->dest_class;
    132 	policy_module_t *mod = state->cur;
    133 	uint32_t sclassi = src_class->s.value - 1;
    134 	int ret;
    135 
    136 	perm = (perm_datum_t *) datum;
    137 	dest_perm = hashtab_search(dest_class->permissions.table, perm_id);
    138 	if (dest_perm == NULL && dest_class->comdatum != NULL) {
    139 		dest_perm =
    140 		    hashtab_search(dest_class->comdatum->permissions.table,
    141 				   perm_id);
    142 	}
    143 
    144 	if (dest_perm == NULL) {
    145 		/* If the object class was not declared in the base, add the perm
    146 		 * to the object class. */
    147 		if (state->dest_class_req) {
    148 			/* If the class was required (not declared), insert the new permission */
    149 			new_id = strdup(perm_id);
    150 			if (new_id == NULL) {
    151 				ERR(state->handle, "Memory error");
    152 				ret = SEPOL_ERR;
    153 				goto err;
    154 			}
    155 			new_perm =
    156 			    (perm_datum_t *) calloc(1, sizeof(perm_datum_t));
    157 			if (new_perm == NULL) {
    158 				ERR(state->handle, "Memory error");
    159 				ret = SEPOL_ERR;
    160 				goto err;
    161 			}
    162 			ret = hashtab_insert(dest_class->permissions.table,
    163 					     (hashtab_key_t) new_id,
    164 					     (hashtab_datum_t) new_perm);
    165 			if (ret) {
    166 				ERR(state->handle,
    167 				    "could not insert permission into class\n");
    168 				goto err;
    169 			}
    170 			new_perm->s.value = dest_class->permissions.nprim + 1;
    171 			dest_perm = new_perm;
    172 		} else {
    173 			/* this is case c from above */
    174 			ERR(state->handle,
    175 			    "Module %s depends on permission %s in class %s, not satisfied",
    176 			    state->cur_mod_name, perm_id,
    177 			    state->dest_class_name);
    178 			return SEPOL_EREQ;
    179 		}
    180 	}
    181 
    182 	/* build the mapping for permissions encompassing this class.
    183 	 * unlike symbols, the permission map translates between
    184 	 * module permission bit to target permission bit.  that bit
    185 	 * may have originated from the class -or- it could be from
    186 	 * the class's common parent.*/
    187 	if (perm->s.value > mod->perm_map_len[sclassi]) {
    188 		uint32_t *newmap = calloc(perm->s.value, sizeof(*newmap));
    189 		if (newmap == NULL) {
    190 			ERR(state->handle, "Out of memory!");
    191 			return -1;
    192 		}
    193 		memcpy(newmap, mod->perm_map[sclassi],
    194 		       mod->perm_map_len[sclassi] * sizeof(*newmap));
    195 		free(mod->perm_map[sclassi]);
    196 		mod->perm_map[sclassi] = newmap;
    197 		mod->perm_map_len[sclassi] = perm->s.value;
    198 	}
    199 	mod->perm_map[sclassi][perm->s.value - 1] = dest_perm->s.value;
    200 
    201 	return 0;
    202       err:
    203 	free(new_id);
    204 	free(new_perm);
    205 	return ret;
    206 }
    207 
    208 static int class_copy_default_new_object(link_state_t *state,
    209 					 class_datum_t *olddatum,
    210 					 class_datum_t *newdatum)
    211 {
    212 	if (olddatum->default_user) {
    213 		if (newdatum->default_user && olddatum->default_user != newdatum->default_user) {
    214 			ERR(state->handle, "Found conflicting default user definitions");
    215 			return SEPOL_ENOTSUP;
    216 		}
    217 		newdatum->default_user = olddatum->default_user;
    218 	}
    219 	if (olddatum->default_role) {
    220 		if (newdatum->default_role && olddatum->default_role != newdatum->default_role) {
    221 			ERR(state->handle, "Found conflicting default role definitions");
    222 			return SEPOL_ENOTSUP;
    223 		}
    224 		newdatum->default_role = olddatum->default_role;
    225 	}
    226 	if (olddatum->default_range) {
    227 		if (newdatum->default_range && olddatum->default_range != newdatum->default_range) {
    228 			ERR(state->handle, "Found conflicting default range definitions");
    229 			return SEPOL_ENOTSUP;
    230 		}
    231 		newdatum->default_range = olddatum->default_range;
    232 	}
    233 	return 0;
    234 }
    235 
    236 static int class_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    237 			       void *data)
    238 {
    239 	char *id = key, *new_id = NULL;
    240 	class_datum_t *cladatum, *new_class = NULL;
    241 	link_state_t *state = (link_state_t *) data;
    242 	scope_datum_t *scope = NULL;
    243 	int ret;
    244 
    245 	cladatum = (class_datum_t *) datum;
    246 	state->dest_class_req = 0;
    247 
    248 	new_class = hashtab_search(state->base->p_classes.table, id);
    249 	/* If there is not an object class already in the base symtab that means
    250 	 * that either a) a module is trying to declare a new object class (which
    251 	 * the compiler should prevent) or b) an object class was required that is
    252 	 * not in the base.
    253 	 */
    254 	if (new_class == NULL) {
    255 		scope =
    256 		    hashtab_search(state->cur->policy->p_classes_scope.table,
    257 				   id);
    258 		if (scope == NULL) {
    259 			ret = SEPOL_ERR;
    260 			goto err;
    261 		}
    262 		if (scope->scope == SCOPE_DECL) {
    263 			/* disallow declarations in modules */
    264 			ERR(state->handle,
    265 			    "%s: Modules may not yet declare new classes.",
    266 			    state->cur_mod_name);
    267 			ret = SEPOL_ENOTSUP;
    268 			goto err;
    269 		} else {
    270 			/* It would be nice to error early here because the requirement is
    271 			 * not met, but we cannot because the decl might be optional (in which
    272 			 * case we should record the requirement so that it is just turned
    273 			 * off). Note: this will break horribly if modules can declare object
    274 			 * classes because the class numbers will be all wrong (i.e., they
    275 			 * might be assigned in the order they were required rather than the
    276 			 * current scheme which ensures correct numbering by ordering the
    277 			 * declarations properly). This can't be fixed until some infrastructure
    278 			 * for querying the object class numbers is in place. */
    279 			state->dest_class_req = 1;
    280 			new_class =
    281 			    (class_datum_t *) calloc(1, sizeof(class_datum_t));
    282 			if (new_class == NULL) {
    283 				ERR(state->handle, "Memory error\n");
    284 				ret = SEPOL_ERR;
    285 				goto err;
    286 			}
    287 			if (symtab_init
    288 			    (&new_class->permissions, PERM_SYMTAB_SIZE)) {
    289 				ret = SEPOL_ERR;
    290 				goto err;
    291 			}
    292 			new_id = strdup(id);
    293 			if (new_id == NULL) {
    294 				symtab_destroy(&new_class->permissions);
    295 				ERR(state->handle, "Memory error\n");
    296 				ret = SEPOL_ERR;
    297 				goto err;
    298 			}
    299 			ret = hashtab_insert(state->base->p_classes.table,
    300 					     (hashtab_key_t) new_id,
    301 					     (hashtab_datum_t) new_class);
    302 			if (ret) {
    303 				symtab_destroy(&new_class->permissions);
    304 				ERR(state->handle,
    305 				    "could not insert new class into symtab");
    306 				goto err;
    307 			}
    308 			new_class->s.value = ++(state->base->p_classes.nprim);
    309 		}
    310 	}
    311 
    312 	state->cur->map[SYM_CLASSES][cladatum->s.value - 1] =
    313 	    new_class->s.value;
    314 
    315 	/* copy permissions */
    316 	state->src_class = cladatum;
    317 	state->dest_class = new_class;
    318 	state->dest_class_name = (char *)key;
    319 
    320 	/* copy default new object rules */
    321 	ret = class_copy_default_new_object(state, cladatum, new_class);
    322 	if (ret)
    323 		return ret;
    324 
    325 	ret =
    326 	    hashtab_map(cladatum->permissions.table, permission_copy_callback,
    327 			state);
    328 	if (ret != 0) {
    329 		return ret;
    330 	}
    331 
    332 	return 0;
    333       err:
    334 	free(new_class);
    335 	free(new_id);
    336 	return ret;
    337 }
    338 
    339 static int role_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    340 			      void *data)
    341 {
    342 	int ret;
    343 	char *id = key, *new_id = NULL;
    344 	role_datum_t *role, *base_role, *new_role = NULL;
    345 	link_state_t *state = (link_state_t *) data;
    346 
    347 	role = (role_datum_t *) datum;
    348 
    349 	base_role = hashtab_search(state->base->p_roles.table, id);
    350 	if (base_role != NULL) {
    351 		/* role already exists.  check that it is what this
    352 		 * module expected.  duplicate declarations (e.g., two
    353 		 * modules both declare role foo_r) is checked during
    354 		 * scope_copy_callback(). */
    355 		if (role->flavor == ROLE_ATTRIB
    356 		    && base_role->flavor != ROLE_ATTRIB) {
    357 			ERR(state->handle,
    358 			    "%s: Expected %s to be a role attribute, but it was already declared as a regular role.",
    359 			    state->cur_mod_name, id);
    360 			return -1;
    361 		} else if (role->flavor != ROLE_ATTRIB
    362 			   && base_role->flavor == ROLE_ATTRIB) {
    363 			ERR(state->handle,
    364 			    "%s: Expected %s to be a regular role, but it was already declared as a role attribute.",
    365 			    state->cur_mod_name, id);
    366 			return -1;
    367 		}
    368 	} else {
    369 		if (state->verbose)
    370 			INFO(state->handle, "copying role %s", id);
    371 
    372 		if ((new_id = strdup(id)) == NULL) {
    373 			goto cleanup;
    374 		}
    375 
    376 		if ((new_role =
    377 		     (role_datum_t *) malloc(sizeof(*new_role))) == NULL) {
    378 			goto cleanup;
    379 		}
    380 		role_datum_init(new_role);
    381 
    382 		/* new_role's dominates, types and roles field will be copied
    383 		 * during role_fix_callback() */
    384 		new_role->flavor = role->flavor;
    385 		new_role->s.value = state->base->p_roles.nprim + 1;
    386 
    387 		ret = hashtab_insert(state->base->p_roles.table,
    388 				     (hashtab_key_t) new_id,
    389 				     (hashtab_datum_t) new_role);
    390 		if (ret) {
    391 			goto cleanup;
    392 		}
    393 		state->base->p_roles.nprim++;
    394 		base_role = new_role;
    395 	}
    396 
    397 	if (state->dest_decl) {
    398 		new_id = NULL;
    399 		if ((new_role = malloc(sizeof(*new_role))) == NULL) {
    400 			goto cleanup;
    401 		}
    402 		role_datum_init(new_role);
    403 		new_role->flavor = base_role->flavor;
    404 		new_role->s.value = base_role->s.value;
    405 		if ((new_id = strdup(id)) == NULL) {
    406 			goto cleanup;
    407 		}
    408 		if (hashtab_insert
    409 		    (state->dest_decl->p_roles.table, new_id, new_role)) {
    410 			goto cleanup;
    411 		}
    412 		state->dest_decl->p_roles.nprim++;
    413 	}
    414 
    415 	state->cur->map[SYM_ROLES][role->s.value - 1] = base_role->s.value;
    416 	return 0;
    417 
    418       cleanup:
    419 	ERR(state->handle, "Out of memory!");
    420 	role_datum_destroy(new_role);
    421 	free(new_id);
    422 	free(new_role);
    423 	return -1;
    424 }
    425 
    426 /* Copy types and attributes from a module into the base module. The
    427  * attributes are copied, but the types that make up this attribute
    428  * are delayed type_fix_callback(). */
    429 static int type_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    430 			      void *data)
    431 {
    432 	int ret;
    433 	char *id = key, *new_id = NULL;
    434 	type_datum_t *type, *base_type, *new_type = NULL;
    435 	link_state_t *state = (link_state_t *) data;
    436 
    437 	type = (type_datum_t *) datum;
    438 	if ((type->flavor == TYPE_TYPE && !type->primary)
    439 	    || type->flavor == TYPE_ALIAS) {
    440 		/* aliases are handled later, in alias_copy_callback() */
    441 		return 0;
    442 	}
    443 
    444 	base_type = hashtab_search(state->base->p_types.table, id);
    445 	if (base_type != NULL) {
    446 		/* type already exists.  check that it is what this
    447 		 * module expected.  duplicate declarations (e.g., two
    448 		 * modules both declare type foo_t) is checked during
    449 		 * scope_copy_callback(). */
    450 		if (type->flavor == TYPE_ATTRIB
    451 		    && base_type->flavor != TYPE_ATTRIB) {
    452 			ERR(state->handle,
    453 			    "%s: Expected %s to be an attribute, but it was already declared as a type.",
    454 			    state->cur_mod_name, id);
    455 			return -1;
    456 		} else if (type->flavor != TYPE_ATTRIB
    457 			   && base_type->flavor == TYPE_ATTRIB) {
    458 			ERR(state->handle,
    459 			    "%s: Expected %s to be a type, but it was already declared as an attribute.",
    460 			    state->cur_mod_name, id);
    461 			return -1;
    462 		}
    463 		/* permissive should pass to the base type */
    464 		base_type->flags |= (type->flags & TYPE_FLAGS_PERMISSIVE);
    465 	} else {
    466 		if (state->verbose)
    467 			INFO(state->handle, "copying type %s", id);
    468 
    469 		if ((new_id = strdup(id)) == NULL) {
    470 			goto cleanup;
    471 		}
    472 
    473 		if ((new_type =
    474 		     (type_datum_t *) calloc(1, sizeof(*new_type))) == NULL) {
    475 			goto cleanup;
    476 		}
    477 		new_type->primary = type->primary;
    478 		new_type->flags = type->flags;
    479 		new_type->flavor = type->flavor;
    480 		/* for attributes, the writing of new_type->types is
    481 		   done in type_fix_callback() */
    482 
    483 		new_type->s.value = state->base->p_types.nprim + 1;
    484 
    485 		ret = hashtab_insert(state->base->p_types.table,
    486 				     (hashtab_key_t) new_id,
    487 				     (hashtab_datum_t) new_type);
    488 		if (ret) {
    489 			goto cleanup;
    490 		}
    491 		state->base->p_types.nprim++;
    492 		base_type = new_type;
    493 	}
    494 
    495 	if (state->dest_decl) {
    496 		new_id = NULL;
    497 		if ((new_type = calloc(1, sizeof(*new_type))) == NULL) {
    498 			goto cleanup;
    499 		}
    500 		new_type->primary = type->primary;
    501 		new_type->flavor = type->flavor;
    502 		new_type->flags = type->flags;
    503 		new_type->s.value = base_type->s.value;
    504 		if ((new_id = strdup(id)) == NULL) {
    505 			goto cleanup;
    506 		}
    507 		if (hashtab_insert
    508 		    (state->dest_decl->p_types.table, new_id, new_type)) {
    509 			goto cleanup;
    510 		}
    511 		state->dest_decl->p_types.nprim++;
    512 	}
    513 
    514 	state->cur->map[SYM_TYPES][type->s.value - 1] = base_type->s.value;
    515 	return 0;
    516 
    517       cleanup:
    518 	ERR(state->handle, "Out of memory!");
    519 	free(new_id);
    520 	free(new_type);
    521 	return -1;
    522 }
    523 
    524 static int user_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    525 			      void *data)
    526 {
    527 	int ret;
    528 	char *id = key, *new_id = NULL;
    529 	user_datum_t *user, *base_user, *new_user = NULL;
    530 	link_state_t *state = (link_state_t *) data;
    531 
    532 	user = (user_datum_t *) datum;
    533 
    534 	base_user = hashtab_search(state->base->p_users.table, id);
    535 	if (base_user == NULL) {
    536 		if (state->verbose)
    537 			INFO(state->handle, "copying user %s", id);
    538 
    539 		if ((new_id = strdup(id)) == NULL) {
    540 			goto cleanup;
    541 		}
    542 
    543 		if ((new_user =
    544 		     (user_datum_t *) malloc(sizeof(*new_user))) == NULL) {
    545 			goto cleanup;
    546 		}
    547 		user_datum_init(new_user);
    548 		/* new_users's roles and MLS fields will be copied during
    549 		   user_fix_callback(). */
    550 
    551 		new_user->s.value = state->base->p_users.nprim + 1;
    552 
    553 		ret = hashtab_insert(state->base->p_users.table,
    554 				     (hashtab_key_t) new_id,
    555 				     (hashtab_datum_t) new_user);
    556 		if (ret) {
    557 			goto cleanup;
    558 		}
    559 		state->base->p_users.nprim++;
    560 		base_user = new_user;
    561 	}
    562 
    563 	if (state->dest_decl) {
    564 		new_id = NULL;
    565 		if ((new_user = malloc(sizeof(*new_user))) == NULL) {
    566 			goto cleanup;
    567 		}
    568 		user_datum_init(new_user);
    569 		new_user->s.value = base_user->s.value;
    570 		if ((new_id = strdup(id)) == NULL) {
    571 			goto cleanup;
    572 		}
    573 		if (hashtab_insert
    574 		    (state->dest_decl->p_users.table, new_id, new_user)) {
    575 			goto cleanup;
    576 		}
    577 		state->dest_decl->p_users.nprim++;
    578 	}
    579 
    580 	state->cur->map[SYM_USERS][user->s.value - 1] = base_user->s.value;
    581 	return 0;
    582 
    583       cleanup:
    584 	ERR(state->handle, "Out of memory!");
    585 	user_datum_destroy(new_user);
    586 	free(new_id);
    587 	free(new_user);
    588 	return -1;
    589 }
    590 
    591 static int bool_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    592 			      void *data)
    593 {
    594 	int ret;
    595 	char *id = key, *new_id = NULL;
    596 	cond_bool_datum_t *booldatum, *base_bool, *new_bool = NULL;
    597 	link_state_t *state = (link_state_t *) data;
    598 	scope_datum_t *scope;
    599 
    600 	booldatum = (cond_bool_datum_t *) datum;
    601 
    602 	base_bool = hashtab_search(state->base->p_bools.table, id);
    603 	if (base_bool == NULL) {
    604 		if (state->verbose)
    605 			INFO(state->handle, "copying boolean %s", id);
    606 
    607 		if ((new_id = strdup(id)) == NULL) {
    608 			goto cleanup;
    609 		}
    610 
    611 		if ((new_bool =
    612 		     (cond_bool_datum_t *) malloc(sizeof(*new_bool))) == NULL) {
    613 			goto cleanup;
    614 		}
    615 		new_bool->s.value = state->base->p_bools.nprim + 1;
    616 
    617 		ret = hashtab_insert(state->base->p_bools.table,
    618 				     (hashtab_key_t) new_id,
    619 				     (hashtab_datum_t) new_bool);
    620 		if (ret) {
    621 			goto cleanup;
    622 		}
    623 		state->base->p_bools.nprim++;
    624 		base_bool = new_bool;
    625 		base_bool->flags = booldatum->flags;
    626 	} else if ((booldatum->flags & COND_BOOL_FLAGS_TUNABLE) !=
    627 		   (base_bool->flags & COND_BOOL_FLAGS_TUNABLE)) {
    628 			/* A mismatch between boolean/tunable declaration
    629 			 * and usage(for example a boolean used in the
    630 			 * tunable_policy() or vice versa).
    631 			 *
    632 			 * This is not allowed and bail out with errors */
    633 			ERR(state->handle,
    634 			    "%s: Mismatch between boolean/tunable definition "
    635 			    "and usage for %s", state->cur_mod_name, id);
    636 			return -1;
    637 	}
    638 
    639 	/* Get the scope info for this boolean to see if this is the declaration,
    640  	 * if so set the state */
    641 	scope = hashtab_search(state->cur->policy->p_bools_scope.table, id);
    642 	if (!scope)
    643 		return SEPOL_ERR;
    644 	if (scope->scope == SCOPE_DECL) {
    645 		base_bool->state = booldatum->state;
    646 		/* Only the declaration rather than requirement
    647 		 * decides if it is a boolean or tunable. */
    648 		base_bool->flags = booldatum->flags;
    649 	}
    650 	state->cur->map[SYM_BOOLS][booldatum->s.value - 1] = base_bool->s.value;
    651 	return 0;
    652 
    653       cleanup:
    654 	ERR(state->handle, "Out of memory!");
    655 	cond_destroy_bool(new_id, new_bool, NULL);
    656 	return -1;
    657 }
    658 
    659 static int sens_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    660 			      void *data)
    661 {
    662 	char *id = key;
    663 	level_datum_t *level, *base_level;
    664 	link_state_t *state = (link_state_t *) data;
    665 	scope_datum_t *scope;
    666 
    667 	level = (level_datum_t *) datum;
    668 
    669 	base_level = hashtab_search(state->base->p_levels.table, id);
    670 	if (!base_level) {
    671 		scope =
    672 		    hashtab_search(state->cur->policy->p_sens_scope.table, id);
    673 		if (!scope)
    674 			return SEPOL_ERR;
    675 		if (scope->scope == SCOPE_DECL) {
    676 			/* disallow declarations in modules */
    677 			ERR(state->handle,
    678 			    "%s: Modules may not declare new sensitivities.",
    679 			    state->cur_mod_name);
    680 			return SEPOL_ENOTSUP;
    681 		}
    682 		if (scope->scope == SCOPE_REQ) {
    683 			/* unmet requirement */
    684 			ERR(state->handle,
    685 			    "%s: Sensitivity %s not declared by base.",
    686 			    state->cur_mod_name, id);
    687 			return SEPOL_ENOTSUP;
    688 		}
    689 	}
    690 
    691 	state->cur->map[SYM_LEVELS][level->level->sens - 1] =
    692 	    base_level->level->sens;
    693 
    694 	return 0;
    695 }
    696 
    697 static int cat_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    698 			     void *data)
    699 {
    700 	char *id = key;
    701 	cat_datum_t *cat, *base_cat;
    702 	link_state_t *state = (link_state_t *) data;
    703 	scope_datum_t *scope;
    704 
    705 	cat = (cat_datum_t *) datum;
    706 
    707 	base_cat = hashtab_search(state->base->p_cats.table, id);
    708 	if (!base_cat) {
    709 		scope =
    710 		    hashtab_search(state->cur->policy->p_cat_scope.table, id);
    711 		if (!scope)
    712 			return SEPOL_ERR;
    713 		if (scope->scope == SCOPE_DECL) {
    714 			/* disallow declarations in modules */
    715 			ERR(state->handle,
    716 			    "%s: Modules may not declare new categories.",
    717 			    state->cur_mod_name);
    718 			return SEPOL_ENOTSUP;
    719 		}
    720 		if (scope->scope == SCOPE_REQ) {
    721 			/* unmet requirement */
    722 			ERR(state->handle,
    723 			    "%s: Category %s not declared by base.",
    724 			    state->cur_mod_name, id);
    725 			return SEPOL_ENOTSUP;
    726 		}
    727 	}
    728 
    729 	state->cur->map[SYM_CATS][cat->s.value - 1] = base_cat->s.value;
    730 
    731 	return 0;
    732 }
    733 
    734 static int (*copy_callback_f[SYM_NUM]) (hashtab_key_t key,
    735 					hashtab_datum_t datum, void *datap) = {
    736 NULL, class_copy_callback, role_copy_callback, type_copy_callback,
    737 	    user_copy_callback, bool_copy_callback, sens_copy_callback,
    738 	    cat_copy_callback};
    739 
    740 /*
    741  * The boundaries have to be copied after the types/roles/users are copied,
    742  * because it refers hashtab to lookup destinated objects.
    743  */
    744 static int type_bounds_copy_callback(hashtab_key_t key,
    745 				     hashtab_datum_t datum, void *data)
    746 {
    747 	link_state_t *state = (link_state_t *) data;
    748 	type_datum_t *type = (type_datum_t *) datum;
    749 	type_datum_t *dest;
    750 	uint32_t bounds_val;
    751 
    752 	if (!type->bounds)
    753 		return 0;
    754 
    755 	bounds_val = state->cur->map[SYM_TYPES][type->bounds - 1];
    756 
    757 	dest = hashtab_search(state->base->p_types.table, key);
    758 	if (!dest) {
    759 		ERR(state->handle,
    760 		    "Type lookup failed for %s", (char *)key);
    761 		return -1;
    762 	}
    763 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
    764 		ERR(state->handle,
    765 		    "Inconsistent boundary for %s", (char *)key);
    766 		return -1;
    767 	}
    768 	dest->bounds = bounds_val;
    769 
    770 	return 0;
    771 }
    772 
    773 static int role_bounds_copy_callback(hashtab_key_t key,
    774 				     hashtab_datum_t datum, void *data)
    775 {
    776 	link_state_t *state = (link_state_t *) data;
    777 	role_datum_t *role = (role_datum_t *) datum;
    778 	role_datum_t *dest;
    779 	uint32_t bounds_val;
    780 
    781 	if (!role->bounds)
    782 		return 0;
    783 
    784 	bounds_val = state->cur->map[SYM_ROLES][role->bounds - 1];
    785 
    786 	dest = hashtab_search(state->base->p_roles.table, key);
    787 	if (!dest) {
    788 		ERR(state->handle,
    789 		    "Role lookup failed for %s", (char *)key);
    790 		return -1;
    791 	}
    792 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
    793 		ERR(state->handle,
    794 		    "Inconsistent boundary for %s", (char *)key);
    795 		return -1;
    796 	}
    797 	dest->bounds = bounds_val;
    798 
    799 	return 0;
    800 }
    801 
    802 static int user_bounds_copy_callback(hashtab_key_t key,
    803 				     hashtab_datum_t datum, void *data)
    804 {
    805 	link_state_t *state = (link_state_t *) data;
    806 	user_datum_t *user = (user_datum_t *) datum;
    807 	user_datum_t *dest;
    808 	uint32_t bounds_val;
    809 
    810 	if (!user->bounds)
    811 		return 0;
    812 
    813 	bounds_val = state->cur->map[SYM_USERS][user->bounds - 1];
    814 
    815 	dest = hashtab_search(state->base->p_users.table, key);
    816 	if (!dest) {
    817 		ERR(state->handle,
    818 		    "User lookup failed for %s", (char *)key);
    819 		return -1;
    820 	}
    821 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
    822 		ERR(state->handle,
    823 		    "Inconsistent boundary for %s", (char *)key);
    824 		return -1;
    825 	}
    826 	dest->bounds = bounds_val;
    827 
    828 	return 0;
    829 }
    830 
    831 /* The aliases have to be copied after the types and attributes to be
    832  * certain that the base symbol table will have the type that the
    833  * alias refers. Otherwise, we won't be able to find the type value
    834  * for the alias. We can't depend on the declaration ordering because
    835  * of the hash table.
    836  */
    837 static int alias_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
    838 			       void *data)
    839 {
    840 	char *id = key, *new_id = NULL, *target_id;
    841 	type_datum_t *type, *base_type, *new_type = NULL, *target_type;
    842 	link_state_t *state = (link_state_t *) data;
    843 	policy_module_t *mod = state->cur;
    844 	int primval;
    845 
    846 	type = (type_datum_t *) datum;
    847 	/* there are 2 kinds of aliases. Ones with their own value (TYPE_ALIAS)
    848 	 * and ones with the value of their primary (TYPE_TYPE && type->primary = 0)
    849 	 */
    850 	if (!
    851 	    (type->flavor == TYPE_ALIAS
    852 	     || (type->flavor == TYPE_TYPE && !type->primary))) {
    853 		/* ignore types and attributes -- they were handled in
    854 		 * type_copy_callback() */
    855 		return 0;
    856 	}
    857 
    858 	if (type->flavor == TYPE_ALIAS)
    859 		primval = type->primary;
    860 	else
    861 		primval = type->s.value;
    862 
    863 	target_id = mod->policy->p_type_val_to_name[primval - 1];
    864 	target_type = hashtab_search(state->base->p_types.table, target_id);
    865 	if (target_type == NULL) {
    866 		ERR(state->handle, "%s: Could not find type %s for alias %s.",
    867 		    state->cur_mod_name, target_id, id);
    868 		return -1;
    869 	}
    870 
    871 	if (!strcmp(id, target_id)) {
    872 		ERR(state->handle, "%s: Self aliasing of %s.",
    873 		    state->cur_mod_name, id);
    874 		return -1;
    875 	}
    876 
    877 	target_type->flags |= (type->flags & TYPE_FLAGS_PERMISSIVE);
    878 
    879 	base_type = hashtab_search(state->base->p_types.table, id);
    880 	if (base_type == NULL) {
    881 		if (state->verbose)
    882 			INFO(state->handle, "copying alias %s", id);
    883 
    884 		if ((new_type =
    885 		     (type_datum_t *) calloc(1, sizeof(*new_type))) == NULL) {
    886 			goto cleanup;
    887 		}
    888 		/* the linked copy always has TYPE_ALIAS style aliases */
    889 		new_type->primary = target_type->s.value;
    890 		new_type->flags = target_type->flags;
    891 		new_type->flavor = TYPE_ALIAS;
    892 		new_type->s.value = state->base->p_types.nprim + 1;
    893 		if ((new_id = strdup(id)) == NULL) {
    894 			goto cleanup;
    895 		}
    896 		if (hashtab_insert
    897 		    (state->base->p_types.table, new_id, new_type)) {
    898 			goto cleanup;
    899 		}
    900 		state->base->p_types.nprim++;
    901 		base_type = new_type;
    902 	} else {
    903 
    904 		/* if this already exists and isn't an alias it was required by another module (or base)
    905 		 * and inserted into the hashtable as a type, fix it up now */
    906 
    907 		if (base_type->flavor == TYPE_ALIAS) {
    908 			/* error checking */
    909 			assert(base_type->primary == target_type->s.value);
    910 			assert(base_type->primary ==
    911 			       mod->map[SYM_TYPES][primval - 1]);
    912 			assert(mod->map[SYM_TYPES][type->s.value - 1] ==
    913 			       base_type->primary);
    914 			return 0;
    915 		}
    916 
    917 		if (base_type->flavor == TYPE_ATTRIB) {
    918 			ERR(state->handle,
    919 			    "%s is an alias of an attribute, not allowed", id);
    920 			return -1;
    921 		}
    922 
    923 		base_type->flavor = TYPE_ALIAS;
    924 		base_type->primary = target_type->s.value;
    925 		base_type->flags |= (target_type->flags & TYPE_FLAGS_PERMISSIVE);
    926 
    927 	}
    928 	/* the aliases map points from its value to its primary so when this module
    929 	 * references this type the value it gets back from the map is the primary */
    930 	mod->map[SYM_TYPES][type->s.value - 1] = base_type->primary;
    931 
    932 	return 0;
    933 
    934       cleanup:
    935 	ERR(state->handle, "Out of memory!");
    936 	free(new_id);
    937 	free(new_type);
    938 	return -1;
    939 }
    940 
    941 /*********** callbacks that fix bitmaps ***********/
    942 
    943 static int type_set_convert(type_set_t * types, type_set_t * dst,
    944 			    policy_module_t * mod, link_state_t * state
    945 			    __attribute__ ((unused)))
    946 {
    947 	unsigned int i;
    948 	ebitmap_node_t *tnode;
    949 	ebitmap_for_each_bit(&types->types, tnode, i) {
    950 		if (ebitmap_node_get_bit(tnode, i)) {
    951 			assert(mod->map[SYM_TYPES][i]);
    952 			if (ebitmap_set_bit
    953 			    (&dst->types, mod->map[SYM_TYPES][i] - 1, 1)) {
    954 				goto cleanup;
    955 			}
    956 		}
    957 	}
    958 	ebitmap_for_each_bit(&types->negset, tnode, i) {
    959 		if (ebitmap_node_get_bit(tnode, i)) {
    960 			assert(mod->map[SYM_TYPES][i]);
    961 			if (ebitmap_set_bit
    962 			    (&dst->negset, mod->map[SYM_TYPES][i] - 1, 1)) {
    963 				goto cleanup;
    964 			}
    965 		}
    966 	}
    967 	dst->flags = types->flags;
    968 	return 0;
    969 
    970       cleanup:
    971 	return -1;
    972 }
    973 
    974 /* OR 2 typemaps together and at the same time map the src types to
    975  * the correct values in the dst typeset.
    976  */
    977 static int type_set_or_convert(type_set_t * types, type_set_t * dst,
    978 			       policy_module_t * mod, link_state_t * state)
    979 {
    980 	type_set_t ts_tmp;
    981 
    982 	type_set_init(&ts_tmp);
    983 	if (type_set_convert(types, &ts_tmp, mod, state) == -1) {
    984 		goto cleanup;
    985 	}
    986 	if (type_set_or_eq(dst, &ts_tmp)) {
    987 		goto cleanup;
    988 	}
    989 	type_set_destroy(&ts_tmp);
    990 	return 0;
    991 
    992       cleanup:
    993 	ERR(state->handle, "Out of memory!");
    994 	type_set_destroy(&ts_tmp);
    995 	return -1;
    996 }
    997 
    998 static int role_set_or_convert(role_set_t * roles, role_set_t * dst,
    999 			       policy_module_t * mod, link_state_t * state)
   1000 {
   1001 	unsigned int i;
   1002 	ebitmap_t tmp;
   1003 	ebitmap_node_t *rnode;
   1004 
   1005 	ebitmap_init(&tmp);
   1006 	ebitmap_for_each_bit(&roles->roles, rnode, i) {
   1007 		if (ebitmap_node_get_bit(rnode, i)) {
   1008 			assert(mod->map[SYM_ROLES][i]);
   1009 			if (ebitmap_set_bit
   1010 			    (&tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
   1011 				goto cleanup;
   1012 			}
   1013 		}
   1014 	}
   1015 	if (ebitmap_union(&dst->roles, &tmp)) {
   1016 		goto cleanup;
   1017 	}
   1018 	dst->flags |= roles->flags;
   1019 	ebitmap_destroy(&tmp);
   1020 	return 0;
   1021       cleanup:
   1022 	ERR(state->handle, "Out of memory!");
   1023 	ebitmap_destroy(&tmp);
   1024 	return -1;
   1025 }
   1026 
   1027 static int mls_level_convert(mls_semantic_level_t * src, mls_semantic_level_t * dst,
   1028 			     policy_module_t * mod, link_state_t * state)
   1029 {
   1030 	mls_semantic_cat_t *src_cat, *new_cat;
   1031 
   1032 	if (!mod->policy->mls)
   1033 		return 0;
   1034 
   1035 	/* Required not declared. */
   1036 	if (!src->sens)
   1037 		return 0;
   1038 
   1039 	assert(mod->map[SYM_LEVELS][src->sens - 1]);
   1040 	dst->sens = mod->map[SYM_LEVELS][src->sens - 1];
   1041 
   1042 	for (src_cat = src->cat; src_cat; src_cat = src_cat->next) {
   1043 		new_cat =
   1044 		    (mls_semantic_cat_t *) malloc(sizeof(mls_semantic_cat_t));
   1045 		if (!new_cat) {
   1046 			ERR(state->handle, "Out of memory");
   1047 			return -1;
   1048 		}
   1049 		mls_semantic_cat_init(new_cat);
   1050 
   1051 		new_cat->next = dst->cat;
   1052 		dst->cat = new_cat;
   1053 
   1054 		assert(mod->map[SYM_CATS][src_cat->low - 1]);
   1055 		dst->cat->low = mod->map[SYM_CATS][src_cat->low - 1];
   1056 		assert(mod->map[SYM_CATS][src_cat->high - 1]);
   1057 		dst->cat->high = mod->map[SYM_CATS][src_cat->high - 1];
   1058 	}
   1059 
   1060 	return 0;
   1061 }
   1062 
   1063 static int mls_range_convert(mls_semantic_range_t * src, mls_semantic_range_t * dst,
   1064 			     policy_module_t * mod, link_state_t * state)
   1065 {
   1066 	int ret;
   1067 	ret = mls_level_convert(&src->level[0], &dst->level[0], mod, state);
   1068 	if (ret)
   1069 		return ret;
   1070 	ret = mls_level_convert(&src->level[1], &dst->level[1], mod, state);
   1071 	if (ret)
   1072 		return ret;
   1073 	return 0;
   1074 }
   1075 
   1076 static int role_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
   1077 			     void *data)
   1078 {
   1079 	unsigned int i;
   1080 	char *id = key;
   1081 	role_datum_t *role, *dest_role = NULL;
   1082 	link_state_t *state = (link_state_t *) data;
   1083 	ebitmap_t e_tmp;
   1084 	policy_module_t *mod = state->cur;
   1085 	ebitmap_node_t *rnode;
   1086 	hashtab_t role_tab;
   1087 
   1088 	role = (role_datum_t *) datum;
   1089 	if (state->dest_decl == NULL)
   1090 		role_tab = state->base->p_roles.table;
   1091 	else
   1092 		role_tab = state->dest_decl->p_roles.table;
   1093 
   1094 	dest_role = hashtab_search(role_tab, id);
   1095 	assert(dest_role != NULL);
   1096 
   1097 	if (state->verbose) {
   1098 		INFO(state->handle, "fixing role %s", id);
   1099 	}
   1100 
   1101 	ebitmap_init(&e_tmp);
   1102 	ebitmap_for_each_bit(&role->dominates, rnode, i) {
   1103 		if (ebitmap_node_get_bit(rnode, i)) {
   1104 			assert(mod->map[SYM_ROLES][i]);
   1105 			if (ebitmap_set_bit
   1106 			    (&e_tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
   1107 				goto cleanup;
   1108 			}
   1109 		}
   1110 	}
   1111 	if (ebitmap_union(&dest_role->dominates, &e_tmp)) {
   1112 		goto cleanup;
   1113 	}
   1114 	if (type_set_or_convert(&role->types, &dest_role->types, mod, state)) {
   1115 		goto cleanup;
   1116 	}
   1117 	ebitmap_destroy(&e_tmp);
   1118 
   1119 	if (role->flavor == ROLE_ATTRIB) {
   1120 		ebitmap_init(&e_tmp);
   1121 		ebitmap_for_each_bit(&role->roles, rnode, i) {
   1122 			if (ebitmap_node_get_bit(rnode, i)) {
   1123 				assert(mod->map[SYM_ROLES][i]);
   1124 				if (ebitmap_set_bit
   1125 				    (&e_tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
   1126 					goto cleanup;
   1127 				}
   1128 			}
   1129 		}
   1130 		if (ebitmap_union(&dest_role->roles, &e_tmp)) {
   1131 			goto cleanup;
   1132 		}
   1133 		ebitmap_destroy(&e_tmp);
   1134 	}
   1135 
   1136 	return 0;
   1137 
   1138       cleanup:
   1139 	ERR(state->handle, "Out of memory!");
   1140 	ebitmap_destroy(&e_tmp);
   1141 	return -1;
   1142 }
   1143 
   1144 static int type_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
   1145 			     void *data)
   1146 {
   1147 	unsigned int i;
   1148 	char *id = key;
   1149 	type_datum_t *type, *new_type = NULL;
   1150 	link_state_t *state = (link_state_t *) data;
   1151 	ebitmap_t e_tmp;
   1152 	policy_module_t *mod = state->cur;
   1153 	ebitmap_node_t *tnode;
   1154 	symtab_t *typetab;
   1155 
   1156 	type = (type_datum_t *) datum;
   1157 
   1158 	if (state->dest_decl == NULL)
   1159 		typetab = &state->base->p_types;
   1160 	else
   1161 		typetab = &state->dest_decl->p_types;
   1162 
   1163 	/* only fix attributes */
   1164 	if (type->flavor != TYPE_ATTRIB) {
   1165 		return 0;
   1166 	}
   1167 
   1168 	new_type = hashtab_search(typetab->table, id);
   1169 	assert(new_type != NULL && new_type->flavor == TYPE_ATTRIB);
   1170 
   1171 	if (state->verbose) {
   1172 		INFO(state->handle, "fixing attribute %s", id);
   1173 	}
   1174 
   1175 	ebitmap_init(&e_tmp);
   1176 	ebitmap_for_each_bit(&type->types, tnode, i) {
   1177 		if (ebitmap_node_get_bit(tnode, i)) {
   1178 			assert(mod->map[SYM_TYPES][i]);
   1179 			if (ebitmap_set_bit
   1180 			    (&e_tmp, mod->map[SYM_TYPES][i] - 1, 1)) {
   1181 				goto cleanup;
   1182 			}
   1183 		}
   1184 	}
   1185 	if (ebitmap_union(&new_type->types, &e_tmp)) {
   1186 		goto cleanup;
   1187 	}
   1188 	ebitmap_destroy(&e_tmp);
   1189 	return 0;
   1190 
   1191       cleanup:
   1192 	ERR(state->handle, "Out of memory!");
   1193 	ebitmap_destroy(&e_tmp);
   1194 	return -1;
   1195 }
   1196 
   1197 static int user_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
   1198 			     void *data)
   1199 {
   1200 	char *id = key;
   1201 	user_datum_t *user, *new_user = NULL;
   1202 	link_state_t *state = (link_state_t *) data;
   1203 	policy_module_t *mod = state->cur;
   1204 	symtab_t *usertab;
   1205 
   1206 	user = (user_datum_t *) datum;
   1207 
   1208 	if (state->dest_decl == NULL)
   1209 		usertab = &state->base->p_users;
   1210 	else
   1211 		usertab = &state->dest_decl->p_users;
   1212 
   1213 	new_user = hashtab_search(usertab->table, id);
   1214 	assert(new_user != NULL);
   1215 
   1216 	if (state->verbose) {
   1217 		INFO(state->handle, "fixing user %s", id);
   1218 	}
   1219 
   1220 	if (role_set_or_convert(&user->roles, &new_user->roles, mod, state)) {
   1221 		goto cleanup;
   1222 	}
   1223 
   1224 	if (mls_range_convert(&user->range, &new_user->range, mod, state))
   1225 		goto cleanup;
   1226 
   1227 	if (mls_level_convert(&user->dfltlevel, &new_user->dfltlevel, mod, state))
   1228 		goto cleanup;
   1229 
   1230 	return 0;
   1231 
   1232       cleanup:
   1233 	ERR(state->handle, "Out of memory!");
   1234 	return -1;
   1235 }
   1236 
   1237 static int (*fix_callback_f[SYM_NUM]) (hashtab_key_t key, hashtab_datum_t datum,
   1238 				       void *datap) = {
   1239 NULL, NULL, role_fix_callback, type_fix_callback, user_fix_callback,
   1240 	    NULL, NULL, NULL};
   1241 
   1242 /*********** functions that copy AV rules ***********/
   1243 
   1244 static int copy_avrule_list(avrule_t * list, avrule_t ** dst,
   1245 			    policy_module_t * module, link_state_t * state)
   1246 {
   1247 	unsigned int i;
   1248 	avrule_t *cur, *new_rule = NULL, *tail;
   1249 	class_perm_node_t *cur_perm, *new_perm, *tail_perm = NULL;
   1250 
   1251 	tail = *dst;
   1252 	while (tail && tail->next) {
   1253 		tail = tail->next;
   1254 	}
   1255 
   1256 	cur = list;
   1257 	while (cur) {
   1258 		if ((new_rule = (avrule_t *) malloc(sizeof(avrule_t))) == NULL) {
   1259 			goto cleanup;
   1260 		}
   1261 		avrule_init(new_rule);
   1262 
   1263 		new_rule->specified = cur->specified;
   1264 		new_rule->flags = cur->flags;
   1265 		if (type_set_convert
   1266 		    (&cur->stypes, &new_rule->stypes, module, state) == -1
   1267 		    || type_set_convert(&cur->ttypes, &new_rule->ttypes, module,
   1268 					state) == -1) {
   1269 			goto cleanup;
   1270 		}
   1271 
   1272 		cur_perm = cur->perms;
   1273 		tail_perm = NULL;
   1274 		while (cur_perm) {
   1275 			if ((new_perm = (class_perm_node_t *)
   1276 			     malloc(sizeof(class_perm_node_t))) == NULL) {
   1277 				goto cleanup;
   1278 			}
   1279 			class_perm_node_init(new_perm);
   1280 
   1281 			new_perm->class =
   1282 			    module->map[SYM_CLASSES][cur_perm->class - 1];
   1283 			assert(new_perm->class);
   1284 
   1285 			if (new_rule->specified & AVRULE_AV) {
   1286 				for (i = 0;
   1287 				     i <
   1288 				     module->perm_map_len[cur_perm->class - 1];
   1289 				     i++) {
   1290 					if (!(cur_perm->data & (1U << i)))
   1291 						continue;
   1292 					new_perm->data |=
   1293 					    (1U <<
   1294 					     (module->
   1295 					      perm_map[cur_perm->class - 1][i] -
   1296 					      1));
   1297 				}
   1298 			} else {
   1299 				new_perm->data =
   1300 				    module->map[SYM_TYPES][cur_perm->data - 1];
   1301 			}
   1302 
   1303 			if (new_rule->perms == NULL) {
   1304 				new_rule->perms = new_perm;
   1305 			} else if (tail_perm) {
   1306 				tail_perm->next = new_perm;
   1307 			}
   1308 			tail_perm = new_perm;
   1309 			cur_perm = cur_perm->next;
   1310 		}
   1311 		new_rule->line = cur->line;
   1312 
   1313 		cur = cur->next;
   1314 
   1315 		if (*dst == NULL) {
   1316 			*dst = new_rule;
   1317 		} else {
   1318 			tail->next = new_rule;
   1319 		}
   1320 		tail = new_rule;
   1321 	}
   1322 
   1323 	return 0;
   1324       cleanup:
   1325 	ERR(state->handle, "Out of memory!");
   1326 	avrule_destroy(new_rule);
   1327 	free(new_rule);
   1328 	return -1;
   1329 }
   1330 
   1331 static int copy_role_trans_list(role_trans_rule_t * list,
   1332 				role_trans_rule_t ** dst,
   1333 				policy_module_t * module, link_state_t * state)
   1334 {
   1335 	role_trans_rule_t *cur, *new_rule = NULL, *tail;
   1336 	unsigned int i;
   1337 	ebitmap_node_t *cnode;
   1338 
   1339 	cur = list;
   1340 	tail = *dst;
   1341 	while (tail && tail->next) {
   1342 		tail = tail->next;
   1343 	}
   1344 	while (cur) {
   1345 		if ((new_rule =
   1346 		     (role_trans_rule_t *) malloc(sizeof(role_trans_rule_t))) ==
   1347 		    NULL) {
   1348 			goto cleanup;
   1349 		}
   1350 		role_trans_rule_init(new_rule);
   1351 
   1352 		if (role_set_or_convert
   1353 		    (&cur->roles, &new_rule->roles, module, state)
   1354 		    || type_set_or_convert(&cur->types, &new_rule->types,
   1355 					   module, state)) {
   1356 			goto cleanup;
   1357 		}
   1358 
   1359 		ebitmap_for_each_bit(&cur->classes, cnode, i) {
   1360 			if (ebitmap_node_get_bit(cnode, i)) {
   1361 				assert(module->map[SYM_CLASSES][i]);
   1362 				if (ebitmap_set_bit(&new_rule->classes,
   1363 						    module->
   1364 						    map[SYM_CLASSES][i] - 1,
   1365 						    1)) {
   1366 					goto cleanup;
   1367 				}
   1368 			}
   1369 		}
   1370 
   1371 		new_rule->new_role = module->map[SYM_ROLES][cur->new_role - 1];
   1372 
   1373 		if (*dst == NULL) {
   1374 			*dst = new_rule;
   1375 		} else {
   1376 			tail->next = new_rule;
   1377 		}
   1378 		tail = new_rule;
   1379 		cur = cur->next;
   1380 	}
   1381 	return 0;
   1382       cleanup:
   1383 	ERR(state->handle, "Out of memory!");
   1384 	role_trans_rule_list_destroy(new_rule);
   1385 	return -1;
   1386 }
   1387 
   1388 static int copy_role_allow_list(role_allow_rule_t * list,
   1389 				role_allow_rule_t ** dst,
   1390 				policy_module_t * module, link_state_t * state)
   1391 {
   1392 	role_allow_rule_t *cur, *new_rule = NULL, *tail;
   1393 
   1394 	cur = list;
   1395 	tail = *dst;
   1396 	while (tail && tail->next) {
   1397 		tail = tail->next;
   1398 	}
   1399 
   1400 	while (cur) {
   1401 		if ((new_rule =
   1402 		     (role_allow_rule_t *) malloc(sizeof(role_allow_rule_t))) ==
   1403 		    NULL) {
   1404 			goto cleanup;
   1405 		}
   1406 		role_allow_rule_init(new_rule);
   1407 
   1408 		if (role_set_or_convert
   1409 		    (&cur->roles, &new_rule->roles, module, state)
   1410 		    || role_set_or_convert(&cur->new_roles,
   1411 					   &new_rule->new_roles, module,
   1412 					   state)) {
   1413 			goto cleanup;
   1414 		}
   1415 		if (*dst == NULL) {
   1416 			*dst = new_rule;
   1417 		} else {
   1418 			tail->next = new_rule;
   1419 		}
   1420 		tail = new_rule;
   1421 		cur = cur->next;
   1422 	}
   1423 	return 0;
   1424       cleanup:
   1425 	ERR(state->handle, "Out of memory!");
   1426 	role_allow_rule_list_destroy(new_rule);
   1427 	return -1;
   1428 }
   1429 
   1430 static int copy_filename_trans_list(filename_trans_rule_t * list,
   1431 				    filename_trans_rule_t ** dst,
   1432 				    policy_module_t * module,
   1433 				    link_state_t * state)
   1434 {
   1435 	filename_trans_rule_t *cur, *new_rule, *tail;
   1436 
   1437 	cur = list;
   1438 	tail = *dst;
   1439 	while (tail && tail->next)
   1440 		tail = tail->next;
   1441 
   1442 	while (cur) {
   1443 		new_rule = malloc(sizeof(*new_rule));
   1444 		if (!new_rule)
   1445 			goto err;
   1446 
   1447 		filename_trans_rule_init(new_rule);
   1448 
   1449 		if (*dst == NULL)
   1450 			*dst = new_rule;
   1451 		else
   1452 			tail->next = new_rule;
   1453 		tail = new_rule;
   1454 
   1455 		new_rule->name = strdup(cur->name);
   1456 		if (!new_rule->name)
   1457 			goto err;
   1458 
   1459 		if (type_set_or_convert(&cur->stypes, &new_rule->stypes, module, state) ||
   1460 		    type_set_or_convert(&cur->ttypes, &new_rule->ttypes, module, state))
   1461 			goto err;
   1462 
   1463 		new_rule->tclass = module->map[SYM_CLASSES][cur->tclass - 1];
   1464 		new_rule->otype = module->map[SYM_TYPES][cur->otype - 1];
   1465 
   1466 		cur = cur->next;
   1467 	}
   1468 	return 0;
   1469 err:
   1470 	ERR(state->handle, "Out of memory!");
   1471 	return -1;
   1472 }
   1473 
   1474 static int copy_range_trans_list(range_trans_rule_t * rules,
   1475 				 range_trans_rule_t ** dst,
   1476 				 policy_module_t * mod, link_state_t * state)
   1477 {
   1478 	range_trans_rule_t *rule, *new_rule = NULL;
   1479 	unsigned int i;
   1480 	ebitmap_node_t *cnode;
   1481 
   1482 	for (rule = rules; rule; rule = rule->next) {
   1483 		new_rule =
   1484 		    (range_trans_rule_t *) malloc(sizeof(range_trans_rule_t));
   1485 		if (!new_rule)
   1486 			goto cleanup;
   1487 
   1488 		range_trans_rule_init(new_rule);
   1489 
   1490 		new_rule->next = *dst;
   1491 		*dst = new_rule;
   1492 
   1493 		if (type_set_convert(&rule->stypes, &new_rule->stypes,
   1494 				     mod, state))
   1495 			goto cleanup;
   1496 
   1497 		if (type_set_convert(&rule->ttypes, &new_rule->ttypes,
   1498 				     mod, state))
   1499 			goto cleanup;
   1500 
   1501 		ebitmap_for_each_bit(&rule->tclasses, cnode, i) {
   1502 			if (ebitmap_node_get_bit(cnode, i)) {
   1503 				assert(mod->map[SYM_CLASSES][i]);
   1504 				if (ebitmap_set_bit
   1505 				    (&new_rule->tclasses,
   1506 				     mod->map[SYM_CLASSES][i] - 1, 1)) {
   1507 					goto cleanup;
   1508 				}
   1509 			}
   1510 		}
   1511 
   1512 		if (mls_range_convert(&rule->trange, &new_rule->trange, mod, state))
   1513 			goto cleanup;
   1514 	}
   1515 	return 0;
   1516 
   1517       cleanup:
   1518 	ERR(state->handle, "Out of memory!");
   1519 	range_trans_rule_list_destroy(new_rule);
   1520 	return -1;
   1521 }
   1522 
   1523 static int copy_cond_list(cond_node_t * list, cond_node_t ** dst,
   1524 			  policy_module_t * module, link_state_t * state)
   1525 {
   1526 	unsigned i;
   1527 	cond_node_t *cur, *new_node = NULL, *tail;
   1528 	cond_expr_t *cur_expr;
   1529 	tail = *dst;
   1530 	while (tail && tail->next)
   1531 		tail = tail->next;
   1532 
   1533 	cur = list;
   1534 	while (cur) {
   1535 		new_node = (cond_node_t *) malloc(sizeof(cond_node_t));
   1536 		if (!new_node) {
   1537 			goto cleanup;
   1538 		}
   1539 		memset(new_node, 0, sizeof(cond_node_t));
   1540 
   1541 		new_node->cur_state = cur->cur_state;
   1542 		new_node->expr = cond_copy_expr(cur->expr);
   1543 		if (!new_node->expr)
   1544 			goto cleanup;
   1545 		/* go back through and remap the expression */
   1546 		for (cur_expr = new_node->expr; cur_expr != NULL;
   1547 		     cur_expr = cur_expr->next) {
   1548 			/* expression nodes don't have a bool value of 0 - don't map them */
   1549 			if (cur_expr->expr_type != COND_BOOL)
   1550 				continue;
   1551 			assert(module->map[SYM_BOOLS][cur_expr->bool - 1] != 0);
   1552 			cur_expr->bool =
   1553 			    module->map[SYM_BOOLS][cur_expr->bool - 1];
   1554 		}
   1555 		new_node->nbools = cur->nbools;
   1556 		/* FIXME should COND_MAX_BOOLS be used here? */
   1557 		for (i = 0; i < min(cur->nbools, COND_MAX_BOOLS); i++) {
   1558 			uint32_t remapped_id =
   1559 			    module->map[SYM_BOOLS][cur->bool_ids[i] - 1];
   1560 			assert(remapped_id != 0);
   1561 			new_node->bool_ids[i] = remapped_id;
   1562 		}
   1563 		new_node->expr_pre_comp = cur->expr_pre_comp;
   1564 
   1565 		if (copy_avrule_list
   1566 		    (cur->avtrue_list, &new_node->avtrue_list, module, state)
   1567 		    || copy_avrule_list(cur->avfalse_list,
   1568 					&new_node->avfalse_list, module,
   1569 					state)) {
   1570 			goto cleanup;
   1571 		}
   1572 
   1573 		if (*dst == NULL) {
   1574 			*dst = new_node;
   1575 		} else {
   1576 			tail->next = new_node;
   1577 		}
   1578 		tail = new_node;
   1579 		cur = cur->next;
   1580 	}
   1581 	return 0;
   1582       cleanup:
   1583 	ERR(state->handle, "Out of memory!");
   1584 	cond_node_destroy(new_node);
   1585 	free(new_node);
   1586 	return -1;
   1587 
   1588 }
   1589 
   1590 /*********** functions that copy avrule_decls from module to base ***********/
   1591 
   1592 static int copy_identifiers(link_state_t * state, symtab_t * src_symtab,
   1593 			    avrule_decl_t * dest_decl)
   1594 {
   1595 	int i, ret;
   1596 
   1597 	state->dest_decl = dest_decl;
   1598 	for (i = 0; i < SYM_NUM; i++) {
   1599 		if (copy_callback_f[i] != NULL) {
   1600 			ret =
   1601 			    hashtab_map(src_symtab[i].table, copy_callback_f[i],
   1602 					state);
   1603 			if (ret) {
   1604 				return ret;
   1605 			}
   1606 		}
   1607 	}
   1608 
   1609 	if (hashtab_map(src_symtab[SYM_TYPES].table,
   1610 			type_bounds_copy_callback, state))
   1611 		return -1;
   1612 
   1613 	if (hashtab_map(src_symtab[SYM_TYPES].table,
   1614 			alias_copy_callback, state))
   1615 		return -1;
   1616 
   1617 	if (hashtab_map(src_symtab[SYM_ROLES].table,
   1618 			role_bounds_copy_callback, state))
   1619 		return -1;
   1620 
   1621 	if (hashtab_map(src_symtab[SYM_USERS].table,
   1622 			user_bounds_copy_callback, state))
   1623 		return -1;
   1624 
   1625 	/* then fix bitmaps associated with those newly copied identifiers */
   1626 	for (i = 0; i < SYM_NUM; i++) {
   1627 		if (fix_callback_f[i] != NULL &&
   1628 		    hashtab_map(src_symtab[i].table, fix_callback_f[i],
   1629 				state)) {
   1630 			return -1;
   1631 		}
   1632 	}
   1633 	return 0;
   1634 }
   1635 
   1636 static int copy_scope_index(scope_index_t * src, scope_index_t * dest,
   1637 			    policy_module_t * module, link_state_t * state)
   1638 {
   1639 	unsigned int i, j;
   1640 	uint32_t largest_mapped_class_value = 0;
   1641 	ebitmap_node_t *node;
   1642 	/* copy the scoping information for this avrule decl block */
   1643 	for (i = 0; i < SYM_NUM; i++) {
   1644 		ebitmap_t *srcmap = src->scope + i;
   1645 		ebitmap_t *destmap = dest->scope + i;
   1646 		if (copy_callback_f[i] == NULL) {
   1647 			continue;
   1648 		}
   1649 		ebitmap_for_each_bit(srcmap, node, j) {
   1650 			if (ebitmap_node_get_bit(node, j)) {
   1651 				assert(module->map[i][j] != 0);
   1652 				if (ebitmap_set_bit
   1653 				    (destmap, module->map[i][j] - 1, 1) != 0) {
   1654 
   1655 					goto cleanup;
   1656 				}
   1657 				if (i == SYM_CLASSES &&
   1658 				    largest_mapped_class_value <
   1659 				    module->map[SYM_CLASSES][j]) {
   1660 					largest_mapped_class_value =
   1661 					    module->map[SYM_CLASSES][j];
   1662 				}
   1663 			}
   1664 		}
   1665 	}
   1666 
   1667 	/* next copy the enabled permissions data  */
   1668 	if ((dest->class_perms_map = malloc(largest_mapped_class_value *
   1669 					    sizeof(*dest->class_perms_map))) ==
   1670 	    NULL) {
   1671 		goto cleanup;
   1672 	}
   1673 	for (i = 0; i < largest_mapped_class_value; i++) {
   1674 		ebitmap_init(dest->class_perms_map + i);
   1675 	}
   1676 	dest->class_perms_len = largest_mapped_class_value;
   1677 	for (i = 0; i < src->class_perms_len; i++) {
   1678 		ebitmap_t *srcmap = src->class_perms_map + i;
   1679 		ebitmap_t *destmap =
   1680 		    dest->class_perms_map + module->map[SYM_CLASSES][i] - 1;
   1681 		ebitmap_for_each_bit(srcmap, node, j) {
   1682 			if (ebitmap_node_get_bit(node, j) &&
   1683 			    ebitmap_set_bit(destmap, module->perm_map[i][j] - 1,
   1684 					    1)) {
   1685 				goto cleanup;
   1686 			}
   1687 		}
   1688 	}
   1689 
   1690 	return 0;
   1691 
   1692       cleanup:
   1693 	ERR(state->handle, "Out of memory!");
   1694 	return -1;
   1695 }
   1696 
   1697 static int copy_avrule_decl(link_state_t * state, policy_module_t * module,
   1698 			    avrule_decl_t * src_decl, avrule_decl_t * dest_decl)
   1699 {
   1700 	int ret;
   1701 
   1702 	/* copy all of the RBAC and TE rules */
   1703 	if (copy_avrule_list
   1704 	    (src_decl->avrules, &dest_decl->avrules, module, state) == -1
   1705 	    || copy_role_trans_list(src_decl->role_tr_rules,
   1706 				    &dest_decl->role_tr_rules, module,
   1707 				    state) == -1
   1708 	    || copy_role_allow_list(src_decl->role_allow_rules,
   1709 				    &dest_decl->role_allow_rules, module,
   1710 				    state) == -1
   1711 	    || copy_cond_list(src_decl->cond_list, &dest_decl->cond_list,
   1712 			      module, state) == -1) {
   1713 		return -1;
   1714 	}
   1715 
   1716 	if (copy_filename_trans_list(src_decl->filename_trans_rules,
   1717 				     &dest_decl->filename_trans_rules,
   1718 				     module, state))
   1719 		return -1;
   1720 
   1721 	if (copy_range_trans_list(src_decl->range_tr_rules,
   1722 				  &dest_decl->range_tr_rules, module, state))
   1723 		return -1;
   1724 
   1725 	/* finally copy any identifiers local to this declaration */
   1726 	ret = copy_identifiers(state, src_decl->symtab, dest_decl);
   1727 	if (ret < 0) {
   1728 		return ret;
   1729 	}
   1730 
   1731 	/* then copy required and declared scope indices here */
   1732 	if (copy_scope_index(&src_decl->required, &dest_decl->required,
   1733 			     module, state) == -1 ||
   1734 	    copy_scope_index(&src_decl->declared, &dest_decl->declared,
   1735 			     module, state) == -1) {
   1736 		return -1;
   1737 	}
   1738 
   1739 	return 0;
   1740 }
   1741 
   1742 static int copy_avrule_block(link_state_t * state, policy_module_t * module,
   1743 			     avrule_block_t * block)
   1744 {
   1745 	avrule_block_t *new_block = avrule_block_create();
   1746 	avrule_decl_t *decl, *last_decl = NULL;
   1747 	int ret;
   1748 
   1749 	if (new_block == NULL) {
   1750 		ERR(state->handle, "Out of memory!");
   1751 		ret = -1;
   1752 		goto cleanup;
   1753 	}
   1754 
   1755 	new_block->flags = block->flags;
   1756 
   1757 	for (decl = block->branch_list; decl != NULL; decl = decl->next) {
   1758 		avrule_decl_t *new_decl =
   1759 		    avrule_decl_create(state->next_decl_id);
   1760 		if (new_decl == NULL) {
   1761 			ERR(state->handle, "Out of memory!");
   1762 			ret = -1;
   1763 			goto cleanup;
   1764 		}
   1765 
   1766 		if (module->policy->name != NULL) {
   1767 			new_decl->module_name = strdup(module->policy->name);
   1768 			if (new_decl->module_name == NULL) {
   1769 				ERR(state->handle, "Out of memory\n");
   1770 				avrule_decl_destroy(new_decl);
   1771 				ret = -1;
   1772 				goto cleanup;
   1773 			}
   1774 		}
   1775 
   1776 		if (last_decl == NULL) {
   1777 			new_block->branch_list = new_decl;
   1778 		} else {
   1779 			last_decl->next = new_decl;
   1780 		}
   1781 		last_decl = new_decl;
   1782 		state->base->decl_val_to_struct[state->next_decl_id - 1] =
   1783 		    new_decl;
   1784 		state->decl_to_mod[state->next_decl_id] = module->policy;
   1785 
   1786 		module->avdecl_map[decl->decl_id] = new_decl->decl_id;
   1787 
   1788 		ret = copy_avrule_decl(state, module, decl, new_decl);
   1789 		if (ret) {
   1790 			avrule_decl_destroy(new_decl);
   1791 			goto cleanup;
   1792 		}
   1793 
   1794 		state->next_decl_id++;
   1795 	}
   1796 	state->last_avrule_block->next = new_block;
   1797 	state->last_avrule_block = new_block;
   1798 	return 0;
   1799 
   1800       cleanup:
   1801 	avrule_block_list_destroy(new_block);
   1802 	return ret;
   1803 }
   1804 
   1805 static int scope_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
   1806 			       void *data)
   1807 {
   1808 	unsigned int i;
   1809 	int ret;
   1810 	char *id = key, *new_id = NULL;
   1811 	scope_datum_t *scope, *base_scope;
   1812 	link_state_t *state = (link_state_t *) data;
   1813 	uint32_t symbol_num = state->symbol_num;
   1814 	uint32_t *avdecl_map = state->cur->avdecl_map;
   1815 
   1816 	scope = (scope_datum_t *) datum;
   1817 
   1818 	/* check if the base already has a scope entry */
   1819 	base_scope = hashtab_search(state->base->scope[symbol_num].table, id);
   1820 	if (base_scope == NULL) {
   1821 		scope_datum_t *new_scope;
   1822 		if ((new_id = strdup(id)) == NULL) {
   1823 			goto cleanup;
   1824 		}
   1825 
   1826 		if ((new_scope =
   1827 		     (scope_datum_t *) calloc(1, sizeof(*new_scope))) == NULL) {
   1828 			free(new_id);
   1829 			goto cleanup;
   1830 		}
   1831 		ret = hashtab_insert(state->base->scope[symbol_num].table,
   1832 				     (hashtab_key_t) new_id,
   1833 				     (hashtab_datum_t) new_scope);
   1834 		if (ret) {
   1835 			free(new_id);
   1836 			free(new_scope);
   1837 			goto cleanup;
   1838 		}
   1839 		new_scope->scope = SCOPE_REQ;	/* this is reset further down */
   1840 		base_scope = new_scope;
   1841 	}
   1842 	if (base_scope->scope == SCOPE_REQ && scope->scope == SCOPE_DECL) {
   1843 		/* this module declared symbol, so overwrite the old
   1844 		 * list with the new decl ids */
   1845 		base_scope->scope = SCOPE_DECL;
   1846 		free(base_scope->decl_ids);
   1847 		base_scope->decl_ids = NULL;
   1848 		base_scope->decl_ids_len = 0;
   1849 		for (i = 0; i < scope->decl_ids_len; i++) {
   1850 			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
   1851 				       &base_scope->decl_ids_len,
   1852 				       &base_scope->decl_ids) == -1) {
   1853 				goto cleanup;
   1854 			}
   1855 		}
   1856 	} else if (base_scope->scope == SCOPE_DECL && scope->scope == SCOPE_REQ) {
   1857 		/* this module depended on a symbol that now exists,
   1858 		 * so don't do anything */
   1859 	} else if (base_scope->scope == SCOPE_REQ && scope->scope == SCOPE_REQ) {
   1860 		/* symbol is still required, so add to the list */
   1861 		for (i = 0; i < scope->decl_ids_len; i++) {
   1862 			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
   1863 				       &base_scope->decl_ids_len,
   1864 				       &base_scope->decl_ids) == -1) {
   1865 				goto cleanup;
   1866 			}
   1867 		}
   1868 	} else {
   1869 		/* this module declared a symbol, and it was already
   1870 		 * declared.  only roles and users may be multiply
   1871 		 * declared; for all others this is an error. */
   1872 		if (symbol_num != SYM_ROLES && symbol_num != SYM_USERS) {
   1873 			ERR(state->handle,
   1874 			    "%s: Duplicate declaration in module: %s %s",
   1875 			    state->cur_mod_name,
   1876 			    symtab_names[state->symbol_num], id);
   1877 			return -1;
   1878 		}
   1879 		for (i = 0; i < scope->decl_ids_len; i++) {
   1880 			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
   1881 				       &base_scope->decl_ids_len,
   1882 				       &base_scope->decl_ids) == -1) {
   1883 				goto cleanup;
   1884 			}
   1885 		}
   1886 	}
   1887 	return 0;
   1888 
   1889       cleanup:
   1890 	ERR(state->handle, "Out of memory!");
   1891 	return -1;
   1892 }
   1893 
   1894 /* Copy a module over to a base, remapping all values within.  After
   1895  * all identifiers and rules are done, copy the scoping information.
   1896  * This is when it checks for duplicate declarations. */
   1897 static int copy_module(link_state_t * state, policy_module_t * module)
   1898 {
   1899 	int i, ret;
   1900 	avrule_block_t *cur;
   1901 	state->cur = module;
   1902 	state->cur_mod_name = module->policy->name;
   1903 
   1904 	/* first copy all of the identifiers */
   1905 	ret = copy_identifiers(state, module->policy->symtab, NULL);
   1906 	if (ret) {
   1907 		return ret;
   1908 	}
   1909 
   1910 	/* next copy all of the avrule blocks */
   1911 	for (cur = module->policy->global; cur != NULL; cur = cur->next) {
   1912 		ret = copy_avrule_block(state, module, cur);
   1913 		if (ret) {
   1914 			return ret;
   1915 		}
   1916 	}
   1917 
   1918 	/* then copy the scoping tables */
   1919 	for (i = 0; i < SYM_NUM; i++) {
   1920 		state->symbol_num = i;
   1921 		if (hashtab_map
   1922 		    (module->policy->scope[i].table, scope_copy_callback,
   1923 		     state)) {
   1924 			return -1;
   1925 		}
   1926 	}
   1927 
   1928 	return 0;
   1929 }
   1930 
   1931 /***** functions that check requirements and enable blocks in a module ******/
   1932 
   1933 /* borrowed from checkpolicy.c */
   1934 
   1935 struct find_perm_arg {
   1936 	unsigned int valuep;
   1937 	hashtab_key_t key;
   1938 };
   1939 
   1940 static int find_perm(hashtab_key_t key, hashtab_datum_t datum, void *varg)
   1941 {
   1942 
   1943 	struct find_perm_arg *arg = varg;
   1944 
   1945 	perm_datum_t *perdatum = (perm_datum_t *) datum;
   1946 	if (arg->valuep == perdatum->s.value) {
   1947 		arg->key = key;
   1948 		return 1;
   1949 	}
   1950 
   1951 	return 0;
   1952 }
   1953 
   1954 /* Check if the requirements are met for a single declaration.  If all
   1955  * are met return 1.  For the first requirement found to be missing,
   1956  * if 'missing_sym_num' and 'missing_value' are both not NULL then
   1957  * write to them the symbol number and value for the missing
   1958  * declaration.  Then return 0 to indicate a missing declaration.
   1959  * Note that if a declaration had no requirement at all (e.g., an ELSE
   1960  * block) this returns 1. */
   1961 static int is_decl_requires_met(link_state_t * state,
   1962 				avrule_decl_t * decl,
   1963 				struct missing_requirement *req)
   1964 {
   1965 	/* (This algorithm is very unoptimized.  It performs many
   1966 	 * redundant checks.  A very obvious improvement is to cache
   1967 	 * which symbols have been verified, so that they do not need
   1968 	 * to be re-checked.) */
   1969 	unsigned int i, j;
   1970 	ebitmap_t *bitmap;
   1971 	char *id, *perm_id;
   1972 	policydb_t *pol = state->base;
   1973 	ebitmap_node_t *node;
   1974 
   1975 	/* check that all symbols have been satisfied */
   1976 	for (i = 0; i < SYM_NUM; i++) {
   1977 		if (i == SYM_CLASSES) {
   1978 			/* classes will be checked during permissions
   1979 			 * checking phase below */
   1980 			continue;
   1981 		}
   1982 		bitmap = &decl->required.scope[i];
   1983 		ebitmap_for_each_bit(bitmap, node, j) {
   1984 			if (!ebitmap_node_get_bit(node, j)) {
   1985 				continue;
   1986 			}
   1987 
   1988 			/* check base's scope table */
   1989 			id = pol->sym_val_to_name[i][j];
   1990 			if (!is_id_enabled(id, state->base, i)) {
   1991 				/* this symbol was not found */
   1992 				if (req != NULL) {
   1993 					req->symbol_type = i;
   1994 					req->symbol_value = j + 1;
   1995 				}
   1996 				return 0;
   1997 			}
   1998 		}
   1999 	}
   2000 	/* check that all classes and permissions have been satisfied */
   2001 	for (i = 0; i < decl->required.class_perms_len; i++) {
   2002 
   2003 		bitmap = decl->required.class_perms_map + i;
   2004 		ebitmap_for_each_bit(bitmap, node, j) {
   2005 			struct find_perm_arg fparg;
   2006 			class_datum_t *cladatum;
   2007 			uint32_t perm_value = j + 1;
   2008 			scope_datum_t *scope;
   2009 
   2010 			if (!ebitmap_node_get_bit(node, j)) {
   2011 				continue;
   2012 			}
   2013 			id = pol->p_class_val_to_name[i];
   2014 			cladatum = pol->class_val_to_struct[i];
   2015 
   2016 			scope =
   2017 			    hashtab_search(state->base->p_classes_scope.table,
   2018 					   id);
   2019 			if (scope == NULL) {
   2020 				ERR(state->handle,
   2021 				    "Could not find scope information for class %s",
   2022 				    id);
   2023 				return -1;
   2024 			}
   2025 
   2026 			fparg.valuep = perm_value;
   2027 			fparg.key = NULL;
   2028 
   2029 			hashtab_map(cladatum->permissions.table, find_perm,
   2030 				    &fparg);
   2031 			if (fparg.key == NULL && cladatum->comdatum != NULL)
   2032 				hashtab_map(cladatum->comdatum->permissions.
   2033 					    table, find_perm, &fparg);
   2034 			perm_id = fparg.key;
   2035 
   2036 			assert(perm_id != NULL);
   2037 			if (!is_perm_enabled(id, perm_id, state->base)) {
   2038 				if (req != NULL) {
   2039 					req->symbol_type = SYM_CLASSES;
   2040 					req->symbol_value = i + 1;
   2041 					req->perm_value = perm_value;
   2042 				}
   2043 				return 0;
   2044 			}
   2045 		}
   2046 	}
   2047 
   2048 	/* all requirements have been met */
   2049 	return 1;
   2050 }
   2051 
   2052 static int debug_requirements(link_state_t * state, policydb_t * p)
   2053 {
   2054 	int ret;
   2055 	avrule_block_t *cur;
   2056 	missing_requirement_t req;
   2057 
   2058 	for (cur = p->global; cur != NULL; cur = cur->next) {
   2059 		if (cur->enabled != NULL)
   2060 			continue;
   2061 
   2062 		ret = is_decl_requires_met(state, cur->branch_list, &req);
   2063 		if (ret < 0) {
   2064 			return ret;
   2065 		} else if (ret == 0) {
   2066 			char *mod_name = cur->branch_list->module_name ?
   2067 			    cur->branch_list->module_name : "BASE";
   2068 			if (req.symbol_type == SYM_CLASSES) {
   2069 
   2070 				struct find_perm_arg fparg;
   2071 
   2072 				class_datum_t *cladatum;
   2073 				cladatum =
   2074 				    p->class_val_to_struct[req.symbol_value -
   2075 							   1];
   2076 
   2077 				fparg.valuep = req.perm_value;
   2078 				fparg.key = NULL;
   2079 				hashtab_map(cladatum->permissions.table,
   2080 					    find_perm, &fparg);
   2081 
   2082 				if (cur->flags & AVRULE_OPTIONAL) {
   2083 					ERR(state->handle,
   2084 					    "%s[%d]'s optional requirements were not met: class %s, permission %s",
   2085 					    mod_name, cur->branch_list->decl_id,
   2086 					    p->p_class_val_to_name[req.
   2087 								   symbol_value
   2088 								   - 1],
   2089 					    fparg.key);
   2090 				} else {
   2091 					ERR(state->handle,
   2092 					    "%s[%d]'s global requirements were not met: class %s, permission %s",
   2093 					    mod_name, cur->branch_list->decl_id,
   2094 					    p->p_class_val_to_name[req.
   2095 								   symbol_value
   2096 								   - 1],
   2097 					    fparg.key);
   2098 				}
   2099 			} else {
   2100 				if (cur->flags & AVRULE_OPTIONAL) {
   2101 					ERR(state->handle,
   2102 					    "%s[%d]'s optional requirements were not met: %s %s",
   2103 					    mod_name, cur->branch_list->decl_id,
   2104 					    symtab_names[req.symbol_type],
   2105 					    p->sym_val_to_name[req.
   2106 							       symbol_type][req.
   2107 									    symbol_value
   2108 									    -
   2109 									    1]);
   2110 				} else {
   2111 					ERR(state->handle,
   2112 					    "%s[%d]'s global requirements were not met: %s %s",
   2113 					    mod_name, cur->branch_list->decl_id,
   2114 					    symtab_names[req.symbol_type],
   2115 					    p->sym_val_to_name[req.
   2116 							       symbol_type][req.
   2117 									    symbol_value
   2118 									    -
   2119 									    1]);
   2120 				}
   2121 			}
   2122 		}
   2123 	}
   2124 	return 0;
   2125 }
   2126 
   2127 static void print_missing_requirements(link_state_t * state,
   2128 				       avrule_block_t * cur,
   2129 				       missing_requirement_t * req)
   2130 {
   2131 	policydb_t *p = state->base;
   2132 	char *mod_name = cur->branch_list->module_name ?
   2133 	    cur->branch_list->module_name : "BASE";
   2134 
   2135 	if (req->symbol_type == SYM_CLASSES) {
   2136 
   2137 		struct find_perm_arg fparg;
   2138 
   2139 		class_datum_t *cladatum;
   2140 		cladatum = p->class_val_to_struct[req->symbol_value - 1];
   2141 
   2142 		fparg.valuep = req->perm_value;
   2143 		fparg.key = NULL;
   2144 		hashtab_map(cladatum->permissions.table, find_perm, &fparg);
   2145 
   2146 		ERR(state->handle,
   2147 		    "%s's global requirements were not met: class %s, permission %s",
   2148 		    mod_name,
   2149 		    p->p_class_val_to_name[req->symbol_value - 1], fparg.key);
   2150 	} else {
   2151 		ERR(state->handle,
   2152 		    "%s's global requirements were not met: %s %s",
   2153 		    mod_name,
   2154 		    symtab_names[req->symbol_type],
   2155 		    p->sym_val_to_name[req->symbol_type][req->symbol_value -
   2156 							 1]);
   2157 	}
   2158 }
   2159 
   2160 /* Enable all of the avrule_decl blocks for the policy. This simple
   2161  * algorithm is the following:
   2162  *
   2163  * 1) Enable all of the non-else avrule_decls for all blocks.
   2164  * 2) Iterate through the non-else decls looking for decls whose requirements
   2165  *    are not met.
   2166  *    2a) If the decl is non-optional, return immediately with an error.
   2167  *    2b) If the decl is optional, disable the block and mark changed = 1
   2168  * 3) If changed == 1 goto 2.
   2169  * 4) Iterate through all blocks looking for those that have no enabled
   2170  *    decl. If the block has an else decl, enable.
   2171  *
   2172  * This will correctly handle all dependencies, including mutual and
   2173  * cicular. The only downside is that it is slow.
   2174  */
   2175 static int enable_avrules(link_state_t * state, policydb_t * pol)
   2176 {
   2177 	int changed = 1;
   2178 	avrule_block_t *block;
   2179 	avrule_decl_t *decl;
   2180 	missing_requirement_t req;
   2181 	int ret = 0, rc;
   2182 
   2183 	if (state->verbose) {
   2184 		INFO(state->handle, "Determining which avrules to enable.");
   2185 	}
   2186 
   2187 	/* 1) enable all of the non-else blocks */
   2188 	for (block = pol->global; block != NULL; block = block->next) {
   2189 		block->enabled = block->branch_list;
   2190 		block->enabled->enabled = 1;
   2191 		for (decl = block->branch_list->next; decl != NULL;
   2192 		     decl = decl->next)
   2193 			decl->enabled = 0;
   2194 	}
   2195 
   2196 	/* 2) Iterate */
   2197 	while (changed) {
   2198 		changed = 0;
   2199 		for (block = pol->global; block != NULL; block = block->next) {
   2200 			if (block->enabled == NULL) {
   2201 				continue;
   2202 			}
   2203 			decl = block->branch_list;
   2204 			if (state->verbose) {
   2205 				char *mod_name = decl->module_name ?
   2206 				    decl->module_name : "BASE";
   2207 				INFO(state->handle, "check module %s decl %d\n",
   2208 				     mod_name, decl->decl_id);
   2209 			}
   2210 			rc = is_decl_requires_met(state, decl, &req);
   2211 			if (rc < 0) {
   2212 				ret = SEPOL_ERR;
   2213 				goto out;
   2214 			} else if (rc == 0) {
   2215 				decl->enabled = 0;
   2216 				block->enabled = NULL;
   2217 				changed = 1;
   2218 				if (!(block->flags & AVRULE_OPTIONAL)) {
   2219 					print_missing_requirements(state, block,
   2220 								   &req);
   2221 					ret = SEPOL_EREQ;
   2222 					goto out;
   2223 				}
   2224 			}
   2225 		}
   2226 	}
   2227 
   2228 	/* 4) else handling
   2229 	 *
   2230 	 * Iterate through all of the blocks skipping the first (which is the
   2231 	 * global block, is required to be present, and cannot have an else).
   2232 	 * If the block is disabled and has an else decl, enable that.
   2233 	 *
   2234 	 * This code assumes that the second block in the branch list is the else
   2235 	 * block. This is currently supported by the compiler.
   2236 	 */
   2237 	for (block = pol->global->next; block != NULL; block = block->next) {
   2238 		if (block->enabled == NULL) {
   2239 			if (block->branch_list->next != NULL) {
   2240 				block->enabled = block->branch_list->next;
   2241 				block->branch_list->next->enabled = 1;
   2242 			}
   2243 		}
   2244 	}
   2245 
   2246       out:
   2247 	if (state->verbose)
   2248 		debug_requirements(state, pol);
   2249 
   2250 	return ret;
   2251 }
   2252 
   2253 /*********** the main linking functions ***********/
   2254 
   2255 /* Given a module's policy, normalize all conditional expressions
   2256  * within.  Return 0 on success, -1 on error. */
   2257 static int cond_normalize(policydb_t * p)
   2258 {
   2259 	avrule_block_t *block;
   2260 	for (block = p->global; block != NULL; block = block->next) {
   2261 		avrule_decl_t *decl;
   2262 		for (decl = block->branch_list; decl != NULL; decl = decl->next) {
   2263 			cond_list_t *cond = decl->cond_list;
   2264 			while (cond) {
   2265 				if (cond_normalize_expr(p, cond) < 0)
   2266 					return -1;
   2267 				cond = cond->next;
   2268 			}
   2269 		}
   2270 	}
   2271 	return 0;
   2272 }
   2273 
   2274 /* Allocate space for the various remapping arrays. */
   2275 static int prepare_module(link_state_t * state, policy_module_t * module)
   2276 {
   2277 	int i;
   2278 	uint32_t items, num_decls = 0;
   2279 	avrule_block_t *cur;
   2280 
   2281 	/* allocate the maps */
   2282 	for (i = 0; i < SYM_NUM; i++) {
   2283 		items = module->policy->symtab[i].nprim;
   2284 		if ((module->map[i] =
   2285 		     (uint32_t *) calloc(items,
   2286 					 sizeof(*module->map[i]))) == NULL) {
   2287 			ERR(state->handle, "Out of memory!");
   2288 			return -1;
   2289 		}
   2290 	}
   2291 
   2292 	/* allocate the permissions remap here */
   2293 	items = module->policy->p_classes.nprim;
   2294 	if ((module->perm_map_len =
   2295 	     calloc(items, sizeof(*module->perm_map_len))) == NULL) {
   2296 		ERR(state->handle, "Out of memory!");
   2297 		return -1;
   2298 	}
   2299 	if ((module->perm_map =
   2300 	     calloc(items, sizeof(*module->perm_map))) == NULL) {
   2301 		ERR(state->handle, "Out of memory!");
   2302 		return -1;
   2303 	}
   2304 
   2305 	/* allocate a map for avrule_decls */
   2306 	for (cur = module->policy->global; cur != NULL; cur = cur->next) {
   2307 		avrule_decl_t *decl;
   2308 		for (decl = cur->branch_list; decl != NULL; decl = decl->next) {
   2309 			if (decl->decl_id > num_decls) {
   2310 				num_decls = decl->decl_id;
   2311 			}
   2312 		}
   2313 	}
   2314 	num_decls++;
   2315 	if ((module->avdecl_map = calloc(num_decls, sizeof(uint32_t))) == NULL) {
   2316 		ERR(state->handle, "Out of memory!");
   2317 		return -1;
   2318 	}
   2319 	module->num_decls = num_decls;
   2320 
   2321 	/* normalize conditionals within */
   2322 	if (cond_normalize(module->policy) < 0) {
   2323 		ERR(state->handle,
   2324 		    "Error while normalizing conditionals within the module %s.",
   2325 		    module->policy->name);
   2326 		return -1;
   2327 	}
   2328 	return 0;
   2329 }
   2330 
   2331 static int prepare_base(link_state_t * state, uint32_t num_mod_decls)
   2332 {
   2333 	avrule_block_t *cur = state->base->global;
   2334 	assert(cur != NULL);
   2335 	state->next_decl_id = 0;
   2336 
   2337 	/* iterate through all of the declarations in the base, to
   2338 	   determine what the next decl_id should be */
   2339 	while (cur != NULL) {
   2340 		avrule_decl_t *decl;
   2341 		for (decl = cur->branch_list; decl != NULL; decl = decl->next) {
   2342 			if (decl->decl_id > state->next_decl_id) {
   2343 				state->next_decl_id = decl->decl_id;
   2344 			}
   2345 		}
   2346 		state->last_avrule_block = cur;
   2347 		cur = cur->next;
   2348 	}
   2349 	state->last_base_avrule_block = state->last_avrule_block;
   2350 	state->next_decl_id++;
   2351 
   2352 	/* allocate the table mapping from base's decl_id to its
   2353 	 * avrule_decls and set the initial mappings */
   2354 	free(state->base->decl_val_to_struct);
   2355 	if ((state->base->decl_val_to_struct =
   2356 	     calloc(state->next_decl_id + num_mod_decls,
   2357 		    sizeof(*(state->base->decl_val_to_struct)))) == NULL) {
   2358 		ERR(state->handle, "Out of memory!");
   2359 		return -1;
   2360 	}
   2361 	/* This allocates the decl block to module mapping used for error reporting */
   2362 	if ((state->decl_to_mod = calloc(state->next_decl_id + num_mod_decls,
   2363 					 sizeof(*(state->decl_to_mod)))) ==
   2364 	    NULL) {
   2365 		ERR(state->handle, "Out of memory!");
   2366 		return -1;
   2367 	}
   2368 	cur = state->base->global;
   2369 	while (cur != NULL) {
   2370 		avrule_decl_t *decl = cur->branch_list;
   2371 		while (decl != NULL) {
   2372 			state->base->decl_val_to_struct[decl->decl_id - 1] =
   2373 			    decl;
   2374 			state->decl_to_mod[decl->decl_id] = state->base;
   2375 			decl = decl->next;
   2376 		}
   2377 		cur = cur->next;
   2378 	}
   2379 
   2380 	/* normalize conditionals within */
   2381 	if (cond_normalize(state->base) < 0) {
   2382 		ERR(state->handle,
   2383 		    "Error while normalizing conditionals within the base module.");
   2384 		return -1;
   2385 	}
   2386 	return 0;
   2387 }
   2388 
   2389 static int expand_role_attributes(hashtab_key_t key, hashtab_datum_t datum,
   2390 				  void * data)
   2391 {
   2392 	char *id;
   2393 	role_datum_t *role, *sub_attr;
   2394 	link_state_t *state;
   2395 	unsigned int i;
   2396 	ebitmap_node_t *rnode;
   2397 
   2398 	id = key;
   2399 	role = (role_datum_t *)datum;
   2400 	state = (link_state_t *)data;
   2401 
   2402 	if (strcmp(id, OBJECT_R) == 0){
   2403 		/* object_r is never a role attribute by far */
   2404 		return 0;
   2405 	}
   2406 
   2407 	if (role->flavor != ROLE_ATTRIB)
   2408 		return 0;
   2409 
   2410 	if (state->verbose)
   2411 		INFO(state->handle, "expanding role attribute %s", id);
   2412 
   2413 restart:
   2414 	ebitmap_for_each_bit(&role->roles, rnode, i) {
   2415 		if (ebitmap_node_get_bit(rnode, i)) {
   2416 			sub_attr = state->base->role_val_to_struct[i];
   2417 			if (sub_attr->flavor != ROLE_ATTRIB)
   2418 				continue;
   2419 
   2420 			/* remove the sub role attribute from the parent
   2421 			 * role attribute's roles ebitmap */
   2422 			if (ebitmap_set_bit(&role->roles, i, 0))
   2423 				return -1;
   2424 
   2425 			/* loop dependency of role attributes */
   2426 			if (sub_attr->s.value == role->s.value)
   2427 				continue;
   2428 
   2429 			/* now go on to expand a sub role attribute
   2430 			 * by escalating its roles ebitmap */
   2431 			if (ebitmap_union(&role->roles, &sub_attr->roles)) {
   2432 				ERR(state->handle, "Out of memory!");
   2433 				return -1;
   2434 			}
   2435 
   2436 			/* sub_attr->roles may contain other role attributes,
   2437 			 * re-scan the parent role attribute's roles ebitmap */
   2438 			goto restart;
   2439 		}
   2440 	}
   2441 
   2442 	return 0;
   2443 }
   2444 
   2445 /* For any role attribute in a declaration's local symtab[SYM_ROLES] table,
   2446  * copy its roles ebitmap into its duplicate's in the base->p_roles.table.
   2447  */
   2448 static int populate_decl_roleattributes(hashtab_key_t key,
   2449 					hashtab_datum_t datum,
   2450 					void *data)
   2451 {
   2452 	char *id = key;
   2453 	role_datum_t *decl_role, *base_role;
   2454 	link_state_t *state = (link_state_t *)data;
   2455 
   2456 	decl_role = (role_datum_t *)datum;
   2457 
   2458 	if (strcmp(id, OBJECT_R) == 0) {
   2459 		/* object_r is never a role attribute by far */
   2460 		return 0;
   2461 	}
   2462 
   2463 	if (decl_role->flavor != ROLE_ATTRIB)
   2464 		return 0;
   2465 
   2466 	base_role = (role_datum_t *)hashtab_search(state->base->p_roles.table,
   2467 						   id);
   2468 	assert(base_role != NULL && base_role->flavor == ROLE_ATTRIB);
   2469 
   2470 	if (ebitmap_union(&base_role->roles, &decl_role->roles)) {
   2471 		ERR(state->handle, "Out of memory!");
   2472 		return -1;
   2473 	}
   2474 
   2475 	return 0;
   2476 }
   2477 
   2478 static int populate_roleattributes(link_state_t *state, policydb_t *pol)
   2479 {
   2480 	avrule_block_t *block;
   2481 	avrule_decl_t *decl;
   2482 
   2483 	if (state->verbose)
   2484 		INFO(state->handle, "Populating role-attribute relationship "
   2485 			    "from enabled declarations' local symtab.");
   2486 
   2487 	/* Iterate through all of the blocks skipping the first(which is the
   2488 	 * global block, is required to be present and can't have an else).
   2489 	 * If the block is disabled or not having an enabled decl, skip it.
   2490 	 */
   2491 	for (block = pol->global->next; block != NULL; block = block->next)
   2492 	{
   2493 		decl = block->enabled;
   2494 		if (decl == NULL || decl->enabled == 0)
   2495 			continue;
   2496 
   2497 		if (hashtab_map(decl->symtab[SYM_ROLES].table,
   2498 				populate_decl_roleattributes, state))
   2499 			return -1;
   2500 	}
   2501 
   2502 	return 0;
   2503 }
   2504 
   2505 /* Link a set of modules into a base module. This process is somewhat
   2506  * similar to an actual compiler: it requires a set of order dependent
   2507  * steps.  The base and every module must have been indexed prior to
   2508  * calling this function.
   2509  */
   2510 int link_modules(sepol_handle_t * handle,
   2511 		 policydb_t * b, policydb_t ** mods, int len, int verbose)
   2512 {
   2513 	int i, ret, retval = -1;
   2514 	policy_module_t **modules = NULL;
   2515 	link_state_t state;
   2516 	uint32_t num_mod_decls = 0;
   2517 
   2518 	memset(&state, 0, sizeof(state));
   2519 	state.base = b;
   2520 	state.verbose = verbose;
   2521 	state.handle = handle;
   2522 
   2523 	if (b->policy_type != POLICY_BASE) {
   2524 		ERR(state.handle, "Target of link was not a base policy.");
   2525 		return -1;
   2526 	}
   2527 
   2528 	/* first allocate some space to hold the maps from module
   2529 	 * symbol's value to the destination symbol value; then do
   2530 	 * other preparation work */
   2531 	if ((modules =
   2532 	     (policy_module_t **) calloc(len, sizeof(*modules))) == NULL) {
   2533 		ERR(state.handle, "Out of memory!");
   2534 		return -1;
   2535 	}
   2536 	for (i = 0; i < len; i++) {
   2537 		if (mods[i]->policy_type != POLICY_MOD) {
   2538 			ERR(state.handle,
   2539 			    "Tried to link in a policy that was not a module.");
   2540 			goto cleanup;
   2541 		}
   2542 
   2543 		if (mods[i]->mls != b->mls) {
   2544 			if (b->mls)
   2545 				ERR(state.handle,
   2546 				    "Tried to link in a non-MLS module with an MLS base.");
   2547 			else
   2548 				ERR(state.handle,
   2549 				    "Tried to link in an MLS module with a non-MLS base.");
   2550 			goto cleanup;
   2551 		}
   2552 
   2553 		if ((modules[i] =
   2554 		     (policy_module_t *) calloc(1,
   2555 						sizeof(policy_module_t))) ==
   2556 		    NULL) {
   2557 			ERR(state.handle, "Out of memory!");
   2558 			goto cleanup;
   2559 		}
   2560 		modules[i]->policy = mods[i];
   2561 		if (prepare_module(&state, modules[i]) == -1) {
   2562 			goto cleanup;
   2563 		}
   2564 		num_mod_decls += modules[i]->num_decls;
   2565 	}
   2566 	if (prepare_base(&state, num_mod_decls) == -1) {
   2567 		goto cleanup;
   2568 	}
   2569 
   2570 	/* copy all types, declared and required */
   2571 	for (i = 0; i < len; i++) {
   2572 		state.cur = modules[i];
   2573 		state.cur_mod_name = modules[i]->policy->name;
   2574 		ret =
   2575 		    hashtab_map(modules[i]->policy->p_types.table,
   2576 				type_copy_callback, &state);
   2577 		if (ret) {
   2578 			retval = ret;
   2579 			goto cleanup;
   2580 		}
   2581 	}
   2582 
   2583 	/* then copy everything else, including aliases, and fixup attributes */
   2584 	for (i = 0; i < len; i++) {
   2585 		state.cur = modules[i];
   2586 		state.cur_mod_name = modules[i]->policy->name;
   2587 		ret =
   2588 		    copy_identifiers(&state, modules[i]->policy->symtab, NULL);
   2589 		if (ret) {
   2590 			retval = ret;
   2591 			goto cleanup;
   2592 		}
   2593 	}
   2594 
   2595 	if (policydb_index_others(state.handle, state.base, 0)) {
   2596 		ERR(state.handle, "Error while indexing others");
   2597 		goto cleanup;
   2598 	}
   2599 
   2600 	/* copy and remap the module's data over to base */
   2601 	for (i = 0; i < len; i++) {
   2602 		state.cur = modules[i];
   2603 		ret = copy_module(&state, modules[i]);
   2604 		if (ret) {
   2605 			retval = ret;
   2606 			goto cleanup;
   2607 		}
   2608 	}
   2609 
   2610 	/* re-index base, for symbols were added to symbol tables  */
   2611 	if (policydb_index_classes(state.base)) {
   2612 		ERR(state.handle, "Error while indexing classes");
   2613 		goto cleanup;
   2614 	}
   2615 	if (policydb_index_others(state.handle, state.base, 0)) {
   2616 		ERR(state.handle, "Error while indexing others");
   2617 		goto cleanup;
   2618 	}
   2619 
   2620 	if (enable_avrules(&state, state.base)) {
   2621 		retval = SEPOL_EREQ;
   2622 		goto cleanup;
   2623 	}
   2624 
   2625 	/* Now that all role attribute's roles ebitmap have been settled,
   2626 	 * escalate sub role attribute's roles ebitmap into that of parent.
   2627 	 *
   2628 	 * First, since some role-attribute relationships could be recorded
   2629 	 * in some decl's local symtab(see get_local_role()), we need to
   2630 	 * populate them up to the base.p_roles table. */
   2631 	if (populate_roleattributes(&state, state.base)) {
   2632 		retval = SEPOL_EREQ;
   2633 		goto cleanup;
   2634 	}
   2635 
   2636 	/* Now do the escalation. */
   2637 	if (hashtab_map(state.base->p_roles.table, expand_role_attributes,
   2638 			&state))
   2639 		goto cleanup;
   2640 
   2641 	retval = 0;
   2642       cleanup:
   2643 	for (i = 0; modules != NULL && i < len; i++) {
   2644 		policy_module_destroy(modules[i]);
   2645 	}
   2646 	free(modules);
   2647 	free(state.decl_to_mod);
   2648 	return retval;
   2649 }
   2650